##// END OF EJS Templates
Merge pull request #2100 from Carreau/2to3fixes...
Bussonnier Matthias -
r7844:0369b784 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,214 +1,215 b''
1 1 # encoding: utf-8
2 2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3 3
4 4 Authors:
5 5
6 6 * Fernando Perez
7 7 * Brian E. Granger
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 12 # Copyright (C) 2008-2011 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 from __future__ import print_function
21 22
22 23 import os
23 24 import sys
24 25 import traceback
25 26 from pprint import pformat
26 27
27 28 from IPython.core import ultratb
28 29 from IPython.core.release import author_email
29 30 from IPython.utils.sysinfo import sys_info
30 31
31 32 #-----------------------------------------------------------------------------
32 33 # Code
33 34 #-----------------------------------------------------------------------------
34 35
35 36 # Template for the user message.
36 37 _default_message_template = """\
37 38 Oops, {app_name} crashed. We do our best to make it stable, but...
38 39
39 40 A crash report was automatically generated with the following information:
40 41 - A verbatim copy of the crash traceback.
41 42 - A copy of your input history during this session.
42 43 - Data on your current {app_name} configuration.
43 44
44 45 It was left in the file named:
45 46 \t'{crash_report_fname}'
46 47 If you can email this file to the developers, the information in it will help
47 48 them in understanding and correcting the problem.
48 49
49 50 You can mail it to: {contact_name} at {contact_email}
50 51 with the subject '{app_name} Crash Report'.
51 52
52 53 If you want to do it now, the following command will work (under Unix):
53 54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
54 55
55 56 To ensure accurate tracking of this issue, please file a report about it at:
56 57 {bug_tracker}
57 58 """
58 59
59 60 _lite_message_template = """
60 61 If you suspect this is an IPython bug, please report it at:
61 62 https://github.com/ipython/ipython/issues
62 63 or send an email to the mailing list at {email}
63 64
64 65 You can print a more detailed traceback right now with "%tb", or use "%debug"
65 66 to interactively debug it.
66 67
67 68 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
68 69 {config}Application.verbose_crash=True
69 70 """
70 71
71 72
72 73 class CrashHandler(object):
73 74 """Customizable crash handlers for IPython applications.
74 75
75 76 Instances of this class provide a :meth:`__call__` method which can be
76 77 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
77 78
78 79 def __call__(self, etype, evalue, etb)
79 80 """
80 81
81 82 message_template = _default_message_template
82 83 section_sep = '\n\n'+'*'*75+'\n\n'
83 84
84 85 def __init__(self, app, contact_name=None, contact_email=None,
85 86 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
86 87 """Create a new crash handler
87 88
88 89 Parameters
89 90 ----------
90 91 app : Application
91 92 A running :class:`Application` instance, which will be queried at
92 93 crash time for internal information.
93 94
94 95 contact_name : str
95 96 A string with the name of the person to contact.
96 97
97 98 contact_email : str
98 99 A string with the email address of the contact.
99 100
100 101 bug_tracker : str
101 102 A string with the URL for your project's bug tracker.
102 103
103 104 show_crash_traceback : bool
104 105 If false, don't print the crash traceback on stderr, only generate
105 106 the on-disk report
106 107
107 108 Non-argument instance attributes:
108 109
109 110 These instances contain some non-argument attributes which allow for
110 111 further customization of the crash handler's behavior. Please see the
111 112 source for further details.
112 113 """
113 114 self.crash_report_fname = "Crash_report_%s.txt" % app.name
114 115 self.app = app
115 116 self.call_pdb = call_pdb
116 117 #self.call_pdb = True # dbg
117 118 self.show_crash_traceback = show_crash_traceback
118 119 self.info = dict(app_name = app.name,
119 120 contact_name = contact_name,
120 121 contact_email = contact_email,
121 122 bug_tracker = bug_tracker,
122 123 crash_report_fname = self.crash_report_fname)
123 124
124 125
125 126 def __call__(self, etype, evalue, etb):
126 127 """Handle an exception, call for compatible with sys.excepthook"""
127 128
128 129 # do not allow the crash handler to be called twice without reinstalling it
129 130 # this prevents unlikely errors in the crash handling from entering an
130 131 # infinite loop.
131 132 sys.excepthook = sys.__excepthook__
132 133
133 134 # Report tracebacks shouldn't use color in general (safer for users)
134 135 color_scheme = 'NoColor'
135 136
136 137 # Use this ONLY for developer debugging (keep commented out for release)
137 138 #color_scheme = 'Linux' # dbg
138 139 try:
139 140 rptdir = self.app.ipython_dir
140 141 except:
141 142 rptdir = os.getcwdu()
142 143 if rptdir is None or not os.path.isdir(rptdir):
143 144 rptdir = os.getcwdu()
144 145 report_name = os.path.join(rptdir,self.crash_report_fname)
145 146 # write the report filename into the instance dict so it can get
146 147 # properly expanded out in the user message template
147 148 self.crash_report_fname = report_name
148 149 self.info['crash_report_fname'] = report_name
149 150 TBhandler = ultratb.VerboseTB(
150 151 color_scheme=color_scheme,
151 152 long_header=1,
152 153 call_pdb=self.call_pdb,
153 154 )
154 155 if self.call_pdb:
155 156 TBhandler(etype,evalue,etb)
156 157 return
157 158 else:
158 159 traceback = TBhandler.text(etype,evalue,etb,context=31)
159 160
160 161 # print traceback to screen
161 162 if self.show_crash_traceback:
162 print >> sys.stderr, traceback
163 print(traceback, file=sys.stderr)
163 164
164 165 # and generate a complete report on disk
165 166 try:
166 167 report = open(report_name,'w')
167 168 except:
168 print >> sys.stderr, 'Could not create crash report on disk.'
169 print('Could not create crash report on disk.', file=sys.stderr)
169 170 return
170 171
171 172 # Inform user on stderr of what happened
172 print >> sys.stderr, '\n'+'*'*70+'\n'
173 print >> sys.stderr, self.message_template.format(**self.info)
173 print('\n'+'*'*70+'\n', file=sys.stderr)
174 print(self.message_template.format(**self.info), file=sys.stderr)
174 175
175 176 # Construct report on disk
176 177 report.write(self.make_report(traceback))
177 178 report.close()
178 179 raw_input("Hit <Enter> to quit (your terminal may close):")
179 180
180 181 def make_report(self,traceback):
181 182 """Return a string containing a crash report."""
182 183
183 184 sec_sep = self.section_sep
184 185
185 186 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
186 187 rpt_add = report.append
187 188 rpt_add(sys_info())
188 189
189 190 try:
190 191 config = pformat(self.app.config)
191 192 rpt_add(sec_sep)
192 193 rpt_add('Application name: %s\n\n' % self.app_name)
193 194 rpt_add('Current user configuration structure:\n\n')
194 195 rpt_add(config)
195 196 except:
196 197 pass
197 198 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
198 199
199 200 return ''.join(report)
200 201
201 202
202 203 def crash_handler_lite(etype, evalue, tb):
203 204 """a light excepthook, adding a small message to the usual traceback"""
204 205 traceback.print_exception(etype, evalue, tb)
205 206
206 207 from IPython.core.interactiveshell import InteractiveShell
207 208 if InteractiveShell.initialized():
208 209 # we are in a Shell environment, give %magic example
209 210 config = "%config "
210 211 else:
211 212 # we are not in a shell, show generic config
212 213 config = "c."
213 print >> sys.stderr, _lite_message_template.format(email=author_email, config=config)
214 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
214 215
@@ -1,525 +1,526 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 http://www.python.org/2.2.3/license.html"""
17 17
18 18 #*****************************************************************************
19 19 #
20 20 # This file is licensed under the PSF license.
21 21 #
22 22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 24 #
25 25 #
26 26 #*****************************************************************************
27 from __future__ import print_function
27 28
28 29 import bdb
29 30 import linecache
30 31 import sys
31 32
32 33 from IPython.utils import PyColorize
33 34 from IPython.core import ipapi
34 35 from IPython.utils import coloransi, io
35 36 from IPython.core.excolors import exception_colors
36 37
37 38 # See if we can use pydb.
38 39 has_pydb = False
39 40 prompt = 'ipdb> '
40 41 #We have to check this directly from sys.argv, config struct not yet available
41 42 if '--pydb' in sys.argv:
42 43 try:
43 44 import pydb
44 45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
45 46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
46 47 # better protect against it.
47 48 has_pydb = True
48 49 except ImportError:
49 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
50 print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available")
50 51
51 52 if has_pydb:
52 53 from pydb import Pdb as OldPdb
53 54 #print "Using pydb for %run -d and post-mortem" #dbg
54 55 prompt = 'ipydb> '
55 56 else:
56 57 from pdb import Pdb as OldPdb
57 58
58 59 # Allow the set_trace code to operate outside of an ipython instance, even if
59 60 # it does so with some limitations. The rest of this support is implemented in
60 61 # the Tracer constructor.
61 62 def BdbQuit_excepthook(et,ev,tb):
62 63 if et==bdb.BdbQuit:
63 print 'Exiting Debugger.'
64 print('Exiting Debugger.')
64 65 else:
65 66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66 67
67 68 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
68 print 'Exiting Debugger.'
69 print('Exiting Debugger.')
69 70
70 71
71 72 class Tracer(object):
72 73 """Class for local debugging, similar to pdb.set_trace.
73 74
74 75 Instances of this class, when called, behave like pdb.set_trace, but
75 76 providing IPython's enhanced capabilities.
76 77
77 78 This is implemented as a class which must be initialized in your own code
78 79 and not as a standalone function because we need to detect at runtime
79 80 whether IPython is already active or not. That detection is done in the
80 81 constructor, ensuring that this code plays nicely with a running IPython,
81 82 while functioning acceptably (though with limitations) if outside of it.
82 83 """
83 84
84 85 def __init__(self,colors=None):
85 86 """Create a local debugger instance.
86 87
87 88 :Parameters:
88 89
89 90 - `colors` (None): a string containing the name of the color scheme to
90 91 use, it must be one of IPython's valid color schemes. If not given, the
91 92 function will default to the current IPython scheme when running inside
92 93 IPython, and to 'NoColor' otherwise.
93 94
94 95 Usage example:
95 96
96 97 from IPython.core.debugger import Tracer; debug_here = Tracer()
97 98
98 99 ... later in your code
99 100 debug_here() # -> will open up the debugger at that point.
100 101
101 102 Once the debugger activates, you can use all of its regular commands to
102 103 step through code, set breakpoints, etc. See the pdb documentation
103 104 from the Python standard library for usage details.
104 105 """
105 106
106 107 try:
107 108 ip = get_ipython()
108 109 except NameError:
109 110 # Outside of ipython, we set our own exception hook manually
110 111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 112 sys.excepthook = BdbQuit_excepthook
112 113 def_colors = 'NoColor'
113 114 try:
114 115 # Limited tab completion support
115 116 import readline
116 117 readline.parse_and_bind('tab: complete')
117 118 except ImportError:
118 119 pass
119 120 else:
120 121 # In ipython, we use its custom exception handler mechanism
121 122 def_colors = ip.colors
122 123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
123 124
124 125 if colors is None:
125 126 colors = def_colors
126 127
127 128 # The stdlib debugger internally uses a modified repr from the `repr`
128 129 # module, that limits the length of printed strings to a hardcoded
129 130 # limit of 30 characters. That much trimming is too aggressive, let's
130 131 # at least raise that limit to 80 chars, which should be enough for
131 132 # most interactive uses.
132 133 try:
133 134 from repr import aRepr
134 135 aRepr.maxstring = 80
135 136 except:
136 137 # This is only a user-facing convenience, so any error we encounter
137 138 # here can be warned about but can be otherwise ignored. These
138 139 # printouts will tell us about problems if this API changes
139 140 import traceback
140 141 traceback.print_exc()
141 142
142 143 self.debugger = Pdb(colors)
143 144
144 145 def __call__(self):
145 146 """Starts an interactive debugger at the point where called.
146 147
147 148 This is similar to the pdb.set_trace() function from the std lib, but
148 149 using IPython's enhanced debugger."""
149 150
150 151 self.debugger.set_trace(sys._getframe().f_back)
151 152
152 153
153 154 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
154 155 """Make new_fn have old_fn's doc string. This is particularly useful
155 156 for the do_... commands that hook into the help system.
156 157 Adapted from from a comp.lang.python posting
157 158 by Duncan Booth."""
158 159 def wrapper(*args, **kw):
159 160 return new_fn(*args, **kw)
160 161 if old_fn.__doc__:
161 162 wrapper.__doc__ = old_fn.__doc__ + additional_text
162 163 return wrapper
163 164
164 165
165 166 def _file_lines(fname):
166 167 """Return the contents of a named file as a list of lines.
167 168
168 169 This function never raises an IOError exception: if the file can't be
169 170 read, it simply returns an empty list."""
170 171
171 172 try:
172 173 outfile = open(fname)
173 174 except IOError:
174 175 return []
175 176 else:
176 177 out = outfile.readlines()
177 178 outfile.close()
178 179 return out
179 180
180 181
181 182 class Pdb(OldPdb):
182 183 """Modified Pdb class, does not load readline."""
183 184
184 185 def __init__(self,color_scheme='NoColor',completekey=None,
185 186 stdin=None, stdout=None):
186 187
187 188 # Parent constructor:
188 189 if has_pydb and completekey is None:
189 190 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
190 191 else:
191 192 OldPdb.__init__(self,completekey,stdin,stdout)
192 193
193 194 self.prompt = prompt # The default prompt is '(Pdb)'
194 195
195 196 # IPython changes...
196 197 self.is_pydb = has_pydb
197 198
198 199 self.shell = ipapi.get()
199 200
200 201 if self.is_pydb:
201 202
202 203 # interactiveshell.py's ipalias seems to want pdb's checkline
203 204 # which located in pydb.fn
204 205 import pydb.fns
205 206 self.checkline = lambda filename, lineno: \
206 207 pydb.fns.checkline(self, filename, lineno)
207 208
208 209 self.curframe = None
209 210 self.do_restart = self.new_do_restart
210 211
211 212 self.old_all_completions = self.shell.Completer.all_completions
212 213 self.shell.Completer.all_completions=self.all_completions
213 214
214 215 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
215 216 OldPdb.do_list)
216 217 self.do_l = self.do_list
217 218 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
218 219 OldPdb.do_frame)
219 220
220 221 self.aliases = {}
221 222
222 223 # Create color table: we copy the default one from the traceback
223 224 # module and add a few attributes needed for debugging
224 225 self.color_scheme_table = exception_colors()
225 226
226 227 # shorthands
227 228 C = coloransi.TermColors
228 229 cst = self.color_scheme_table
229 230
230 231 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
231 232 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
232 233
233 234 cst['Linux'].colors.breakpoint_enabled = C.LightRed
234 235 cst['Linux'].colors.breakpoint_disabled = C.Red
235 236
236 237 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
237 238 cst['LightBG'].colors.breakpoint_disabled = C.Red
238 239
239 240 self.set_colors(color_scheme)
240 241
241 242 # Add a python parser so we can syntax highlight source while
242 243 # debugging.
243 244 self.parser = PyColorize.Parser()
244 245
245 246 def set_colors(self, scheme):
246 247 """Shorthand access to the color table scheme selector method."""
247 248 self.color_scheme_table.set_active_scheme(scheme)
248 249
249 250 def interaction(self, frame, traceback):
250 251 self.shell.set_completer_frame(frame)
251 252 OldPdb.interaction(self, frame, traceback)
252 253
253 254 def new_do_up(self, arg):
254 255 OldPdb.do_up(self, arg)
255 256 self.shell.set_completer_frame(self.curframe)
256 257 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
257 258
258 259 def new_do_down(self, arg):
259 260 OldPdb.do_down(self, arg)
260 261 self.shell.set_completer_frame(self.curframe)
261 262
262 263 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
263 264
264 265 def new_do_frame(self, arg):
265 266 OldPdb.do_frame(self, arg)
266 267 self.shell.set_completer_frame(self.curframe)
267 268
268 269 def new_do_quit(self, arg):
269 270
270 271 if hasattr(self, 'old_all_completions'):
271 272 self.shell.Completer.all_completions=self.old_all_completions
272 273
273 274
274 275 return OldPdb.do_quit(self, arg)
275 276
276 277 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
277 278
278 279 def new_do_restart(self, arg):
279 280 """Restart command. In the context of ipython this is exactly the same
280 281 thing as 'quit'."""
281 282 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
282 283 return self.do_quit(arg)
283 284
284 285 def postloop(self):
285 286 self.shell.set_completer_frame(None)
286 287
287 288 def print_stack_trace(self):
288 289 try:
289 290 for frame_lineno in self.stack:
290 291 self.print_stack_entry(frame_lineno, context = 5)
291 292 except KeyboardInterrupt:
292 293 pass
293 294
294 295 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
295 296 context = 3):
296 297 #frame, lineno = frame_lineno
297 print >>io.stdout, self.format_stack_entry(frame_lineno, '', context)
298 print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout)
298 299
299 300 # vds: >>
300 301 frame, lineno = frame_lineno
301 302 filename = frame.f_code.co_filename
302 303 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
303 304 # vds: <<
304 305
305 306 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
306 307 import linecache, repr
307 308
308 309 ret = []
309 310
310 311 Colors = self.color_scheme_table.active_colors
311 312 ColorsNormal = Colors.Normal
312 313 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
313 314 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
314 315 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
315 316 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
316 317 ColorsNormal)
317 318
318 319 frame, lineno = frame_lineno
319 320
320 321 return_value = ''
321 322 if '__return__' in frame.f_locals:
322 323 rv = frame.f_locals['__return__']
323 324 #return_value += '->'
324 325 return_value += repr.repr(rv) + '\n'
325 326 ret.append(return_value)
326 327
327 328 #s = filename + '(' + `lineno` + ')'
328 329 filename = self.canonic(frame.f_code.co_filename)
329 330 link = tpl_link % filename
330 331
331 332 if frame.f_code.co_name:
332 333 func = frame.f_code.co_name
333 334 else:
334 335 func = "<lambda>"
335 336
336 337 call = ''
337 338 if func != '?':
338 339 if '__args__' in frame.f_locals:
339 340 args = repr.repr(frame.f_locals['__args__'])
340 341 else:
341 342 args = '()'
342 343 call = tpl_call % (func, args)
343 344
344 345 # The level info should be generated in the same format pdb uses, to
345 346 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
346 347 if frame is self.curframe:
347 348 ret.append('> ')
348 349 else:
349 350 ret.append(' ')
350 351 ret.append('%s(%s)%s\n' % (link,lineno,call))
351 352
352 353 start = lineno - 1 - context//2
353 354 lines = linecache.getlines(filename)
354 355 start = max(start, 0)
355 356 start = min(start, len(lines) - context)
356 357 lines = lines[start : start + context]
357 358
358 359 for i,line in enumerate(lines):
359 360 show_arrow = (start + 1 + i == lineno)
360 361 linetpl = (frame is self.curframe or show_arrow) \
361 362 and tpl_line_em \
362 363 or tpl_line
363 364 ret.append(self.__format_line(linetpl, filename,
364 365 start + 1 + i, line,
365 366 arrow = show_arrow) )
366 367
367 368 return ''.join(ret)
368 369
369 370 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
370 371 bp_mark = ""
371 372 bp_mark_color = ""
372 373
373 374 scheme = self.color_scheme_table.active_scheme_name
374 375 new_line, err = self.parser.format2(line, 'str', scheme)
375 376 if not err: line = new_line
376 377
377 378 bp = None
378 379 if lineno in self.get_file_breaks(filename):
379 380 bps = self.get_breaks(filename, lineno)
380 381 bp = bps[-1]
381 382
382 383 if bp:
383 384 Colors = self.color_scheme_table.active_colors
384 385 bp_mark = str(bp.number)
385 386 bp_mark_color = Colors.breakpoint_enabled
386 387 if not bp.enabled:
387 388 bp_mark_color = Colors.breakpoint_disabled
388 389
389 390 numbers_width = 7
390 391 if arrow:
391 392 # This is the line with the error
392 393 pad = numbers_width - len(str(lineno)) - len(bp_mark)
393 394 if pad >= 3:
394 395 marker = '-'*(pad-3) + '-> '
395 396 elif pad == 2:
396 397 marker = '> '
397 398 elif pad == 1:
398 399 marker = '>'
399 400 else:
400 401 marker = ''
401 402 num = '%s%s' % (marker, str(lineno))
402 403 line = tpl_line % (bp_mark_color + bp_mark, num, line)
403 404 else:
404 405 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
405 406 line = tpl_line % (bp_mark_color + bp_mark, num, line)
406 407
407 408 return line
408 409
409 410 def list_command_pydb(self, arg):
410 411 """List command to use if we have a newer pydb installed"""
411 412 filename, first, last = OldPdb.parse_list_cmd(self, arg)
412 413 if filename is not None:
413 414 self.print_list_lines(filename, first, last)
414 415
415 416 def print_list_lines(self, filename, first, last):
416 417 """The printing (as opposed to the parsing part of a 'list'
417 418 command."""
418 419 try:
419 420 Colors = self.color_scheme_table.active_colors
420 421 ColorsNormal = Colors.Normal
421 422 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
422 423 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
423 424 src = []
424 425 for lineno in range(first, last+1):
425 426 line = linecache.getline(filename, lineno)
426 427 if not line:
427 428 break
428 429
429 430 if lineno == self.curframe.f_lineno:
430 431 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
431 432 else:
432 433 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
433 434
434 435 src.append(line)
435 436 self.lineno = lineno
436 437
437 print >>io.stdout, ''.join(src)
438 print(''.join(src), file=io.stdout)
438 439
439 440 except KeyboardInterrupt:
440 441 pass
441 442
442 443 def do_list(self, arg):
443 444 self.lastcmd = 'list'
444 445 last = None
445 446 if arg:
446 447 try:
447 448 x = eval(arg, {}, {})
448 449 if type(x) == type(()):
449 450 first, last = x
450 451 first = int(first)
451 452 last = int(last)
452 453 if last < first:
453 454 # Assume it's a count
454 455 last = first + last
455 456 else:
456 457 first = max(1, int(x) - 5)
457 458 except:
458 print '*** Error in argument:', `arg`
459 print('*** Error in argument:', repr(arg))
459 460 return
460 461 elif self.lineno is None:
461 462 first = max(1, self.curframe.f_lineno - 5)
462 463 else:
463 464 first = self.lineno + 1
464 465 if last is None:
465 466 last = first + 10
466 467 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
467 468
468 469 # vds: >>
469 470 lineno = first
470 471 filename = self.curframe.f_code.co_filename
471 472 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
472 473 # vds: <<
473 474
474 475 do_l = do_list
475 476
476 477 def do_pdef(self, arg):
477 478 """The debugger interface to magic_pdef"""
478 479 namespaces = [('Locals', self.curframe.f_locals),
479 480 ('Globals', self.curframe.f_globals)]
480 481 self.shell.magic_pdef(arg, namespaces=namespaces)
481 482
482 483 def do_pdoc(self, arg):
483 484 """The debugger interface to magic_pdoc"""
484 485 namespaces = [('Locals', self.curframe.f_locals),
485 486 ('Globals', self.curframe.f_globals)]
486 487 self.shell.magic_pdoc(arg, namespaces=namespaces)
487 488
488 489 def do_pinfo(self, arg):
489 490 """The debugger equivalant of ?obj"""
490 491 namespaces = [('Locals', self.curframe.f_locals),
491 492 ('Globals', self.curframe.f_globals)]
492 493 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
493 494
494 495 def checkline(self, filename, lineno):
495 496 """Check whether specified line seems to be executable.
496 497
497 498 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
498 499 line or EOF). Warning: testing is not comprehensive.
499 500 """
500 501 #######################################################################
501 502 # XXX Hack! Use python-2.5 compatible code for this call, because with
502 503 # all of our changes, we've drifted from the pdb api in 2.6. For now,
503 504 # changing:
504 505 #
505 506 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
506 507 # to:
507 508 #
508 509 line = linecache.getline(filename, lineno)
509 510 #
510 511 # does the trick. But in reality, we need to fix this by reconciling
511 512 # our updates with the new Pdb APIs in Python 2.6.
512 513 #
513 514 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
514 515 #######################################################################
515 516
516 517 if not line:
517 print >>self.stdout, 'End of file'
518 print('End of file', file=self.stdout)
518 519 return 0
519 520 line = line.strip()
520 521 # Don't allow setting breakpoint at a blank line
521 522 if (not line or (line[0] == '#') or
522 523 (line[:3] == '"""') or line[:3] == "'''"):
523 print >>self.stdout, '*** Blank or comment'
524 print('*** Blank or comment', file=self.stdout)
524 525 return 0
525 526 return lineno
@@ -1,269 +1,270 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5
6 6 Authors:
7 7
8 8 * Fernando Perez
9 9 * Brian Granger
10 10 * Robert Kern
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Copyright (C) 2008-2011 The IPython Development Team
15 15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 from __future__ import print_function
24 25
25 26 import __builtin__
26 27
27 28 from IPython.config.configurable import Configurable
28 29 from IPython.utils import io
29 30 from IPython.utils.traitlets import Instance, List
30 31 from IPython.utils.warn import warn
31 32
32 33 #-----------------------------------------------------------------------------
33 34 # Main displayhook class
34 35 #-----------------------------------------------------------------------------
35 36
36 37 # TODO: Move the various attributes (cache_size, [others now moved]). Some
37 38 # of these are also attributes of InteractiveShell. They should be on ONE object
38 39 # only and the other objects should ask that one object for their values.
39 40
40 41 class DisplayHook(Configurable):
41 42 """The custom IPython displayhook to replace sys.displayhook.
42 43
43 44 This class does many things, but the basic idea is that it is a callable
44 45 that gets called anytime user code returns a value.
45 46 """
46 47
47 48 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
48 49
49 50 def __init__(self, shell=None, cache_size=1000, config=None):
50 51 super(DisplayHook, self).__init__(shell=shell, config=config)
51 52
52 53 cache_size_min = 3
53 54 if cache_size <= 0:
54 55 self.do_full_cache = 0
55 56 cache_size = 0
56 57 elif cache_size < cache_size_min:
57 58 self.do_full_cache = 0
58 59 cache_size = 0
59 60 warn('caching was disabled (min value for cache size is %s).' %
60 61 cache_size_min,level=3)
61 62 else:
62 63 self.do_full_cache = 1
63 64
64 65 self.cache_size = cache_size
65 66
66 67 # we need a reference to the user-level namespace
67 68 self.shell = shell
68 69
69 70 self._,self.__,self.___ = '','',''
70 71
71 72 # these are deliberately global:
72 73 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
73 74 self.shell.user_ns.update(to_user_ns)
74 75
75 76 @property
76 77 def prompt_count(self):
77 78 return self.shell.execution_count
78 79
79 80 #-------------------------------------------------------------------------
80 81 # Methods used in __call__. Override these methods to modify the behavior
81 82 # of the displayhook.
82 83 #-------------------------------------------------------------------------
83 84
84 85 def check_for_underscore(self):
85 86 """Check if the user has set the '_' variable by hand."""
86 87 # If something injected a '_' variable in __builtin__, delete
87 88 # ipython's automatic one so we don't clobber that. gettext() in
88 89 # particular uses _, so we need to stay away from it.
89 90 if '_' in __builtin__.__dict__:
90 91 try:
91 92 del self.shell.user_ns['_']
92 93 except KeyError:
93 94 pass
94 95
95 96 def quiet(self):
96 97 """Should we silence the display hook because of ';'?"""
97 98 # do not print output if input ends in ';'
98 99 try:
99 100 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
100 101 if cell.rstrip().endswith(';'):
101 102 return True
102 103 except IndexError:
103 104 # some uses of ipshellembed may fail here
104 105 pass
105 106 return False
106 107
107 108 def start_displayhook(self):
108 109 """Start the displayhook, initializing resources."""
109 110 pass
110 111
111 112 def write_output_prompt(self):
112 113 """Write the output prompt.
113 114
114 115 The default implementation simply writes the prompt to
115 116 ``io.stdout``.
116 117 """
117 118 # Use write, not print which adds an extra space.
118 119 io.stdout.write(self.shell.separate_out)
119 120 outprompt = self.shell.prompt_manager.render('out')
120 121 if self.do_full_cache:
121 122 io.stdout.write(outprompt)
122 123
123 124 def compute_format_data(self, result):
124 125 """Compute format data of the object to be displayed.
125 126
126 127 The format data is a generalization of the :func:`repr` of an object.
127 128 In the default implementation the format data is a :class:`dict` of
128 129 key value pair where the keys are valid MIME types and the values
129 130 are JSON'able data structure containing the raw data for that MIME
130 131 type. It is up to frontends to determine pick a MIME to to use and
131 132 display that data in an appropriate manner.
132 133
133 134 This method only computes the format data for the object and should
134 135 NOT actually print or write that to a stream.
135 136
136 137 Parameters
137 138 ----------
138 139 result : object
139 140 The Python object passed to the display hook, whose format will be
140 141 computed.
141 142
142 143 Returns
143 144 -------
144 145 format_data : dict
145 146 A :class:`dict` whose keys are valid MIME types and values are
146 147 JSON'able raw data for that MIME type. It is recommended that
147 148 all return values of this should always include the "text/plain"
148 149 MIME type representation of the object.
149 150 """
150 151 return self.shell.display_formatter.format(result)
151 152
152 153 def write_format_data(self, format_dict):
153 154 """Write the format data dict to the frontend.
154 155
155 156 This default version of this method simply writes the plain text
156 157 representation of the object to ``io.stdout``. Subclasses should
157 158 override this method to send the entire `format_dict` to the
158 159 frontends.
159 160
160 161 Parameters
161 162 ----------
162 163 format_dict : dict
163 164 The format dict for the object passed to `sys.displayhook`.
164 165 """
165 166 # We want to print because we want to always make sure we have a
166 167 # newline, even if all the prompt separators are ''. This is the
167 168 # standard IPython behavior.
168 169 result_repr = format_dict['text/plain']
169 170 if '\n' in result_repr:
170 171 # So that multi-line strings line up with the left column of
171 172 # the screen, instead of having the output prompt mess up
172 173 # their first line.
173 174 # We use the prompt template instead of the expanded prompt
174 175 # because the expansion may add ANSI escapes that will interfere
175 176 # with our ability to determine whether or not we should add
176 177 # a newline.
177 178 prompt_template = self.shell.prompt_manager.out_template
178 179 if prompt_template and not prompt_template.endswith('\n'):
179 180 # But avoid extraneous empty lines.
180 181 result_repr = '\n' + result_repr
181 182
182 print >>io.stdout, result_repr
183 print(result_repr, file=io.stdout)
183 184
184 185 def update_user_ns(self, result):
185 186 """Update user_ns with various things like _, __, _1, etc."""
186 187
187 188 # Avoid recursive reference when displaying _oh/Out
188 189 if result is not self.shell.user_ns['_oh']:
189 190 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
190 191 warn('Output cache limit (currently '+
191 `self.cache_size`+' entries) hit.\n'
192 repr(self.cache_size)+' entries) hit.\n'
192 193 'Flushing cache and resetting history counter...\n'
193 194 'The only history variables available will be _,__,___ and _1\n'
194 195 'with the current result.')
195 196
196 197 self.flush()
197 198 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
198 199 # we cause buggy behavior for things like gettext).
199 200
200 201 if '_' not in __builtin__.__dict__:
201 202 self.___ = self.__
202 203 self.__ = self._
203 204 self._ = result
204 205 self.shell.push({'_':self._,
205 206 '__':self.__,
206 207 '___':self.___}, interactive=False)
207 208
208 209 # hackish access to top-level namespace to create _1,_2... dynamically
209 210 to_main = {}
210 211 if self.do_full_cache:
211 new_result = '_'+`self.prompt_count`
212 new_result = '_'+repr(self.prompt_count)
212 213 to_main[new_result] = result
213 214 self.shell.push(to_main, interactive=False)
214 215 self.shell.user_ns['_oh'][self.prompt_count] = result
215 216
216 217 def log_output(self, format_dict):
217 218 """Log the output."""
218 219 if self.shell.logger.log_output:
219 220 self.shell.logger.log_write(format_dict['text/plain'], 'output')
220 221 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
221 222 format_dict['text/plain']
222 223
223 224 def finish_displayhook(self):
224 225 """Finish up all displayhook activities."""
225 226 io.stdout.write(self.shell.separate_out2)
226 227 io.stdout.flush()
227 228
228 229 def __call__(self, result=None):
229 230 """Printing with history cache management.
230 231
231 232 This is invoked everytime the interpreter needs to print, and is
232 233 activated by setting the variable sys.displayhook to it.
233 234 """
234 235 self.check_for_underscore()
235 236 if result is not None and not self.quiet():
236 237 self.start_displayhook()
237 238 self.write_output_prompt()
238 239 format_dict = self.compute_format_data(result)
239 240 self.write_format_data(format_dict)
240 241 self.update_user_ns(result)
241 242 self.log_output(format_dict)
242 243 self.finish_displayhook()
243 244
244 245 def flush(self):
245 246 if not self.do_full_cache:
246 raise ValueError,"You shouldn't have reached the cache flush "\
247 "if full caching is not enabled!"
247 raise ValueError("You shouldn't have reached the cache flush "
248 "if full caching is not enabled!")
248 249 # delete auto-generated vars from global namespace
249 250
250 251 for n in range(1,self.prompt_count + 1):
251 key = '_'+`n`
252 key = '_'+repr(n)
252 253 try:
253 254 del self.shell.user_ns[key]
254 255 except: pass
255 256 # In some embedded circumstances, the user_ns doesn't have the
256 257 # '_oh' key set up.
257 258 oh = self.shell.user_ns.get('_oh', None)
258 259 if oh is not None:
259 260 oh.clear()
260 261
261 262 # Release our own references to objects:
262 263 self._, self.__, self.___ = '', '', ''
263 264
264 265 if '_' not in __builtin__.__dict__:
265 266 self.shell.user_ns.update({'_':None,'__':None, '___':None})
266 267 import gc
267 268 # TODO: Is this really needed?
268 269 gc.collect()
269 270
@@ -1,3005 +1,3006 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 from __future__ import print_function
19 20
20 21 import __builtin__ as builtin_mod
21 22 import __future__
22 23 import abc
23 24 import ast
24 25 import atexit
25 26 import os
26 27 import re
27 28 import runpy
28 29 import sys
29 30 import tempfile
30 31 import types
31 32
32 33 # We need to use nested to support python 2.6, once we move to >=2.7, we can
33 34 # use the with keyword's new builtin support for nested managers
34 35 try:
35 36 from contextlib import nested
36 37 except:
37 38 from IPython.utils.nested_context import nested
38 39
39 40 from IPython.config.configurable import SingletonConfigurable
40 41 from IPython.core import debugger, oinspect
41 42 from IPython.core import history as ipcorehist
42 43 from IPython.core import magic
43 44 from IPython.core import page
44 45 from IPython.core import prefilter
45 46 from IPython.core import shadowns
46 47 from IPython.core import ultratb
47 48 from IPython.core.alias import AliasManager, AliasError
48 49 from IPython.core.autocall import ExitAutocall
49 50 from IPython.core.builtin_trap import BuiltinTrap
50 51 from IPython.core.compilerop import CachingCompiler
51 52 from IPython.core.display_trap import DisplayTrap
52 53 from IPython.core.displayhook import DisplayHook
53 54 from IPython.core.displaypub import DisplayPublisher
54 55 from IPython.core.error import UsageError
55 56 from IPython.core.extensions import ExtensionManager
56 57 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
57 58 from IPython.core.formatters import DisplayFormatter
58 59 from IPython.core.history import HistoryManager
59 60 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
60 61 from IPython.core.logger import Logger
61 62 from IPython.core.macro import Macro
62 63 from IPython.core.payload import PayloadManager
63 64 from IPython.core.plugin import PluginManager
64 65 from IPython.core.prefilter import PrefilterManager
65 66 from IPython.core.profiledir import ProfileDir
66 67 from IPython.core.pylabtools import pylab_activate
67 68 from IPython.core.prompts import PromptManager
68 69 from IPython.utils import PyColorize
69 70 from IPython.utils import io
70 71 from IPython.utils import py3compat
71 72 from IPython.utils import openpy
72 73 from IPython.utils.doctestreload import doctest_reload
73 74 from IPython.utils.io import ask_yes_no
74 75 from IPython.utils.ipstruct import Struct
75 76 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
76 77 from IPython.utils.pickleshare import PickleShareDB
77 78 from IPython.utils.process import system, getoutput
78 79 from IPython.utils.strdispatch import StrDispatch
79 80 from IPython.utils.syspathcontext import prepended_to_syspath
80 81 from IPython.utils.text import (format_screen, LSString, SList,
81 82 DollarFormatter)
82 83 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
83 84 List, Unicode, Instance, Type)
84 85 from IPython.utils.warn import warn, error
85 86 import IPython.core.hooks
86 87
87 88 # FIXME: do this in a function to avoid circular dependencies
88 89 # A better solution is to remove IPython.parallel.error,
89 90 # and place those classes in IPython.core.error.
90 91
91 92 class RemoteError(Exception):
92 93 pass
93 94
94 95 def _import_remote_error():
95 96 global RemoteError
96 97 try:
97 98 from IPython.parallel.error import RemoteError
98 99 except:
99 100 pass
100 101
101 102 _import_remote_error()
102 103
103 104 #-----------------------------------------------------------------------------
104 105 # Globals
105 106 #-----------------------------------------------------------------------------
106 107
107 108 # compiled regexps for autoindent management
108 109 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
109 110
110 111 #-----------------------------------------------------------------------------
111 112 # Utilities
112 113 #-----------------------------------------------------------------------------
113 114
114 115 def softspace(file, newvalue):
115 116 """Copied from code.py, to remove the dependency"""
116 117
117 118 oldvalue = 0
118 119 try:
119 120 oldvalue = file.softspace
120 121 except AttributeError:
121 122 pass
122 123 try:
123 124 file.softspace = newvalue
124 125 except (AttributeError, TypeError):
125 126 # "attribute-less object" or "read-only attributes"
126 127 pass
127 128 return oldvalue
128 129
129 130
130 131 def no_op(*a, **kw): pass
131 132
132 133 class NoOpContext(object):
133 134 def __enter__(self): pass
134 135 def __exit__(self, type, value, traceback): pass
135 136 no_op_context = NoOpContext()
136 137
137 138 class SpaceInInput(Exception): pass
138 139
139 140 class Bunch: pass
140 141
141 142
142 143 def get_default_colors():
143 144 if sys.platform=='darwin':
144 145 return "LightBG"
145 146 elif os.name=='nt':
146 147 return 'Linux'
147 148 else:
148 149 return 'Linux'
149 150
150 151
151 152 class SeparateUnicode(Unicode):
152 153 """A Unicode subclass to validate separate_in, separate_out, etc.
153 154
154 155 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
155 156 """
156 157
157 158 def validate(self, obj, value):
158 159 if value == '0': value = ''
159 160 value = value.replace('\\n','\n')
160 161 return super(SeparateUnicode, self).validate(obj, value)
161 162
162 163
163 164 class ReadlineNoRecord(object):
164 165 """Context manager to execute some code, then reload readline history
165 166 so that interactive input to the code doesn't appear when pressing up."""
166 167 def __init__(self, shell):
167 168 self.shell = shell
168 169 self._nested_level = 0
169 170
170 171 def __enter__(self):
171 172 if self._nested_level == 0:
172 173 try:
173 174 self.orig_length = self.current_length()
174 175 self.readline_tail = self.get_readline_tail()
175 176 except (AttributeError, IndexError): # Can fail with pyreadline
176 177 self.orig_length, self.readline_tail = 999999, []
177 178 self._nested_level += 1
178 179
179 180 def __exit__(self, type, value, traceback):
180 181 self._nested_level -= 1
181 182 if self._nested_level == 0:
182 183 # Try clipping the end if it's got longer
183 184 try:
184 185 e = self.current_length() - self.orig_length
185 186 if e > 0:
186 187 for _ in range(e):
187 188 self.shell.readline.remove_history_item(self.orig_length)
188 189
189 190 # If it still doesn't match, just reload readline history.
190 191 if self.current_length() != self.orig_length \
191 192 or self.get_readline_tail() != self.readline_tail:
192 193 self.shell.refill_readline_hist()
193 194 except (AttributeError, IndexError):
194 195 pass
195 196 # Returning False will cause exceptions to propagate
196 197 return False
197 198
198 199 def current_length(self):
199 200 return self.shell.readline.get_current_history_length()
200 201
201 202 def get_readline_tail(self, n=10):
202 203 """Get the last n items in readline history."""
203 204 end = self.shell.readline.get_current_history_length() + 1
204 205 start = max(end-n, 1)
205 206 ghi = self.shell.readline.get_history_item
206 207 return [ghi(x) for x in range(start, end)]
207 208
208 209 #-----------------------------------------------------------------------------
209 210 # Main IPython class
210 211 #-----------------------------------------------------------------------------
211 212
212 213 class InteractiveShell(SingletonConfigurable):
213 214 """An enhanced, interactive shell for Python."""
214 215
215 216 _instance = None
216 217
217 218 autocall = Enum((0,1,2), default_value=0, config=True, help=
218 219 """
219 220 Make IPython automatically call any callable object even if you didn't
220 221 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
221 222 automatically. The value can be '0' to disable the feature, '1' for
222 223 'smart' autocall, where it is not applied if there are no more
223 224 arguments on the line, and '2' for 'full' autocall, where all callable
224 225 objects are automatically called (even if no arguments are present).
225 226 """
226 227 )
227 228 # TODO: remove all autoindent logic and put into frontends.
228 229 # We can't do this yet because even runlines uses the autoindent.
229 230 autoindent = CBool(True, config=True, help=
230 231 """
231 232 Autoindent IPython code entered interactively.
232 233 """
233 234 )
234 235 automagic = CBool(True, config=True, help=
235 236 """
236 237 Enable magic commands to be called without the leading %.
237 238 """
238 239 )
239 240 cache_size = Integer(1000, config=True, help=
240 241 """
241 242 Set the size of the output cache. The default is 1000, you can
242 243 change it permanently in your config file. Setting it to 0 completely
243 244 disables the caching system, and the minimum value accepted is 20 (if
244 245 you provide a value less than 20, it is reset to 0 and a warning is
245 246 issued). This limit is defined because otherwise you'll spend more
246 247 time re-flushing a too small cache than working
247 248 """
248 249 )
249 250 color_info = CBool(True, config=True, help=
250 251 """
251 252 Use colors for displaying information about objects. Because this
252 253 information is passed through a pager (like 'less'), and some pagers
253 254 get confused with color codes, this capability can be turned off.
254 255 """
255 256 )
256 257 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
257 258 default_value=get_default_colors(), config=True,
258 259 help="Set the color scheme (NoColor, Linux, or LightBG)."
259 260 )
260 261 colors_force = CBool(False, help=
261 262 """
262 263 Force use of ANSI color codes, regardless of OS and readline
263 264 availability.
264 265 """
265 266 # FIXME: This is essentially a hack to allow ZMQShell to show colors
266 267 # without readline on Win32. When the ZMQ formatting system is
267 268 # refactored, this should be removed.
268 269 )
269 270 debug = CBool(False, config=True)
270 271 deep_reload = CBool(False, config=True, help=
271 272 """
272 273 Enable deep (recursive) reloading by default. IPython can use the
273 274 deep_reload module which reloads changes in modules recursively (it
274 275 replaces the reload() function, so you don't need to change anything to
275 276 use it). deep_reload() forces a full reload of modules whose code may
276 277 have changed, which the default reload() function does not. When
277 278 deep_reload is off, IPython will use the normal reload(), but
278 279 deep_reload will still be available as dreload().
279 280 """
280 281 )
281 282 disable_failing_post_execute = CBool(False, config=True,
282 283 help="Don't call post-execute functions that have failed in the past."
283 284 )
284 285 display_formatter = Instance(DisplayFormatter)
285 286 displayhook_class = Type(DisplayHook)
286 287 display_pub_class = Type(DisplayPublisher)
287 288
288 289 exit_now = CBool(False)
289 290 exiter = Instance(ExitAutocall)
290 291 def _exiter_default(self):
291 292 return ExitAutocall(self)
292 293 # Monotonically increasing execution counter
293 294 execution_count = Integer(1)
294 295 filename = Unicode("<ipython console>")
295 296 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
296 297
297 298 # Input splitter, to split entire cells of input into either individual
298 299 # interactive statements or whole blocks.
299 300 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
300 301 (), {})
301 302 logstart = CBool(False, config=True, help=
302 303 """
303 304 Start logging to the default log file.
304 305 """
305 306 )
306 307 logfile = Unicode('', config=True, help=
307 308 """
308 309 The name of the logfile to use.
309 310 """
310 311 )
311 312 logappend = Unicode('', config=True, help=
312 313 """
313 314 Start logging to the given file in append mode.
314 315 """
315 316 )
316 317 object_info_string_level = Enum((0,1,2), default_value=0,
317 318 config=True)
318 319 pdb = CBool(False, config=True, help=
319 320 """
320 321 Automatically call the pdb debugger after every exception.
321 322 """
322 323 )
323 324 multiline_history = CBool(sys.platform != 'win32', config=True,
324 325 help="Save multi-line entries as one entry in readline history"
325 326 )
326 327
327 328 # deprecated prompt traits:
328 329
329 330 prompt_in1 = Unicode('In [\\#]: ', config=True,
330 331 help="Deprecated, use PromptManager.in_template")
331 332 prompt_in2 = Unicode(' .\\D.: ', config=True,
332 333 help="Deprecated, use PromptManager.in2_template")
333 334 prompt_out = Unicode('Out[\\#]: ', config=True,
334 335 help="Deprecated, use PromptManager.out_template")
335 336 prompts_pad_left = CBool(True, config=True,
336 337 help="Deprecated, use PromptManager.justify")
337 338
338 339 def _prompt_trait_changed(self, name, old, new):
339 340 table = {
340 341 'prompt_in1' : 'in_template',
341 342 'prompt_in2' : 'in2_template',
342 343 'prompt_out' : 'out_template',
343 344 'prompts_pad_left' : 'justify',
344 345 }
345 346 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
346 347 name=name, newname=table[name])
347 348 )
348 349 # protect against weird cases where self.config may not exist:
349 350 if self.config is not None:
350 351 # propagate to corresponding PromptManager trait
351 352 setattr(self.config.PromptManager, table[name], new)
352 353
353 354 _prompt_in1_changed = _prompt_trait_changed
354 355 _prompt_in2_changed = _prompt_trait_changed
355 356 _prompt_out_changed = _prompt_trait_changed
356 357 _prompt_pad_left_changed = _prompt_trait_changed
357 358
358 359 show_rewritten_input = CBool(True, config=True,
359 360 help="Show rewritten input, e.g. for autocall."
360 361 )
361 362
362 363 quiet = CBool(False, config=True)
363 364
364 365 history_length = Integer(10000, config=True)
365 366
366 367 # The readline stuff will eventually be moved to the terminal subclass
367 368 # but for now, we can't do that as readline is welded in everywhere.
368 369 readline_use = CBool(True, config=True)
369 370 readline_remove_delims = Unicode('-/~', config=True)
370 371 # don't use \M- bindings by default, because they
371 372 # conflict with 8-bit encodings. See gh-58,gh-88
372 373 readline_parse_and_bind = List([
373 374 'tab: complete',
374 375 '"\C-l": clear-screen',
375 376 'set show-all-if-ambiguous on',
376 377 '"\C-o": tab-insert',
377 378 '"\C-r": reverse-search-history',
378 379 '"\C-s": forward-search-history',
379 380 '"\C-p": history-search-backward',
380 381 '"\C-n": history-search-forward',
381 382 '"\e[A": history-search-backward',
382 383 '"\e[B": history-search-forward',
383 384 '"\C-k": kill-line',
384 385 '"\C-u": unix-line-discard',
385 386 ], allow_none=False, config=True)
386 387
387 388 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
388 389 default_value='last_expr', config=True,
389 390 help="""
390 391 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
391 392 run interactively (displaying output from expressions).""")
392 393
393 394 # TODO: this part of prompt management should be moved to the frontends.
394 395 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
395 396 separate_in = SeparateUnicode('\n', config=True)
396 397 separate_out = SeparateUnicode('', config=True)
397 398 separate_out2 = SeparateUnicode('', config=True)
398 399 wildcards_case_sensitive = CBool(True, config=True)
399 400 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
400 401 default_value='Context', config=True)
401 402
402 403 # Subcomponents of InteractiveShell
403 404 alias_manager = Instance('IPython.core.alias.AliasManager')
404 405 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
405 406 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
406 407 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
407 408 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
408 409 plugin_manager = Instance('IPython.core.plugin.PluginManager')
409 410 payload_manager = Instance('IPython.core.payload.PayloadManager')
410 411 history_manager = Instance('IPython.core.history.HistoryManager')
411 412 magics_manager = Instance('IPython.core.magic.MagicsManager')
412 413
413 414 profile_dir = Instance('IPython.core.application.ProfileDir')
414 415 @property
415 416 def profile(self):
416 417 if self.profile_dir is not None:
417 418 name = os.path.basename(self.profile_dir.location)
418 419 return name.replace('profile_','')
419 420
420 421
421 422 # Private interface
422 423 _post_execute = Instance(dict)
423 424
424 425 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
425 426 user_module=None, user_ns=None,
426 427 custom_exceptions=((), None)):
427 428
428 429 # This is where traits with a config_key argument are updated
429 430 # from the values on config.
430 431 super(InteractiveShell, self).__init__(config=config)
431 432 self.configurables = [self]
432 433
433 434 # These are relatively independent and stateless
434 435 self.init_ipython_dir(ipython_dir)
435 436 self.init_profile_dir(profile_dir)
436 437 self.init_instance_attrs()
437 438 self.init_environment()
438 439
439 440 # Check if we're in a virtualenv, and set up sys.path.
440 441 self.init_virtualenv()
441 442
442 443 # Create namespaces (user_ns, user_global_ns, etc.)
443 444 self.init_create_namespaces(user_module, user_ns)
444 445 # This has to be done after init_create_namespaces because it uses
445 446 # something in self.user_ns, but before init_sys_modules, which
446 447 # is the first thing to modify sys.
447 448 # TODO: When we override sys.stdout and sys.stderr before this class
448 449 # is created, we are saving the overridden ones here. Not sure if this
449 450 # is what we want to do.
450 451 self.save_sys_module_state()
451 452 self.init_sys_modules()
452 453
453 454 # While we're trying to have each part of the code directly access what
454 455 # it needs without keeping redundant references to objects, we have too
455 456 # much legacy code that expects ip.db to exist.
456 457 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
457 458
458 459 self.init_history()
459 460 self.init_encoding()
460 461 self.init_prefilter()
461 462
462 463 self.init_syntax_highlighting()
463 464 self.init_hooks()
464 465 self.init_pushd_popd_magic()
465 466 # self.init_traceback_handlers use to be here, but we moved it below
466 467 # because it and init_io have to come after init_readline.
467 468 self.init_user_ns()
468 469 self.init_logger()
469 470 self.init_alias()
470 471 self.init_builtins()
471 472
472 473 # The following was in post_config_initialization
473 474 self.init_inspector()
474 475 # init_readline() must come before init_io(), because init_io uses
475 476 # readline related things.
476 477 self.init_readline()
477 478 # We save this here in case user code replaces raw_input, but it needs
478 479 # to be after init_readline(), because PyPy's readline works by replacing
479 480 # raw_input.
480 481 if py3compat.PY3:
481 482 self.raw_input_original = input
482 483 else:
483 484 self.raw_input_original = raw_input
484 485 # init_completer must come after init_readline, because it needs to
485 486 # know whether readline is present or not system-wide to configure the
486 487 # completers, since the completion machinery can now operate
487 488 # independently of readline (e.g. over the network)
488 489 self.init_completer()
489 490 # TODO: init_io() needs to happen before init_traceback handlers
490 491 # because the traceback handlers hardcode the stdout/stderr streams.
491 492 # This logic in in debugger.Pdb and should eventually be changed.
492 493 self.init_io()
493 494 self.init_traceback_handlers(custom_exceptions)
494 495 self.init_prompts()
495 496 self.init_display_formatter()
496 497 self.init_display_pub()
497 498 self.init_displayhook()
498 499 self.init_reload_doctest()
499 500 self.init_magics()
500 501 self.init_logstart()
501 502 self.init_pdb()
502 503 self.init_extension_manager()
503 504 self.init_plugin_manager()
504 505 self.init_payload()
505 506 self.hooks.late_startup_hook()
506 507 atexit.register(self.atexit_operations)
507 508
508 509 def get_ipython(self):
509 510 """Return the currently running IPython instance."""
510 511 return self
511 512
512 513 #-------------------------------------------------------------------------
513 514 # Trait changed handlers
514 515 #-------------------------------------------------------------------------
515 516
516 517 def _ipython_dir_changed(self, name, new):
517 518 if not os.path.isdir(new):
518 519 os.makedirs(new, mode = 0777)
519 520
520 521 def set_autoindent(self,value=None):
521 522 """Set the autoindent flag, checking for readline support.
522 523
523 524 If called with no arguments, it acts as a toggle."""
524 525
525 526 if value != 0 and not self.has_readline:
526 527 if os.name == 'posix':
527 528 warn("The auto-indent feature requires the readline library")
528 529 self.autoindent = 0
529 530 return
530 531 if value is None:
531 532 self.autoindent = not self.autoindent
532 533 else:
533 534 self.autoindent = value
534 535
535 536 #-------------------------------------------------------------------------
536 537 # init_* methods called by __init__
537 538 #-------------------------------------------------------------------------
538 539
539 540 def init_ipython_dir(self, ipython_dir):
540 541 if ipython_dir is not None:
541 542 self.ipython_dir = ipython_dir
542 543 return
543 544
544 545 self.ipython_dir = get_ipython_dir()
545 546
546 547 def init_profile_dir(self, profile_dir):
547 548 if profile_dir is not None:
548 549 self.profile_dir = profile_dir
549 550 return
550 551 self.profile_dir =\
551 552 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
552 553
553 554 def init_instance_attrs(self):
554 555 self.more = False
555 556
556 557 # command compiler
557 558 self.compile = CachingCompiler()
558 559
559 560 # Make an empty namespace, which extension writers can rely on both
560 561 # existing and NEVER being used by ipython itself. This gives them a
561 562 # convenient location for storing additional information and state
562 563 # their extensions may require, without fear of collisions with other
563 564 # ipython names that may develop later.
564 565 self.meta = Struct()
565 566
566 567 # Temporary files used for various purposes. Deleted at exit.
567 568 self.tempfiles = []
568 569
569 570 # Keep track of readline usage (later set by init_readline)
570 571 self.has_readline = False
571 572
572 573 # keep track of where we started running (mainly for crash post-mortem)
573 574 # This is not being used anywhere currently.
574 575 self.starting_dir = os.getcwdu()
575 576
576 577 # Indentation management
577 578 self.indent_current_nsp = 0
578 579
579 580 # Dict to track post-execution functions that have been registered
580 581 self._post_execute = {}
581 582
582 583 def init_environment(self):
583 584 """Any changes we need to make to the user's environment."""
584 585 pass
585 586
586 587 def init_encoding(self):
587 588 # Get system encoding at startup time. Certain terminals (like Emacs
588 589 # under Win32 have it set to None, and we need to have a known valid
589 590 # encoding to use in the raw_input() method
590 591 try:
591 592 self.stdin_encoding = sys.stdin.encoding or 'ascii'
592 593 except AttributeError:
593 594 self.stdin_encoding = 'ascii'
594 595
595 596 def init_syntax_highlighting(self):
596 597 # Python source parser/formatter for syntax highlighting
597 598 pyformat = PyColorize.Parser().format
598 599 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
599 600
600 601 def init_pushd_popd_magic(self):
601 602 # for pushd/popd management
602 603 self.home_dir = get_home_dir()
603 604
604 605 self.dir_stack = []
605 606
606 607 def init_logger(self):
607 608 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
608 609 logmode='rotate')
609 610
610 611 def init_logstart(self):
611 612 """Initialize logging in case it was requested at the command line.
612 613 """
613 614 if self.logappend:
614 615 self.magic('logstart %s append' % self.logappend)
615 616 elif self.logfile:
616 617 self.magic('logstart %s' % self.logfile)
617 618 elif self.logstart:
618 619 self.magic('logstart')
619 620
620 621 def init_builtins(self):
621 622 # A single, static flag that we set to True. Its presence indicates
622 623 # that an IPython shell has been created, and we make no attempts at
623 624 # removing on exit or representing the existence of more than one
624 625 # IPython at a time.
625 626 builtin_mod.__dict__['__IPYTHON__'] = True
626 627
627 628 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
628 629 # manage on enter/exit, but with all our shells it's virtually
629 630 # impossible to get all the cases right. We're leaving the name in for
630 631 # those who adapted their codes to check for this flag, but will
631 632 # eventually remove it after a few more releases.
632 633 builtin_mod.__dict__['__IPYTHON__active'] = \
633 634 'Deprecated, check for __IPYTHON__'
634 635
635 636 self.builtin_trap = BuiltinTrap(shell=self)
636 637
637 638 def init_inspector(self):
638 639 # Object inspector
639 640 self.inspector = oinspect.Inspector(oinspect.InspectColors,
640 641 PyColorize.ANSICodeColors,
641 642 'NoColor',
642 643 self.object_info_string_level)
643 644
644 645 def init_io(self):
645 646 # This will just use sys.stdout and sys.stderr. If you want to
646 647 # override sys.stdout and sys.stderr themselves, you need to do that
647 648 # *before* instantiating this class, because io holds onto
648 649 # references to the underlying streams.
649 650 if sys.platform == 'win32' and self.has_readline:
650 651 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
651 652 else:
652 653 io.stdout = io.IOStream(sys.stdout)
653 654 io.stderr = io.IOStream(sys.stderr)
654 655
655 656 def init_prompts(self):
656 657 self.prompt_manager = PromptManager(shell=self, config=self.config)
657 658 self.configurables.append(self.prompt_manager)
658 659 # Set system prompts, so that scripts can decide if they are running
659 660 # interactively.
660 661 sys.ps1 = 'In : '
661 662 sys.ps2 = '...: '
662 663 sys.ps3 = 'Out: '
663 664
664 665 def init_display_formatter(self):
665 666 self.display_formatter = DisplayFormatter(config=self.config)
666 667 self.configurables.append(self.display_formatter)
667 668
668 669 def init_display_pub(self):
669 670 self.display_pub = self.display_pub_class(config=self.config)
670 671 self.configurables.append(self.display_pub)
671 672
672 673 def init_displayhook(self):
673 674 # Initialize displayhook, set in/out prompts and printing system
674 675 self.displayhook = self.displayhook_class(
675 676 config=self.config,
676 677 shell=self,
677 678 cache_size=self.cache_size,
678 679 )
679 680 self.configurables.append(self.displayhook)
680 681 # This is a context manager that installs/revmoes the displayhook at
681 682 # the appropriate time.
682 683 self.display_trap = DisplayTrap(hook=self.displayhook)
683 684
684 685 def init_reload_doctest(self):
685 686 # Do a proper resetting of doctest, including the necessary displayhook
686 687 # monkeypatching
687 688 try:
688 689 doctest_reload()
689 690 except ImportError:
690 691 warn("doctest module does not exist.")
691 692
692 693 def init_virtualenv(self):
693 694 """Add a virtualenv to sys.path so the user can import modules from it.
694 695 This isn't perfect: it doesn't use the Python interpreter with which the
695 696 virtualenv was built, and it ignores the --no-site-packages option. A
696 697 warning will appear suggesting the user installs IPython in the
697 698 virtualenv, but for many cases, it probably works well enough.
698 699
699 700 Adapted from code snippets online.
700 701
701 702 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
702 703 """
703 704 if 'VIRTUAL_ENV' not in os.environ:
704 705 # Not in a virtualenv
705 706 return
706 707
707 708 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
708 709 # Running properly in the virtualenv, don't need to do anything
709 710 return
710 711
711 712 warn("Attempting to work in a virtualenv. If you encounter problems, please "
712 713 "install IPython inside the virtualenv.\n")
713 714 if sys.platform == "win32":
714 715 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
715 716 else:
716 717 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
717 718 'python%d.%d' % sys.version_info[:2], 'site-packages')
718 719
719 720 import site
720 721 sys.path.insert(0, virtual_env)
721 722 site.addsitedir(virtual_env)
722 723
723 724 #-------------------------------------------------------------------------
724 725 # Things related to injections into the sys module
725 726 #-------------------------------------------------------------------------
726 727
727 728 def save_sys_module_state(self):
728 729 """Save the state of hooks in the sys module.
729 730
730 731 This has to be called after self.user_module is created.
731 732 """
732 733 self._orig_sys_module_state = {}
733 734 self._orig_sys_module_state['stdin'] = sys.stdin
734 735 self._orig_sys_module_state['stdout'] = sys.stdout
735 736 self._orig_sys_module_state['stderr'] = sys.stderr
736 737 self._orig_sys_module_state['excepthook'] = sys.excepthook
737 738 self._orig_sys_modules_main_name = self.user_module.__name__
738 739 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
739 740
740 741 def restore_sys_module_state(self):
741 742 """Restore the state of the sys module."""
742 743 try:
743 744 for k, v in self._orig_sys_module_state.iteritems():
744 745 setattr(sys, k, v)
745 746 except AttributeError:
746 747 pass
747 748 # Reset what what done in self.init_sys_modules
748 749 if self._orig_sys_modules_main_mod is not None:
749 750 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
750 751
751 752 #-------------------------------------------------------------------------
752 753 # Things related to hooks
753 754 #-------------------------------------------------------------------------
754 755
755 756 def init_hooks(self):
756 757 # hooks holds pointers used for user-side customizations
757 758 self.hooks = Struct()
758 759
759 760 self.strdispatchers = {}
760 761
761 762 # Set all default hooks, defined in the IPython.hooks module.
762 763 hooks = IPython.core.hooks
763 764 for hook_name in hooks.__all__:
764 765 # default hooks have priority 100, i.e. low; user hooks should have
765 766 # 0-100 priority
766 767 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
767 768
768 769 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
769 770 """set_hook(name,hook) -> sets an internal IPython hook.
770 771
771 772 IPython exposes some of its internal API as user-modifiable hooks. By
772 773 adding your function to one of these hooks, you can modify IPython's
773 774 behavior to call at runtime your own routines."""
774 775
775 776 # At some point in the future, this should validate the hook before it
776 777 # accepts it. Probably at least check that the hook takes the number
777 778 # of args it's supposed to.
778 779
779 780 f = types.MethodType(hook,self)
780 781
781 782 # check if the hook is for strdispatcher first
782 783 if str_key is not None:
783 784 sdp = self.strdispatchers.get(name, StrDispatch())
784 785 sdp.add_s(str_key, f, priority )
785 786 self.strdispatchers[name] = sdp
786 787 return
787 788 if re_key is not None:
788 789 sdp = self.strdispatchers.get(name, StrDispatch())
789 790 sdp.add_re(re.compile(re_key), f, priority )
790 791 self.strdispatchers[name] = sdp
791 792 return
792 793
793 794 dp = getattr(self.hooks, name, None)
794 795 if name not in IPython.core.hooks.__all__:
795 print "Warning! Hook '%s' is not one of %s" % \
796 (name, IPython.core.hooks.__all__ )
796 print("Warning! Hook '%s' is not one of %s" % \
797 (name, IPython.core.hooks.__all__ ))
797 798 if not dp:
798 799 dp = IPython.core.hooks.CommandChainDispatcher()
799 800
800 801 try:
801 802 dp.add(f,priority)
802 803 except AttributeError:
803 804 # it was not commandchain, plain old func - replace
804 805 dp = f
805 806
806 807 setattr(self.hooks,name, dp)
807 808
808 809 def register_post_execute(self, func):
809 810 """Register a function for calling after code execution.
810 811 """
811 812 if not callable(func):
812 813 raise ValueError('argument %s must be callable' % func)
813 814 self._post_execute[func] = True
814 815
815 816 #-------------------------------------------------------------------------
816 817 # Things related to the "main" module
817 818 #-------------------------------------------------------------------------
818 819
819 820 def new_main_mod(self,ns=None):
820 821 """Return a new 'main' module object for user code execution.
821 822 """
822 823 main_mod = self._user_main_module
823 824 init_fakemod_dict(main_mod,ns)
824 825 return main_mod
825 826
826 827 def cache_main_mod(self,ns,fname):
827 828 """Cache a main module's namespace.
828 829
829 830 When scripts are executed via %run, we must keep a reference to the
830 831 namespace of their __main__ module (a FakeModule instance) around so
831 832 that Python doesn't clear it, rendering objects defined therein
832 833 useless.
833 834
834 835 This method keeps said reference in a private dict, keyed by the
835 836 absolute path of the module object (which corresponds to the script
836 837 path). This way, for multiple executions of the same script we only
837 838 keep one copy of the namespace (the last one), thus preventing memory
838 839 leaks from old references while allowing the objects from the last
839 840 execution to be accessible.
840 841
841 842 Note: we can not allow the actual FakeModule instances to be deleted,
842 843 because of how Python tears down modules (it hard-sets all their
843 844 references to None without regard for reference counts). This method
844 845 must therefore make a *copy* of the given namespace, to allow the
845 846 original module's __dict__ to be cleared and reused.
846 847
847 848
848 849 Parameters
849 850 ----------
850 851 ns : a namespace (a dict, typically)
851 852
852 853 fname : str
853 854 Filename associated with the namespace.
854 855
855 856 Examples
856 857 --------
857 858
858 859 In [10]: import IPython
859 860
860 861 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
861 862
862 863 In [12]: IPython.__file__ in _ip._main_ns_cache
863 864 Out[12]: True
864 865 """
865 866 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
866 867
867 868 def clear_main_mod_cache(self):
868 869 """Clear the cache of main modules.
869 870
870 871 Mainly for use by utilities like %reset.
871 872
872 873 Examples
873 874 --------
874 875
875 876 In [15]: import IPython
876 877
877 878 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
878 879
879 880 In [17]: len(_ip._main_ns_cache) > 0
880 881 Out[17]: True
881 882
882 883 In [18]: _ip.clear_main_mod_cache()
883 884
884 885 In [19]: len(_ip._main_ns_cache) == 0
885 886 Out[19]: True
886 887 """
887 888 self._main_ns_cache.clear()
888 889
889 890 #-------------------------------------------------------------------------
890 891 # Things related to debugging
891 892 #-------------------------------------------------------------------------
892 893
893 894 def init_pdb(self):
894 895 # Set calling of pdb on exceptions
895 896 # self.call_pdb is a property
896 897 self.call_pdb = self.pdb
897 898
898 899 def _get_call_pdb(self):
899 900 return self._call_pdb
900 901
901 902 def _set_call_pdb(self,val):
902 903
903 904 if val not in (0,1,False,True):
904 raise ValueError,'new call_pdb value must be boolean'
905 raise ValueError('new call_pdb value must be boolean')
905 906
906 907 # store value in instance
907 908 self._call_pdb = val
908 909
909 910 # notify the actual exception handlers
910 911 self.InteractiveTB.call_pdb = val
911 912
912 913 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
913 914 'Control auto-activation of pdb at exceptions')
914 915
915 916 def debugger(self,force=False):
916 917 """Call the pydb/pdb debugger.
917 918
918 919 Keywords:
919 920
920 921 - force(False): by default, this routine checks the instance call_pdb
921 922 flag and does not actually invoke the debugger if the flag is false.
922 923 The 'force' option forces the debugger to activate even if the flag
923 924 is false.
924 925 """
925 926
926 927 if not (force or self.call_pdb):
927 928 return
928 929
929 930 if not hasattr(sys,'last_traceback'):
930 931 error('No traceback has been produced, nothing to debug.')
931 932 return
932 933
933 934 # use pydb if available
934 935 if debugger.has_pydb:
935 936 from pydb import pm
936 937 else:
937 938 # fallback to our internal debugger
938 939 pm = lambda : self.InteractiveTB.debugger(force=True)
939 940
940 941 with self.readline_no_record:
941 942 pm()
942 943
943 944 #-------------------------------------------------------------------------
944 945 # Things related to IPython's various namespaces
945 946 #-------------------------------------------------------------------------
946 947 default_user_namespaces = True
947 948
948 949 def init_create_namespaces(self, user_module=None, user_ns=None):
949 950 # Create the namespace where the user will operate. user_ns is
950 951 # normally the only one used, and it is passed to the exec calls as
951 952 # the locals argument. But we do carry a user_global_ns namespace
952 953 # given as the exec 'globals' argument, This is useful in embedding
953 954 # situations where the ipython shell opens in a context where the
954 955 # distinction between locals and globals is meaningful. For
955 956 # non-embedded contexts, it is just the same object as the user_ns dict.
956 957
957 958 # FIXME. For some strange reason, __builtins__ is showing up at user
958 959 # level as a dict instead of a module. This is a manual fix, but I
959 960 # should really track down where the problem is coming from. Alex
960 961 # Schmolck reported this problem first.
961 962
962 963 # A useful post by Alex Martelli on this topic:
963 964 # Re: inconsistent value from __builtins__
964 965 # Von: Alex Martelli <aleaxit@yahoo.com>
965 966 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
966 967 # Gruppen: comp.lang.python
967 968
968 969 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
969 970 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
970 971 # > <type 'dict'>
971 972 # > >>> print type(__builtins__)
972 973 # > <type 'module'>
973 974 # > Is this difference in return value intentional?
974 975
975 976 # Well, it's documented that '__builtins__' can be either a dictionary
976 977 # or a module, and it's been that way for a long time. Whether it's
977 978 # intentional (or sensible), I don't know. In any case, the idea is
978 979 # that if you need to access the built-in namespace directly, you
979 980 # should start with "import __builtin__" (note, no 's') which will
980 981 # definitely give you a module. Yeah, it's somewhat confusing:-(.
981 982
982 983 # These routines return a properly built module and dict as needed by
983 984 # the rest of the code, and can also be used by extension writers to
984 985 # generate properly initialized namespaces.
985 986 if (user_ns is not None) or (user_module is not None):
986 987 self.default_user_namespaces = False
987 988 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
988 989
989 990 # A record of hidden variables we have added to the user namespace, so
990 991 # we can list later only variables defined in actual interactive use.
991 992 self.user_ns_hidden = set()
992 993
993 994 # Now that FakeModule produces a real module, we've run into a nasty
994 995 # problem: after script execution (via %run), the module where the user
995 996 # code ran is deleted. Now that this object is a true module (needed
996 997 # so docetst and other tools work correctly), the Python module
997 998 # teardown mechanism runs over it, and sets to None every variable
998 999 # present in that module. Top-level references to objects from the
999 1000 # script survive, because the user_ns is updated with them. However,
1000 1001 # calling functions defined in the script that use other things from
1001 1002 # the script will fail, because the function's closure had references
1002 1003 # to the original objects, which are now all None. So we must protect
1003 1004 # these modules from deletion by keeping a cache.
1004 1005 #
1005 1006 # To avoid keeping stale modules around (we only need the one from the
1006 1007 # last run), we use a dict keyed with the full path to the script, so
1007 1008 # only the last version of the module is held in the cache. Note,
1008 1009 # however, that we must cache the module *namespace contents* (their
1009 1010 # __dict__). Because if we try to cache the actual modules, old ones
1010 1011 # (uncached) could be destroyed while still holding references (such as
1011 1012 # those held by GUI objects that tend to be long-lived)>
1012 1013 #
1013 1014 # The %reset command will flush this cache. See the cache_main_mod()
1014 1015 # and clear_main_mod_cache() methods for details on use.
1015 1016
1016 1017 # This is the cache used for 'main' namespaces
1017 1018 self._main_ns_cache = {}
1018 1019 # And this is the single instance of FakeModule whose __dict__ we keep
1019 1020 # copying and clearing for reuse on each %run
1020 1021 self._user_main_module = FakeModule()
1021 1022
1022 1023 # A table holding all the namespaces IPython deals with, so that
1023 1024 # introspection facilities can search easily.
1024 1025 self.ns_table = {'user_global':self.user_module.__dict__,
1025 1026 'user_local':self.user_ns,
1026 1027 'builtin':builtin_mod.__dict__
1027 1028 }
1028 1029
1029 1030 @property
1030 1031 def user_global_ns(self):
1031 1032 return self.user_module.__dict__
1032 1033
1033 1034 def prepare_user_module(self, user_module=None, user_ns=None):
1034 1035 """Prepare the module and namespace in which user code will be run.
1035 1036
1036 1037 When IPython is started normally, both parameters are None: a new module
1037 1038 is created automatically, and its __dict__ used as the namespace.
1038 1039
1039 1040 If only user_module is provided, its __dict__ is used as the namespace.
1040 1041 If only user_ns is provided, a dummy module is created, and user_ns
1041 1042 becomes the global namespace. If both are provided (as they may be
1042 1043 when embedding), user_ns is the local namespace, and user_module
1043 1044 provides the global namespace.
1044 1045
1045 1046 Parameters
1046 1047 ----------
1047 1048 user_module : module, optional
1048 1049 The current user module in which IPython is being run. If None,
1049 1050 a clean module will be created.
1050 1051 user_ns : dict, optional
1051 1052 A namespace in which to run interactive commands.
1052 1053
1053 1054 Returns
1054 1055 -------
1055 1056 A tuple of user_module and user_ns, each properly initialised.
1056 1057 """
1057 1058 if user_module is None and user_ns is not None:
1058 1059 user_ns.setdefault("__name__", "__main__")
1059 1060 class DummyMod(object):
1060 1061 "A dummy module used for IPython's interactive namespace."
1061 1062 pass
1062 1063 user_module = DummyMod()
1063 1064 user_module.__dict__ = user_ns
1064 1065
1065 1066 if user_module is None:
1066 1067 user_module = types.ModuleType("__main__",
1067 1068 doc="Automatically created module for IPython interactive environment")
1068 1069
1069 1070 # We must ensure that __builtin__ (without the final 's') is always
1070 1071 # available and pointing to the __builtin__ *module*. For more details:
1071 1072 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1072 1073 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1073 1074 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1074 1075
1075 1076 if user_ns is None:
1076 1077 user_ns = user_module.__dict__
1077 1078
1078 1079 return user_module, user_ns
1079 1080
1080 1081 def init_sys_modules(self):
1081 1082 # We need to insert into sys.modules something that looks like a
1082 1083 # module but which accesses the IPython namespace, for shelve and
1083 1084 # pickle to work interactively. Normally they rely on getting
1084 1085 # everything out of __main__, but for embedding purposes each IPython
1085 1086 # instance has its own private namespace, so we can't go shoving
1086 1087 # everything into __main__.
1087 1088
1088 1089 # note, however, that we should only do this for non-embedded
1089 1090 # ipythons, which really mimic the __main__.__dict__ with their own
1090 1091 # namespace. Embedded instances, on the other hand, should not do
1091 1092 # this because they need to manage the user local/global namespaces
1092 1093 # only, but they live within a 'normal' __main__ (meaning, they
1093 1094 # shouldn't overtake the execution environment of the script they're
1094 1095 # embedded in).
1095 1096
1096 1097 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1097 1098 main_name = self.user_module.__name__
1098 1099 sys.modules[main_name] = self.user_module
1099 1100
1100 1101 def init_user_ns(self):
1101 1102 """Initialize all user-visible namespaces to their minimum defaults.
1102 1103
1103 1104 Certain history lists are also initialized here, as they effectively
1104 1105 act as user namespaces.
1105 1106
1106 1107 Notes
1107 1108 -----
1108 1109 All data structures here are only filled in, they are NOT reset by this
1109 1110 method. If they were not empty before, data will simply be added to
1110 1111 therm.
1111 1112 """
1112 1113 # This function works in two parts: first we put a few things in
1113 1114 # user_ns, and we sync that contents into user_ns_hidden so that these
1114 1115 # initial variables aren't shown by %who. After the sync, we add the
1115 1116 # rest of what we *do* want the user to see with %who even on a new
1116 1117 # session (probably nothing, so theye really only see their own stuff)
1117 1118
1118 1119 # The user dict must *always* have a __builtin__ reference to the
1119 1120 # Python standard __builtin__ namespace, which must be imported.
1120 1121 # This is so that certain operations in prompt evaluation can be
1121 1122 # reliably executed with builtins. Note that we can NOT use
1122 1123 # __builtins__ (note the 's'), because that can either be a dict or a
1123 1124 # module, and can even mutate at runtime, depending on the context
1124 1125 # (Python makes no guarantees on it). In contrast, __builtin__ is
1125 1126 # always a module object, though it must be explicitly imported.
1126 1127
1127 1128 # For more details:
1128 1129 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1129 1130 ns = dict()
1130 1131
1131 1132 # Put 'help' in the user namespace
1132 1133 try:
1133 1134 from site import _Helper
1134 1135 ns['help'] = _Helper()
1135 1136 except ImportError:
1136 1137 warn('help() not available - check site.py')
1137 1138
1138 1139 # make global variables for user access to the histories
1139 1140 ns['_ih'] = self.history_manager.input_hist_parsed
1140 1141 ns['_oh'] = self.history_manager.output_hist
1141 1142 ns['_dh'] = self.history_manager.dir_hist
1142 1143
1143 1144 ns['_sh'] = shadowns
1144 1145
1145 1146 # user aliases to input and output histories. These shouldn't show up
1146 1147 # in %who, as they can have very large reprs.
1147 1148 ns['In'] = self.history_manager.input_hist_parsed
1148 1149 ns['Out'] = self.history_manager.output_hist
1149 1150
1150 1151 # Store myself as the public api!!!
1151 1152 ns['get_ipython'] = self.get_ipython
1152 1153
1153 1154 ns['exit'] = self.exiter
1154 1155 ns['quit'] = self.exiter
1155 1156
1156 1157 # Sync what we've added so far to user_ns_hidden so these aren't seen
1157 1158 # by %who
1158 1159 self.user_ns_hidden.update(ns)
1159 1160
1160 1161 # Anything put into ns now would show up in %who. Think twice before
1161 1162 # putting anything here, as we really want %who to show the user their
1162 1163 # stuff, not our variables.
1163 1164
1164 1165 # Finally, update the real user's namespace
1165 1166 self.user_ns.update(ns)
1166 1167
1167 1168 @property
1168 1169 def all_ns_refs(self):
1169 1170 """Get a list of references to all the namespace dictionaries in which
1170 1171 IPython might store a user-created object.
1171 1172
1172 1173 Note that this does not include the displayhook, which also caches
1173 1174 objects from the output."""
1174 1175 return [self.user_ns, self.user_global_ns,
1175 1176 self._user_main_module.__dict__] + self._main_ns_cache.values()
1176 1177
1177 1178 def reset(self, new_session=True):
1178 1179 """Clear all internal namespaces, and attempt to release references to
1179 1180 user objects.
1180 1181
1181 1182 If new_session is True, a new history session will be opened.
1182 1183 """
1183 1184 # Clear histories
1184 1185 self.history_manager.reset(new_session)
1185 1186 # Reset counter used to index all histories
1186 1187 if new_session:
1187 1188 self.execution_count = 1
1188 1189
1189 1190 # Flush cached output items
1190 1191 if self.displayhook.do_full_cache:
1191 1192 self.displayhook.flush()
1192 1193
1193 1194 # The main execution namespaces must be cleared very carefully,
1194 1195 # skipping the deletion of the builtin-related keys, because doing so
1195 1196 # would cause errors in many object's __del__ methods.
1196 1197 if self.user_ns is not self.user_global_ns:
1197 1198 self.user_ns.clear()
1198 1199 ns = self.user_global_ns
1199 1200 drop_keys = set(ns.keys())
1200 1201 drop_keys.discard('__builtin__')
1201 1202 drop_keys.discard('__builtins__')
1202 1203 drop_keys.discard('__name__')
1203 1204 for k in drop_keys:
1204 1205 del ns[k]
1205 1206
1206 1207 self.user_ns_hidden.clear()
1207 1208
1208 1209 # Restore the user namespaces to minimal usability
1209 1210 self.init_user_ns()
1210 1211
1211 1212 # Restore the default and user aliases
1212 1213 self.alias_manager.clear_aliases()
1213 1214 self.alias_manager.init_aliases()
1214 1215
1215 1216 # Flush the private list of module references kept for script
1216 1217 # execution protection
1217 1218 self.clear_main_mod_cache()
1218 1219
1219 1220 # Clear out the namespace from the last %run
1220 1221 self.new_main_mod()
1221 1222
1222 1223 def del_var(self, varname, by_name=False):
1223 1224 """Delete a variable from the various namespaces, so that, as
1224 1225 far as possible, we're not keeping any hidden references to it.
1225 1226
1226 1227 Parameters
1227 1228 ----------
1228 1229 varname : str
1229 1230 The name of the variable to delete.
1230 1231 by_name : bool
1231 1232 If True, delete variables with the given name in each
1232 1233 namespace. If False (default), find the variable in the user
1233 1234 namespace, and delete references to it.
1234 1235 """
1235 1236 if varname in ('__builtin__', '__builtins__'):
1236 1237 raise ValueError("Refusing to delete %s" % varname)
1237 1238
1238 1239 ns_refs = self.all_ns_refs
1239 1240
1240 1241 if by_name: # Delete by name
1241 1242 for ns in ns_refs:
1242 1243 try:
1243 1244 del ns[varname]
1244 1245 except KeyError:
1245 1246 pass
1246 1247 else: # Delete by object
1247 1248 try:
1248 1249 obj = self.user_ns[varname]
1249 1250 except KeyError:
1250 1251 raise NameError("name '%s' is not defined" % varname)
1251 1252 # Also check in output history
1252 1253 ns_refs.append(self.history_manager.output_hist)
1253 1254 for ns in ns_refs:
1254 1255 to_delete = [n for n, o in ns.iteritems() if o is obj]
1255 1256 for name in to_delete:
1256 1257 del ns[name]
1257 1258
1258 1259 # displayhook keeps extra references, but not in a dictionary
1259 1260 for name in ('_', '__', '___'):
1260 1261 if getattr(self.displayhook, name) is obj:
1261 1262 setattr(self.displayhook, name, None)
1262 1263
1263 1264 def reset_selective(self, regex=None):
1264 1265 """Clear selective variables from internal namespaces based on a
1265 1266 specified regular expression.
1266 1267
1267 1268 Parameters
1268 1269 ----------
1269 1270 regex : string or compiled pattern, optional
1270 1271 A regular expression pattern that will be used in searching
1271 1272 variable names in the users namespaces.
1272 1273 """
1273 1274 if regex is not None:
1274 1275 try:
1275 1276 m = re.compile(regex)
1276 1277 except TypeError:
1277 1278 raise TypeError('regex must be a string or compiled pattern')
1278 1279 # Search for keys in each namespace that match the given regex
1279 1280 # If a match is found, delete the key/value pair.
1280 1281 for ns in self.all_ns_refs:
1281 1282 for var in ns:
1282 1283 if m.search(var):
1283 1284 del ns[var]
1284 1285
1285 1286 def push(self, variables, interactive=True):
1286 1287 """Inject a group of variables into the IPython user namespace.
1287 1288
1288 1289 Parameters
1289 1290 ----------
1290 1291 variables : dict, str or list/tuple of str
1291 1292 The variables to inject into the user's namespace. If a dict, a
1292 1293 simple update is done. If a str, the string is assumed to have
1293 1294 variable names separated by spaces. A list/tuple of str can also
1294 1295 be used to give the variable names. If just the variable names are
1295 1296 give (list/tuple/str) then the variable values looked up in the
1296 1297 callers frame.
1297 1298 interactive : bool
1298 1299 If True (default), the variables will be listed with the ``who``
1299 1300 magic.
1300 1301 """
1301 1302 vdict = None
1302 1303
1303 1304 # We need a dict of name/value pairs to do namespace updates.
1304 1305 if isinstance(variables, dict):
1305 1306 vdict = variables
1306 1307 elif isinstance(variables, (basestring, list, tuple)):
1307 1308 if isinstance(variables, basestring):
1308 1309 vlist = variables.split()
1309 1310 else:
1310 1311 vlist = variables
1311 1312 vdict = {}
1312 1313 cf = sys._getframe(1)
1313 1314 for name in vlist:
1314 1315 try:
1315 1316 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1316 1317 except:
1317 print ('Could not get variable %s from %s' %
1318 print('Could not get variable %s from %s' %
1318 1319 (name,cf.f_code.co_name))
1319 1320 else:
1320 1321 raise ValueError('variables must be a dict/str/list/tuple')
1321 1322
1322 1323 # Propagate variables to user namespace
1323 1324 self.user_ns.update(vdict)
1324 1325
1325 1326 # And configure interactive visibility
1326 1327 user_ns_hidden = self.user_ns_hidden
1327 1328 if interactive:
1328 1329 user_ns_hidden.difference_update(vdict)
1329 1330 else:
1330 1331 user_ns_hidden.update(vdict)
1331 1332
1332 1333 def drop_by_id(self, variables):
1333 1334 """Remove a dict of variables from the user namespace, if they are the
1334 1335 same as the values in the dictionary.
1335 1336
1336 1337 This is intended for use by extensions: variables that they've added can
1337 1338 be taken back out if they are unloaded, without removing any that the
1338 1339 user has overwritten.
1339 1340
1340 1341 Parameters
1341 1342 ----------
1342 1343 variables : dict
1343 1344 A dictionary mapping object names (as strings) to the objects.
1344 1345 """
1345 1346 for name, obj in variables.iteritems():
1346 1347 if name in self.user_ns and self.user_ns[name] is obj:
1347 1348 del self.user_ns[name]
1348 1349 self.user_ns_hidden.discard(name)
1349 1350
1350 1351 #-------------------------------------------------------------------------
1351 1352 # Things related to object introspection
1352 1353 #-------------------------------------------------------------------------
1353 1354
1354 1355 def _ofind(self, oname, namespaces=None):
1355 1356 """Find an object in the available namespaces.
1356 1357
1357 1358 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1358 1359
1359 1360 Has special code to detect magic functions.
1360 1361 """
1361 1362 oname = oname.strip()
1362 1363 #print '1- oname: <%r>' % oname # dbg
1363 1364 if not oname.startswith(ESC_MAGIC) and \
1364 1365 not oname.startswith(ESC_MAGIC2) and \
1365 1366 not py3compat.isidentifier(oname, dotted=True):
1366 1367 return dict(found=False)
1367 1368
1368 1369 alias_ns = None
1369 1370 if namespaces is None:
1370 1371 # Namespaces to search in:
1371 1372 # Put them in a list. The order is important so that we
1372 1373 # find things in the same order that Python finds them.
1373 1374 namespaces = [ ('Interactive', self.user_ns),
1374 1375 ('Interactive (global)', self.user_global_ns),
1375 1376 ('Python builtin', builtin_mod.__dict__),
1376 1377 ('Alias', self.alias_manager.alias_table),
1377 1378 ]
1378 1379 alias_ns = self.alias_manager.alias_table
1379 1380
1380 1381 # initialize results to 'null'
1381 1382 found = False; obj = None; ospace = None; ds = None;
1382 1383 ismagic = False; isalias = False; parent = None
1383 1384
1384 1385 # We need to special-case 'print', which as of python2.6 registers as a
1385 1386 # function but should only be treated as one if print_function was
1386 1387 # loaded with a future import. In this case, just bail.
1387 1388 if (oname == 'print' and not py3compat.PY3 and not \
1388 1389 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 1390 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 1391 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391 1392
1392 1393 # Look for the given name by splitting it in parts. If the head is
1393 1394 # found, then we look for all the remaining parts as members, and only
1394 1395 # declare success if we can find them all.
1395 1396 oname_parts = oname.split('.')
1396 1397 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 1398 for nsname,ns in namespaces:
1398 1399 try:
1399 1400 obj = ns[oname_head]
1400 1401 except KeyError:
1401 1402 continue
1402 1403 else:
1403 1404 #print 'oname_rest:', oname_rest # dbg
1404 1405 for part in oname_rest:
1405 1406 try:
1406 1407 parent = obj
1407 1408 obj = getattr(obj,part)
1408 1409 except:
1409 1410 # Blanket except b/c some badly implemented objects
1410 1411 # allow __getattr__ to raise exceptions other than
1411 1412 # AttributeError, which then crashes IPython.
1412 1413 break
1413 1414 else:
1414 1415 # If we finish the for loop (no break), we got all members
1415 1416 found = True
1416 1417 ospace = nsname
1417 1418 if ns == alias_ns:
1418 1419 isalias = True
1419 1420 break # namespace loop
1420 1421
1421 1422 # Try to see if it's magic
1422 1423 if not found:
1423 1424 obj = None
1424 1425 if oname.startswith(ESC_MAGIC2):
1425 1426 oname = oname.lstrip(ESC_MAGIC2)
1426 1427 obj = self.find_cell_magic(oname)
1427 1428 elif oname.startswith(ESC_MAGIC):
1428 1429 oname = oname.lstrip(ESC_MAGIC)
1429 1430 obj = self.find_line_magic(oname)
1430 1431 else:
1431 1432 # search without prefix, so run? will find %run?
1432 1433 obj = self.find_line_magic(oname)
1433 1434 if obj is None:
1434 1435 obj = self.find_cell_magic(oname)
1435 1436 if obj is not None:
1436 1437 found = True
1437 1438 ospace = 'IPython internal'
1438 1439 ismagic = True
1439 1440
1440 1441 # Last try: special-case some literals like '', [], {}, etc:
1441 1442 if not found and oname_head in ["''",'""','[]','{}','()']:
1442 1443 obj = eval(oname_head)
1443 1444 found = True
1444 1445 ospace = 'Interactive'
1445 1446
1446 1447 return {'found':found, 'obj':obj, 'namespace':ospace,
1447 1448 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1448 1449
1449 1450 def _ofind_property(self, oname, info):
1450 1451 """Second part of object finding, to look for property details."""
1451 1452 if info.found:
1452 1453 # Get the docstring of the class property if it exists.
1453 1454 path = oname.split('.')
1454 1455 root = '.'.join(path[:-1])
1455 1456 if info.parent is not None:
1456 1457 try:
1457 1458 target = getattr(info.parent, '__class__')
1458 1459 # The object belongs to a class instance.
1459 1460 try:
1460 1461 target = getattr(target, path[-1])
1461 1462 # The class defines the object.
1462 1463 if isinstance(target, property):
1463 1464 oname = root + '.__class__.' + path[-1]
1464 1465 info = Struct(self._ofind(oname))
1465 1466 except AttributeError: pass
1466 1467 except AttributeError: pass
1467 1468
1468 1469 # We return either the new info or the unmodified input if the object
1469 1470 # hadn't been found
1470 1471 return info
1471 1472
1472 1473 def _object_find(self, oname, namespaces=None):
1473 1474 """Find an object and return a struct with info about it."""
1474 1475 inf = Struct(self._ofind(oname, namespaces))
1475 1476 return Struct(self._ofind_property(oname, inf))
1476 1477
1477 1478 def _inspect(self, meth, oname, namespaces=None, **kw):
1478 1479 """Generic interface to the inspector system.
1479 1480
1480 1481 This function is meant to be called by pdef, pdoc & friends."""
1481 1482 info = self._object_find(oname)
1482 1483 if info.found:
1483 1484 pmethod = getattr(self.inspector, meth)
1484 1485 formatter = format_screen if info.ismagic else None
1485 1486 if meth == 'pdoc':
1486 1487 pmethod(info.obj, oname, formatter)
1487 1488 elif meth == 'pinfo':
1488 1489 pmethod(info.obj, oname, formatter, info, **kw)
1489 1490 else:
1490 1491 pmethod(info.obj, oname)
1491 1492 else:
1492 print 'Object `%s` not found.' % oname
1493 print('Object `%s` not found.' % oname)
1493 1494 return 'not found' # so callers can take other action
1494 1495
1495 1496 def object_inspect(self, oname, detail_level=0):
1496 1497 with self.builtin_trap:
1497 1498 info = self._object_find(oname)
1498 1499 if info.found:
1499 1500 return self.inspector.info(info.obj, oname, info=info,
1500 1501 detail_level=detail_level
1501 1502 )
1502 1503 else:
1503 1504 return oinspect.object_info(name=oname, found=False)
1504 1505
1505 1506 #-------------------------------------------------------------------------
1506 1507 # Things related to history management
1507 1508 #-------------------------------------------------------------------------
1508 1509
1509 1510 def init_history(self):
1510 1511 """Sets up the command history, and starts regular autosaves."""
1511 1512 self.history_manager = HistoryManager(shell=self, config=self.config)
1512 1513 self.configurables.append(self.history_manager)
1513 1514
1514 1515 #-------------------------------------------------------------------------
1515 1516 # Things related to exception handling and tracebacks (not debugging)
1516 1517 #-------------------------------------------------------------------------
1517 1518
1518 1519 def init_traceback_handlers(self, custom_exceptions):
1519 1520 # Syntax error handler.
1520 1521 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1521 1522
1522 1523 # The interactive one is initialized with an offset, meaning we always
1523 1524 # want to remove the topmost item in the traceback, which is our own
1524 1525 # internal code. Valid modes: ['Plain','Context','Verbose']
1525 1526 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1526 1527 color_scheme='NoColor',
1527 1528 tb_offset = 1,
1528 1529 check_cache=self.compile.check_cache)
1529 1530
1530 1531 # The instance will store a pointer to the system-wide exception hook,
1531 1532 # so that runtime code (such as magics) can access it. This is because
1532 1533 # during the read-eval loop, it may get temporarily overwritten.
1533 1534 self.sys_excepthook = sys.excepthook
1534 1535
1535 1536 # and add any custom exception handlers the user may have specified
1536 1537 self.set_custom_exc(*custom_exceptions)
1537 1538
1538 1539 # Set the exception mode
1539 1540 self.InteractiveTB.set_mode(mode=self.xmode)
1540 1541
1541 1542 def set_custom_exc(self, exc_tuple, handler):
1542 1543 """set_custom_exc(exc_tuple,handler)
1543 1544
1544 1545 Set a custom exception handler, which will be called if any of the
1545 1546 exceptions in exc_tuple occur in the mainloop (specifically, in the
1546 1547 run_code() method).
1547 1548
1548 1549 Parameters
1549 1550 ----------
1550 1551
1551 1552 exc_tuple : tuple of exception classes
1552 1553 A *tuple* of exception classes, for which to call the defined
1553 1554 handler. It is very important that you use a tuple, and NOT A
1554 1555 LIST here, because of the way Python's except statement works. If
1555 1556 you only want to trap a single exception, use a singleton tuple::
1556 1557
1557 1558 exc_tuple == (MyCustomException,)
1558 1559
1559 1560 handler : callable
1560 1561 handler must have the following signature::
1561 1562
1562 1563 def my_handler(self, etype, value, tb, tb_offset=None):
1563 1564 ...
1564 1565 return structured_traceback
1565 1566
1566 1567 Your handler must return a structured traceback (a list of strings),
1567 1568 or None.
1568 1569
1569 1570 This will be made into an instance method (via types.MethodType)
1570 1571 of IPython itself, and it will be called if any of the exceptions
1571 1572 listed in the exc_tuple are caught. If the handler is None, an
1572 1573 internal basic one is used, which just prints basic info.
1573 1574
1574 1575 To protect IPython from crashes, if your handler ever raises an
1575 1576 exception or returns an invalid result, it will be immediately
1576 1577 disabled.
1577 1578
1578 1579 WARNING: by putting in your own exception handler into IPython's main
1579 1580 execution loop, you run a very good chance of nasty crashes. This
1580 1581 facility should only be used if you really know what you are doing."""
1581 1582
1582 1583 assert type(exc_tuple)==type(()) , \
1583 1584 "The custom exceptions must be given AS A TUPLE."
1584 1585
1585 1586 def dummy_handler(self,etype,value,tb,tb_offset=None):
1586 print '*** Simple custom exception handler ***'
1587 print 'Exception type :',etype
1588 print 'Exception value:',value
1589 print 'Traceback :',tb
1587 print('*** Simple custom exception handler ***')
1588 print('Exception type :',etype)
1589 print('Exception value:',value)
1590 print('Traceback :',tb)
1590 1591 #print 'Source code :','\n'.join(self.buffer)
1591 1592
1592 1593 def validate_stb(stb):
1593 1594 """validate structured traceback return type
1594 1595
1595 1596 return type of CustomTB *should* be a list of strings, but allow
1596 1597 single strings or None, which are harmless.
1597 1598
1598 1599 This function will *always* return a list of strings,
1599 1600 and will raise a TypeError if stb is inappropriate.
1600 1601 """
1601 1602 msg = "CustomTB must return list of strings, not %r" % stb
1602 1603 if stb is None:
1603 1604 return []
1604 1605 elif isinstance(stb, basestring):
1605 1606 return [stb]
1606 1607 elif not isinstance(stb, list):
1607 1608 raise TypeError(msg)
1608 1609 # it's a list
1609 1610 for line in stb:
1610 1611 # check every element
1611 1612 if not isinstance(line, basestring):
1612 1613 raise TypeError(msg)
1613 1614 return stb
1614 1615
1615 1616 if handler is None:
1616 1617 wrapped = dummy_handler
1617 1618 else:
1618 1619 def wrapped(self,etype,value,tb,tb_offset=None):
1619 1620 """wrap CustomTB handler, to protect IPython from user code
1620 1621
1621 1622 This makes it harder (but not impossible) for custom exception
1622 1623 handlers to crash IPython.
1623 1624 """
1624 1625 try:
1625 1626 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1626 1627 return validate_stb(stb)
1627 1628 except:
1628 1629 # clear custom handler immediately
1629 1630 self.set_custom_exc((), None)
1630 print >> io.stderr, "Custom TB Handler failed, unregistering"
1631 print("Custom TB Handler failed, unregistering", file=io.stderr)
1631 1632 # show the exception in handler first
1632 1633 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1633 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1634 print >> io.stdout, "The original exception:"
1634 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1635 print("The original exception:", file=io.stdout)
1635 1636 stb = self.InteractiveTB.structured_traceback(
1636 1637 (etype,value,tb), tb_offset=tb_offset
1637 1638 )
1638 1639 return stb
1639 1640
1640 1641 self.CustomTB = types.MethodType(wrapped,self)
1641 1642 self.custom_exceptions = exc_tuple
1642 1643
1643 1644 def excepthook(self, etype, value, tb):
1644 1645 """One more defense for GUI apps that call sys.excepthook.
1645 1646
1646 1647 GUI frameworks like wxPython trap exceptions and call
1647 1648 sys.excepthook themselves. I guess this is a feature that
1648 1649 enables them to keep running after exceptions that would
1649 1650 otherwise kill their mainloop. This is a bother for IPython
1650 1651 which excepts to catch all of the program exceptions with a try:
1651 1652 except: statement.
1652 1653
1653 1654 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1654 1655 any app directly invokes sys.excepthook, it will look to the user like
1655 1656 IPython crashed. In order to work around this, we can disable the
1656 1657 CrashHandler and replace it with this excepthook instead, which prints a
1657 1658 regular traceback using our InteractiveTB. In this fashion, apps which
1658 1659 call sys.excepthook will generate a regular-looking exception from
1659 1660 IPython, and the CrashHandler will only be triggered by real IPython
1660 1661 crashes.
1661 1662
1662 1663 This hook should be used sparingly, only in places which are not likely
1663 1664 to be true IPython errors.
1664 1665 """
1665 1666 self.showtraceback((etype,value,tb),tb_offset=0)
1666 1667
1667 1668 def _get_exc_info(self, exc_tuple=None):
1668 1669 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1669 1670
1670 1671 Ensures sys.last_type,value,traceback hold the exc_info we found,
1671 1672 from whichever source.
1672 1673
1673 1674 raises ValueError if none of these contain any information
1674 1675 """
1675 1676 if exc_tuple is None:
1676 1677 etype, value, tb = sys.exc_info()
1677 1678 else:
1678 1679 etype, value, tb = exc_tuple
1679 1680
1680 1681 if etype is None:
1681 1682 if hasattr(sys, 'last_type'):
1682 1683 etype, value, tb = sys.last_type, sys.last_value, \
1683 1684 sys.last_traceback
1684 1685
1685 1686 if etype is None:
1686 1687 raise ValueError("No exception to find")
1687 1688
1688 1689 # Now store the exception info in sys.last_type etc.
1689 1690 # WARNING: these variables are somewhat deprecated and not
1690 1691 # necessarily safe to use in a threaded environment, but tools
1691 1692 # like pdb depend on their existence, so let's set them. If we
1692 1693 # find problems in the field, we'll need to revisit their use.
1693 1694 sys.last_type = etype
1694 1695 sys.last_value = value
1695 1696 sys.last_traceback = tb
1696 1697
1697 1698 return etype, value, tb
1698 1699
1699 1700
1700 1701 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1701 1702 exception_only=False):
1702 1703 """Display the exception that just occurred.
1703 1704
1704 1705 If nothing is known about the exception, this is the method which
1705 1706 should be used throughout the code for presenting user tracebacks,
1706 1707 rather than directly invoking the InteractiveTB object.
1707 1708
1708 1709 A specific showsyntaxerror() also exists, but this method can take
1709 1710 care of calling it if needed, so unless you are explicitly catching a
1710 1711 SyntaxError exception, don't try to analyze the stack manually and
1711 1712 simply call this method."""
1712 1713
1713 1714 try:
1714 1715 try:
1715 1716 etype, value, tb = self._get_exc_info(exc_tuple)
1716 1717 except ValueError:
1717 1718 self.write_err('No traceback available to show.\n')
1718 1719 return
1719 1720
1720 1721 if etype is SyntaxError:
1721 1722 # Though this won't be called by syntax errors in the input
1722 1723 # line, there may be SyntaxError cases with imported code.
1723 1724 self.showsyntaxerror(filename)
1724 1725 elif etype is UsageError:
1725 1726 self.write_err("UsageError: %s" % value)
1726 1727 elif issubclass(etype, RemoteError):
1727 1728 # IPython.parallel remote exceptions.
1728 1729 # Draw the remote traceback, not the local one.
1729 1730 self._showtraceback(etype, value, value.render_traceback())
1730 1731 else:
1731 1732 if exception_only:
1732 1733 stb = ['An exception has occurred, use %tb to see '
1733 1734 'the full traceback.\n']
1734 1735 stb.extend(self.InteractiveTB.get_exception_only(etype,
1735 1736 value))
1736 1737 else:
1737 1738 stb = self.InteractiveTB.structured_traceback(etype,
1738 1739 value, tb, tb_offset=tb_offset)
1739 1740
1740 1741 self._showtraceback(etype, value, stb)
1741 1742 if self.call_pdb:
1742 1743 # drop into debugger
1743 1744 self.debugger(force=True)
1744 1745 return
1745 1746
1746 1747 # Actually show the traceback
1747 1748 self._showtraceback(etype, value, stb)
1748 1749
1749 1750 except KeyboardInterrupt:
1750 1751 self.write_err("\nKeyboardInterrupt\n")
1751 1752
1752 1753 def _showtraceback(self, etype, evalue, stb):
1753 1754 """Actually show a traceback.
1754 1755
1755 1756 Subclasses may override this method to put the traceback on a different
1756 1757 place, like a side channel.
1757 1758 """
1758 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1759 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1759 1760
1760 1761 def showsyntaxerror(self, filename=None):
1761 1762 """Display the syntax error that just occurred.
1762 1763
1763 1764 This doesn't display a stack trace because there isn't one.
1764 1765
1765 1766 If a filename is given, it is stuffed in the exception instead
1766 1767 of what was there before (because Python's parser always uses
1767 1768 "<string>" when reading from a string).
1768 1769 """
1769 1770 etype, value, last_traceback = self._get_exc_info()
1770 1771
1771 1772 if filename and etype is SyntaxError:
1772 1773 try:
1773 1774 value.filename = filename
1774 1775 except:
1775 1776 # Not the format we expect; leave it alone
1776 1777 pass
1777 1778
1778 1779 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1779 1780 self._showtraceback(etype, value, stb)
1780 1781
1781 1782 # This is overridden in TerminalInteractiveShell to show a message about
1782 1783 # the %paste magic.
1783 1784 def showindentationerror(self):
1784 1785 """Called by run_cell when there's an IndentationError in code entered
1785 1786 at the prompt.
1786 1787
1787 1788 This is overridden in TerminalInteractiveShell to show a message about
1788 1789 the %paste magic."""
1789 1790 self.showsyntaxerror()
1790 1791
1791 1792 #-------------------------------------------------------------------------
1792 1793 # Things related to readline
1793 1794 #-------------------------------------------------------------------------
1794 1795
1795 1796 def init_readline(self):
1796 1797 """Command history completion/saving/reloading."""
1797 1798
1798 1799 if self.readline_use:
1799 1800 import IPython.utils.rlineimpl as readline
1800 1801
1801 1802 self.rl_next_input = None
1802 1803 self.rl_do_indent = False
1803 1804
1804 1805 if not self.readline_use or not readline.have_readline:
1805 1806 self.has_readline = False
1806 1807 self.readline = None
1807 1808 # Set a number of methods that depend on readline to be no-op
1808 1809 self.readline_no_record = no_op_context
1809 1810 self.set_readline_completer = no_op
1810 1811 self.set_custom_completer = no_op
1811 1812 self.set_completer_frame = no_op
1812 1813 if self.readline_use:
1813 1814 warn('Readline services not available or not loaded.')
1814 1815 else:
1815 1816 self.has_readline = True
1816 1817 self.readline = readline
1817 1818 sys.modules['readline'] = readline
1818 1819
1819 1820 # Platform-specific configuration
1820 1821 if os.name == 'nt':
1821 1822 # FIXME - check with Frederick to see if we can harmonize
1822 1823 # naming conventions with pyreadline to avoid this
1823 1824 # platform-dependent check
1824 1825 self.readline_startup_hook = readline.set_pre_input_hook
1825 1826 else:
1826 1827 self.readline_startup_hook = readline.set_startup_hook
1827 1828
1828 1829 # Load user's initrc file (readline config)
1829 1830 # Or if libedit is used, load editrc.
1830 1831 inputrc_name = os.environ.get('INPUTRC')
1831 1832 if inputrc_name is None:
1832 1833 inputrc_name = '.inputrc'
1833 1834 if readline.uses_libedit:
1834 1835 inputrc_name = '.editrc'
1835 1836 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1836 1837 if os.path.isfile(inputrc_name):
1837 1838 try:
1838 1839 readline.read_init_file(inputrc_name)
1839 1840 except:
1840 1841 warn('Problems reading readline initialization file <%s>'
1841 1842 % inputrc_name)
1842 1843
1843 1844 # Configure readline according to user's prefs
1844 1845 # This is only done if GNU readline is being used. If libedit
1845 1846 # is being used (as on Leopard) the readline config is
1846 1847 # not run as the syntax for libedit is different.
1847 1848 if not readline.uses_libedit:
1848 1849 for rlcommand in self.readline_parse_and_bind:
1849 1850 #print "loading rl:",rlcommand # dbg
1850 1851 readline.parse_and_bind(rlcommand)
1851 1852
1852 1853 # Remove some chars from the delimiters list. If we encounter
1853 1854 # unicode chars, discard them.
1854 1855 delims = readline.get_completer_delims()
1855 1856 if not py3compat.PY3:
1856 1857 delims = delims.encode("ascii", "ignore")
1857 1858 for d in self.readline_remove_delims:
1858 1859 delims = delims.replace(d, "")
1859 1860 delims = delims.replace(ESC_MAGIC, '')
1860 1861 readline.set_completer_delims(delims)
1861 1862 # otherwise we end up with a monster history after a while:
1862 1863 readline.set_history_length(self.history_length)
1863 1864
1864 1865 self.refill_readline_hist()
1865 1866 self.readline_no_record = ReadlineNoRecord(self)
1866 1867
1867 1868 # Configure auto-indent for all platforms
1868 1869 self.set_autoindent(self.autoindent)
1869 1870
1870 1871 def refill_readline_hist(self):
1871 1872 # Load the last 1000 lines from history
1872 1873 self.readline.clear_history()
1873 1874 stdin_encoding = sys.stdin.encoding or "utf-8"
1874 1875 last_cell = u""
1875 1876 for _, _, cell in self.history_manager.get_tail(1000,
1876 1877 include_latest=True):
1877 1878 # Ignore blank lines and consecutive duplicates
1878 1879 cell = cell.rstrip()
1879 1880 if cell and (cell != last_cell):
1880 1881 if self.multiline_history:
1881 1882 self.readline.add_history(py3compat.unicode_to_str(cell,
1882 1883 stdin_encoding))
1883 1884 else:
1884 1885 for line in cell.splitlines():
1885 1886 self.readline.add_history(py3compat.unicode_to_str(line,
1886 1887 stdin_encoding))
1887 1888 last_cell = cell
1888 1889
1889 1890 def set_next_input(self, s):
1890 1891 """ Sets the 'default' input string for the next command line.
1891 1892
1892 1893 Requires readline.
1893 1894
1894 1895 Example:
1895 1896
1896 1897 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1897 1898 [D:\ipython]|2> Hello Word_ # cursor is here
1898 1899 """
1899 1900 self.rl_next_input = py3compat.cast_bytes_py2(s)
1900 1901
1901 1902 # Maybe move this to the terminal subclass?
1902 1903 def pre_readline(self):
1903 1904 """readline hook to be used at the start of each line.
1904 1905
1905 1906 Currently it handles auto-indent only."""
1906 1907
1907 1908 if self.rl_do_indent:
1908 1909 self.readline.insert_text(self._indent_current_str())
1909 1910 if self.rl_next_input is not None:
1910 1911 self.readline.insert_text(self.rl_next_input)
1911 1912 self.rl_next_input = None
1912 1913
1913 1914 def _indent_current_str(self):
1914 1915 """return the current level of indentation as a string"""
1915 1916 return self.input_splitter.indent_spaces * ' '
1916 1917
1917 1918 #-------------------------------------------------------------------------
1918 1919 # Things related to text completion
1919 1920 #-------------------------------------------------------------------------
1920 1921
1921 1922 def init_completer(self):
1922 1923 """Initialize the completion machinery.
1923 1924
1924 1925 This creates completion machinery that can be used by client code,
1925 1926 either interactively in-process (typically triggered by the readline
1926 1927 library), programatically (such as in test suites) or out-of-prcess
1927 1928 (typically over the network by remote frontends).
1928 1929 """
1929 1930 from IPython.core.completer import IPCompleter
1930 1931 from IPython.core.completerlib import (module_completer,
1931 1932 magic_run_completer, cd_completer, reset_completer)
1932 1933
1933 1934 self.Completer = IPCompleter(shell=self,
1934 1935 namespace=self.user_ns,
1935 1936 global_namespace=self.user_global_ns,
1936 1937 alias_table=self.alias_manager.alias_table,
1937 1938 use_readline=self.has_readline,
1938 1939 config=self.config,
1939 1940 )
1940 1941 self.configurables.append(self.Completer)
1941 1942
1942 1943 # Add custom completers to the basic ones built into IPCompleter
1943 1944 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1944 1945 self.strdispatchers['complete_command'] = sdisp
1945 1946 self.Completer.custom_completers = sdisp
1946 1947
1947 1948 self.set_hook('complete_command', module_completer, str_key = 'import')
1948 1949 self.set_hook('complete_command', module_completer, str_key = 'from')
1949 1950 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1950 1951 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1951 1952 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1952 1953
1953 1954 # Only configure readline if we truly are using readline. IPython can
1954 1955 # do tab-completion over the network, in GUIs, etc, where readline
1955 1956 # itself may be absent
1956 1957 if self.has_readline:
1957 1958 self.set_readline_completer()
1958 1959
1959 1960 def complete(self, text, line=None, cursor_pos=None):
1960 1961 """Return the completed text and a list of completions.
1961 1962
1962 1963 Parameters
1963 1964 ----------
1964 1965
1965 1966 text : string
1966 1967 A string of text to be completed on. It can be given as empty and
1967 1968 instead a line/position pair are given. In this case, the
1968 1969 completer itself will split the line like readline does.
1969 1970
1970 1971 line : string, optional
1971 1972 The complete line that text is part of.
1972 1973
1973 1974 cursor_pos : int, optional
1974 1975 The position of the cursor on the input line.
1975 1976
1976 1977 Returns
1977 1978 -------
1978 1979 text : string
1979 1980 The actual text that was completed.
1980 1981
1981 1982 matches : list
1982 1983 A sorted list with all possible completions.
1983 1984
1984 1985 The optional arguments allow the completion to take more context into
1985 1986 account, and are part of the low-level completion API.
1986 1987
1987 1988 This is a wrapper around the completion mechanism, similar to what
1988 1989 readline does at the command line when the TAB key is hit. By
1989 1990 exposing it as a method, it can be used by other non-readline
1990 1991 environments (such as GUIs) for text completion.
1991 1992
1992 1993 Simple usage example:
1993 1994
1994 1995 In [1]: x = 'hello'
1995 1996
1996 1997 In [2]: _ip.complete('x.l')
1997 1998 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1998 1999 """
1999 2000
2000 2001 # Inject names into __builtin__ so we can complete on the added names.
2001 2002 with self.builtin_trap:
2002 2003 return self.Completer.complete(text, line, cursor_pos)
2003 2004
2004 2005 def set_custom_completer(self, completer, pos=0):
2005 2006 """Adds a new custom completer function.
2006 2007
2007 2008 The position argument (defaults to 0) is the index in the completers
2008 2009 list where you want the completer to be inserted."""
2009 2010
2010 2011 newcomp = types.MethodType(completer,self.Completer)
2011 2012 self.Completer.matchers.insert(pos,newcomp)
2012 2013
2013 2014 def set_readline_completer(self):
2014 2015 """Reset readline's completer to be our own."""
2015 2016 self.readline.set_completer(self.Completer.rlcomplete)
2016 2017
2017 2018 def set_completer_frame(self, frame=None):
2018 2019 """Set the frame of the completer."""
2019 2020 if frame:
2020 2021 self.Completer.namespace = frame.f_locals
2021 2022 self.Completer.global_namespace = frame.f_globals
2022 2023 else:
2023 2024 self.Completer.namespace = self.user_ns
2024 2025 self.Completer.global_namespace = self.user_global_ns
2025 2026
2026 2027 #-------------------------------------------------------------------------
2027 2028 # Things related to magics
2028 2029 #-------------------------------------------------------------------------
2029 2030
2030 2031 def init_magics(self):
2031 2032 from IPython.core import magics as m
2032 2033 self.magics_manager = magic.MagicsManager(shell=self,
2033 2034 confg=self.config,
2034 2035 user_magics=m.UserMagics(self))
2035 2036 self.configurables.append(self.magics_manager)
2036 2037
2037 2038 # Expose as public API from the magics manager
2038 2039 self.register_magics = self.magics_manager.register
2039 2040 self.register_magic_function = self.magics_manager.register_function
2040 2041 self.define_magic = self.magics_manager.define_magic
2041 2042
2042 2043 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2043 2044 m.ConfigMagics, m.DeprecatedMagics, m.ExecutionMagics,
2044 2045 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2045 2046 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2046 2047 )
2047 2048
2048 2049 # FIXME: Move the color initialization to the DisplayHook, which
2049 2050 # should be split into a prompt manager and displayhook. We probably
2050 2051 # even need a centralize colors management object.
2051 2052 self.magic('colors %s' % self.colors)
2052 2053
2053 2054 def run_line_magic(self, magic_name, line):
2054 2055 """Execute the given line magic.
2055 2056
2056 2057 Parameters
2057 2058 ----------
2058 2059 magic_name : str
2059 2060 Name of the desired magic function, without '%' prefix.
2060 2061
2061 2062 line : str
2062 2063 The rest of the input line as a single string.
2063 2064 """
2064 2065 fn = self.find_line_magic(magic_name)
2065 2066 if fn is None:
2066 2067 cm = self.find_cell_magic(magic_name)
2067 2068 etpl = "Line magic function `%%%s` not found%s."
2068 2069 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2069 2070 'did you mean that instead?)' % magic_name )
2070 2071 error(etpl % (magic_name, extra))
2071 2072 else:
2072 2073 # Note: this is the distance in the stack to the user's frame.
2073 2074 # This will need to be updated if the internal calling logic gets
2074 2075 # refactored, or else we'll be expanding the wrong variables.
2075 2076 stack_depth = 2
2076 2077 magic_arg_s = self.var_expand(line, stack_depth)
2077 2078 # Put magic args in a list so we can call with f(*a) syntax
2078 2079 args = [magic_arg_s]
2079 2080 # Grab local namespace if we need it:
2080 2081 if getattr(fn, "needs_local_scope", False):
2081 2082 args.append(sys._getframe(stack_depth).f_locals)
2082 2083 with self.builtin_trap:
2083 2084 result = fn(*args)
2084 2085 return result
2085 2086
2086 2087 def run_cell_magic(self, magic_name, line, cell):
2087 2088 """Execute the given cell magic.
2088 2089
2089 2090 Parameters
2090 2091 ----------
2091 2092 magic_name : str
2092 2093 Name of the desired magic function, without '%' prefix.
2093 2094
2094 2095 line : str
2095 2096 The rest of the first input line as a single string.
2096 2097
2097 2098 cell : str
2098 2099 The body of the cell as a (possibly multiline) string.
2099 2100 """
2100 2101 fn = self.find_cell_magic(magic_name)
2101 2102 if fn is None:
2102 2103 lm = self.find_line_magic(magic_name)
2103 2104 etpl = "Cell magic function `%%%%%s` not found%s."
2104 2105 extra = '' if lm is None else (' (But line magic `%%%s` exists, '
2105 2106 'did you mean that instead?)' % magic_name )
2106 2107 error(etpl % (magic_name, extra))
2107 2108 else:
2108 2109 # Note: this is the distance in the stack to the user's frame.
2109 2110 # This will need to be updated if the internal calling logic gets
2110 2111 # refactored, or else we'll be expanding the wrong variables.
2111 2112 stack_depth = 2
2112 2113 magic_arg_s = self.var_expand(line, stack_depth)
2113 2114 with self.builtin_trap:
2114 2115 result = fn(line, cell)
2115 2116 return result
2116 2117
2117 2118 def find_line_magic(self, magic_name):
2118 2119 """Find and return a line magic by name.
2119 2120
2120 2121 Returns None if the magic isn't found."""
2121 2122 return self.magics_manager.magics['line'].get(magic_name)
2122 2123
2123 2124 def find_cell_magic(self, magic_name):
2124 2125 """Find and return a cell magic by name.
2125 2126
2126 2127 Returns None if the magic isn't found."""
2127 2128 return self.magics_manager.magics['cell'].get(magic_name)
2128 2129
2129 2130 def find_magic(self, magic_name, magic_kind='line'):
2130 2131 """Find and return a magic of the given type by name.
2131 2132
2132 2133 Returns None if the magic isn't found."""
2133 2134 return self.magics_manager.magics[magic_kind].get(magic_name)
2134 2135
2135 2136 def magic(self, arg_s):
2136 2137 """DEPRECATED. Use run_line_magic() instead.
2137 2138
2138 2139 Call a magic function by name.
2139 2140
2140 2141 Input: a string containing the name of the magic function to call and
2141 2142 any additional arguments to be passed to the magic.
2142 2143
2143 2144 magic('name -opt foo bar') is equivalent to typing at the ipython
2144 2145 prompt:
2145 2146
2146 2147 In[1]: %name -opt foo bar
2147 2148
2148 2149 To call a magic without arguments, simply use magic('name').
2149 2150
2150 2151 This provides a proper Python function to call IPython's magics in any
2151 2152 valid Python code you can type at the interpreter, including loops and
2152 2153 compound statements.
2153 2154 """
2154 2155 # TODO: should we issue a loud deprecation warning here?
2155 2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2156 2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2157 2158 return self.run_line_magic(magic_name, magic_arg_s)
2158 2159
2159 2160 #-------------------------------------------------------------------------
2160 2161 # Things related to macros
2161 2162 #-------------------------------------------------------------------------
2162 2163
2163 2164 def define_macro(self, name, themacro):
2164 2165 """Define a new macro
2165 2166
2166 2167 Parameters
2167 2168 ----------
2168 2169 name : str
2169 2170 The name of the macro.
2170 2171 themacro : str or Macro
2171 2172 The action to do upon invoking the macro. If a string, a new
2172 2173 Macro object is created by passing the string to it.
2173 2174 """
2174 2175
2175 2176 from IPython.core import macro
2176 2177
2177 2178 if isinstance(themacro, basestring):
2178 2179 themacro = macro.Macro(themacro)
2179 2180 if not isinstance(themacro, macro.Macro):
2180 2181 raise ValueError('A macro must be a string or a Macro instance.')
2181 2182 self.user_ns[name] = themacro
2182 2183
2183 2184 #-------------------------------------------------------------------------
2184 2185 # Things related to the running of system commands
2185 2186 #-------------------------------------------------------------------------
2186 2187
2187 2188 def system_piped(self, cmd):
2188 2189 """Call the given cmd in a subprocess, piping stdout/err
2189 2190
2190 2191 Parameters
2191 2192 ----------
2192 2193 cmd : str
2193 2194 Command to execute (can not end in '&', as background processes are
2194 2195 not supported. Should not be a command that expects input
2195 2196 other than simple text.
2196 2197 """
2197 2198 if cmd.rstrip().endswith('&'):
2198 2199 # this is *far* from a rigorous test
2199 2200 # We do not support backgrounding processes because we either use
2200 2201 # pexpect or pipes to read from. Users can always just call
2201 2202 # os.system() or use ip.system=ip.system_raw
2202 2203 # if they really want a background process.
2203 2204 raise OSError("Background processes not supported.")
2204 2205
2205 2206 # we explicitly do NOT return the subprocess status code, because
2206 2207 # a non-None value would trigger :func:`sys.displayhook` calls.
2207 2208 # Instead, we store the exit_code in user_ns.
2208 2209 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2209 2210
2210 2211 def system_raw(self, cmd):
2211 2212 """Call the given cmd in a subprocess using os.system
2212 2213
2213 2214 Parameters
2214 2215 ----------
2215 2216 cmd : str
2216 2217 Command to execute.
2217 2218 """
2218 2219 cmd = self.var_expand(cmd, depth=1)
2219 2220 # protect os.system from UNC paths on Windows, which it can't handle:
2220 2221 if sys.platform == 'win32':
2221 2222 from IPython.utils._process_win32 import AvoidUNCPath
2222 2223 with AvoidUNCPath() as path:
2223 2224 if path is not None:
2224 2225 cmd = '"pushd %s &&"%s' % (path, cmd)
2225 2226 cmd = py3compat.unicode_to_str(cmd)
2226 2227 ec = os.system(cmd)
2227 2228 else:
2228 2229 cmd = py3compat.unicode_to_str(cmd)
2229 2230 ec = os.system(cmd)
2230 2231
2231 2232 # We explicitly do NOT return the subprocess status code, because
2232 2233 # a non-None value would trigger :func:`sys.displayhook` calls.
2233 2234 # Instead, we store the exit_code in user_ns.
2234 2235 self.user_ns['_exit_code'] = ec
2235 2236
2236 2237 # use piped system by default, because it is better behaved
2237 2238 system = system_piped
2238 2239
2239 2240 def getoutput(self, cmd, split=True, depth=0):
2240 2241 """Get output (possibly including stderr) from a subprocess.
2241 2242
2242 2243 Parameters
2243 2244 ----------
2244 2245 cmd : str
2245 2246 Command to execute (can not end in '&', as background processes are
2246 2247 not supported.
2247 2248 split : bool, optional
2248 2249 If True, split the output into an IPython SList. Otherwise, an
2249 2250 IPython LSString is returned. These are objects similar to normal
2250 2251 lists and strings, with a few convenience attributes for easier
2251 2252 manipulation of line-based output. You can use '?' on them for
2252 2253 details.
2253 2254 depth : int, optional
2254 2255 How many frames above the caller are the local variables which should
2255 2256 be expanded in the command string? The default (0) assumes that the
2256 2257 expansion variables are in the stack frame calling this function.
2257 2258 """
2258 2259 if cmd.rstrip().endswith('&'):
2259 2260 # this is *far* from a rigorous test
2260 2261 raise OSError("Background processes not supported.")
2261 2262 out = getoutput(self.var_expand(cmd, depth=depth+1))
2262 2263 if split:
2263 2264 out = SList(out.splitlines())
2264 2265 else:
2265 2266 out = LSString(out)
2266 2267 return out
2267 2268
2268 2269 #-------------------------------------------------------------------------
2269 2270 # Things related to aliases
2270 2271 #-------------------------------------------------------------------------
2271 2272
2272 2273 def init_alias(self):
2273 2274 self.alias_manager = AliasManager(shell=self, config=self.config)
2274 2275 self.configurables.append(self.alias_manager)
2275 2276 self.ns_table['alias'] = self.alias_manager.alias_table,
2276 2277
2277 2278 #-------------------------------------------------------------------------
2278 2279 # Things related to extensions and plugins
2279 2280 #-------------------------------------------------------------------------
2280 2281
2281 2282 def init_extension_manager(self):
2282 2283 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2283 2284 self.configurables.append(self.extension_manager)
2284 2285
2285 2286 def init_plugin_manager(self):
2286 2287 self.plugin_manager = PluginManager(config=self.config)
2287 2288 self.configurables.append(self.plugin_manager)
2288 2289
2289 2290
2290 2291 #-------------------------------------------------------------------------
2291 2292 # Things related to payloads
2292 2293 #-------------------------------------------------------------------------
2293 2294
2294 2295 def init_payload(self):
2295 2296 self.payload_manager = PayloadManager(config=self.config)
2296 2297 self.configurables.append(self.payload_manager)
2297 2298
2298 2299 #-------------------------------------------------------------------------
2299 2300 # Things related to the prefilter
2300 2301 #-------------------------------------------------------------------------
2301 2302
2302 2303 def init_prefilter(self):
2303 2304 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2304 2305 self.configurables.append(self.prefilter_manager)
2305 2306 # Ultimately this will be refactored in the new interpreter code, but
2306 2307 # for now, we should expose the main prefilter method (there's legacy
2307 2308 # code out there that may rely on this).
2308 2309 self.prefilter = self.prefilter_manager.prefilter_lines
2309 2310
2310 2311 def auto_rewrite_input(self, cmd):
2311 2312 """Print to the screen the rewritten form of the user's command.
2312 2313
2313 2314 This shows visual feedback by rewriting input lines that cause
2314 2315 automatic calling to kick in, like::
2315 2316
2316 2317 /f x
2317 2318
2318 2319 into::
2319 2320
2320 2321 ------> f(x)
2321 2322
2322 2323 after the user's input prompt. This helps the user understand that the
2323 2324 input line was transformed automatically by IPython.
2324 2325 """
2325 2326 if not self.show_rewritten_input:
2326 2327 return
2327 2328
2328 2329 rw = self.prompt_manager.render('rewrite') + cmd
2329 2330
2330 2331 try:
2331 2332 # plain ascii works better w/ pyreadline, on some machines, so
2332 2333 # we use it and only print uncolored rewrite if we have unicode
2333 2334 rw = str(rw)
2334 print >> io.stdout, rw
2335 print(rw, file=io.stdout)
2335 2336 except UnicodeEncodeError:
2336 print "------> " + cmd
2337 print("------> " + cmd)
2337 2338
2338 2339 #-------------------------------------------------------------------------
2339 2340 # Things related to extracting values/expressions from kernel and user_ns
2340 2341 #-------------------------------------------------------------------------
2341 2342
2342 2343 def _simple_error(self):
2343 2344 etype, value = sys.exc_info()[:2]
2344 2345 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2345 2346
2346 2347 def user_variables(self, names):
2347 2348 """Get a list of variable names from the user's namespace.
2348 2349
2349 2350 Parameters
2350 2351 ----------
2351 2352 names : list of strings
2352 2353 A list of names of variables to be read from the user namespace.
2353 2354
2354 2355 Returns
2355 2356 -------
2356 2357 A dict, keyed by the input names and with the repr() of each value.
2357 2358 """
2358 2359 out = {}
2359 2360 user_ns = self.user_ns
2360 2361 for varname in names:
2361 2362 try:
2362 2363 value = repr(user_ns[varname])
2363 2364 except:
2364 2365 value = self._simple_error()
2365 2366 out[varname] = value
2366 2367 return out
2367 2368
2368 2369 def user_expressions(self, expressions):
2369 2370 """Evaluate a dict of expressions in the user's namespace.
2370 2371
2371 2372 Parameters
2372 2373 ----------
2373 2374 expressions : dict
2374 2375 A dict with string keys and string values. The expression values
2375 2376 should be valid Python expressions, each of which will be evaluated
2376 2377 in the user namespace.
2377 2378
2378 2379 Returns
2379 2380 -------
2380 2381 A dict, keyed like the input expressions dict, with the repr() of each
2381 2382 value.
2382 2383 """
2383 2384 out = {}
2384 2385 user_ns = self.user_ns
2385 2386 global_ns = self.user_global_ns
2386 2387 for key, expr in expressions.iteritems():
2387 2388 try:
2388 2389 value = repr(eval(expr, global_ns, user_ns))
2389 2390 except:
2390 2391 value = self._simple_error()
2391 2392 out[key] = value
2392 2393 return out
2393 2394
2394 2395 #-------------------------------------------------------------------------
2395 2396 # Things related to the running of code
2396 2397 #-------------------------------------------------------------------------
2397 2398
2398 2399 def ex(self, cmd):
2399 2400 """Execute a normal python statement in user namespace."""
2400 2401 with self.builtin_trap:
2401 2402 exec cmd in self.user_global_ns, self.user_ns
2402 2403
2403 2404 def ev(self, expr):
2404 2405 """Evaluate python expression expr in user namespace.
2405 2406
2406 2407 Returns the result of evaluation
2407 2408 """
2408 2409 with self.builtin_trap:
2409 2410 return eval(expr, self.user_global_ns, self.user_ns)
2410 2411
2411 2412 def safe_execfile(self, fname, *where, **kw):
2412 2413 """A safe version of the builtin execfile().
2413 2414
2414 2415 This version will never throw an exception, but instead print
2415 2416 helpful error messages to the screen. This only works on pure
2416 2417 Python files with the .py extension.
2417 2418
2418 2419 Parameters
2419 2420 ----------
2420 2421 fname : string
2421 2422 The name of the file to be executed.
2422 2423 where : tuple
2423 2424 One or two namespaces, passed to execfile() as (globals,locals).
2424 2425 If only one is given, it is passed as both.
2425 2426 exit_ignore : bool (False)
2426 2427 If True, then silence SystemExit for non-zero status (it is always
2427 2428 silenced for zero status, as it is so common).
2428 2429 raise_exceptions : bool (False)
2429 2430 If True raise exceptions everywhere. Meant for testing.
2430 2431
2431 2432 """
2432 2433 kw.setdefault('exit_ignore', False)
2433 2434 kw.setdefault('raise_exceptions', False)
2434 2435
2435 2436 fname = os.path.abspath(os.path.expanduser(fname))
2436 2437
2437 2438 # Make sure we can open the file
2438 2439 try:
2439 2440 with open(fname) as thefile:
2440 2441 pass
2441 2442 except:
2442 2443 warn('Could not open file <%s> for safe execution.' % fname)
2443 2444 return
2444 2445
2445 2446 # Find things also in current directory. This is needed to mimic the
2446 2447 # behavior of running a script from the system command line, where
2447 2448 # Python inserts the script's directory into sys.path
2448 2449 dname = os.path.dirname(fname)
2449 2450
2450 2451 with prepended_to_syspath(dname):
2451 2452 try:
2452 2453 py3compat.execfile(fname,*where)
2453 2454 except SystemExit as status:
2454 2455 # If the call was made with 0 or None exit status (sys.exit(0)
2455 2456 # or sys.exit() ), don't bother showing a traceback, as both of
2456 2457 # these are considered normal by the OS:
2457 2458 # > python -c'import sys;sys.exit(0)'; echo $?
2458 2459 # 0
2459 2460 # > python -c'import sys;sys.exit()'; echo $?
2460 2461 # 0
2461 2462 # For other exit status, we show the exception unless
2462 2463 # explicitly silenced, but only in short form.
2463 2464 if kw['raise_exceptions']:
2464 2465 raise
2465 2466 if status.code not in (0, None) and not kw['exit_ignore']:
2466 2467 self.showtraceback(exception_only=True)
2467 2468 except:
2468 2469 if kw['raise_exceptions']:
2469 2470 raise
2470 2471 self.showtraceback()
2471 2472
2472 2473 def safe_execfile_ipy(self, fname):
2473 2474 """Like safe_execfile, but for .ipy files with IPython syntax.
2474 2475
2475 2476 Parameters
2476 2477 ----------
2477 2478 fname : str
2478 2479 The name of the file to execute. The filename must have a
2479 2480 .ipy extension.
2480 2481 """
2481 2482 fname = os.path.abspath(os.path.expanduser(fname))
2482 2483
2483 2484 # Make sure we can open the file
2484 2485 try:
2485 2486 with open(fname) as thefile:
2486 2487 pass
2487 2488 except:
2488 2489 warn('Could not open file <%s> for safe execution.' % fname)
2489 2490 return
2490 2491
2491 2492 # Find things also in current directory. This is needed to mimic the
2492 2493 # behavior of running a script from the system command line, where
2493 2494 # Python inserts the script's directory into sys.path
2494 2495 dname = os.path.dirname(fname)
2495 2496
2496 2497 with prepended_to_syspath(dname):
2497 2498 try:
2498 2499 with open(fname) as thefile:
2499 2500 # self.run_cell currently captures all exceptions
2500 2501 # raised in user code. It would be nice if there were
2501 2502 # versions of runlines, execfile that did raise, so
2502 2503 # we could catch the errors.
2503 2504 self.run_cell(thefile.read(), store_history=False)
2504 2505 except:
2505 2506 self.showtraceback()
2506 2507 warn('Unknown failure executing file: <%s>' % fname)
2507 2508
2508 2509 def safe_run_module(self, mod_name, where):
2509 2510 """A safe version of runpy.run_module().
2510 2511
2511 2512 This version will never throw an exception, but instead print
2512 2513 helpful error messages to the screen.
2513 2514
2514 2515 Parameters
2515 2516 ----------
2516 2517 mod_name : string
2517 2518 The name of the module to be executed.
2518 2519 where : dict
2519 2520 The globals namespace.
2520 2521 """
2521 2522 try:
2522 2523 where.update(
2523 2524 runpy.run_module(str(mod_name), run_name="__main__",
2524 2525 alter_sys=True)
2525 2526 )
2526 2527 except:
2527 2528 self.showtraceback()
2528 2529 warn('Unknown failure executing module: <%s>' % mod_name)
2529 2530
2530 2531 def _run_cached_cell_magic(self, magic_name, line):
2531 2532 """Special method to call a cell magic with the data stored in self.
2532 2533 """
2533 2534 cell = self._current_cell_magic_body
2534 2535 self._current_cell_magic_body = None
2535 2536 return self.run_cell_magic(magic_name, line, cell)
2536 2537
2537 2538 def run_cell(self, raw_cell, store_history=False, silent=False):
2538 2539 """Run a complete IPython cell.
2539 2540
2540 2541 Parameters
2541 2542 ----------
2542 2543 raw_cell : str
2543 2544 The code (including IPython code such as %magic functions) to run.
2544 2545 store_history : bool
2545 2546 If True, the raw and translated cell will be stored in IPython's
2546 2547 history. For user code calling back into IPython's machinery, this
2547 2548 should be set to False.
2548 2549 silent : bool
2549 2550 If True, avoid side-effets, such as implicit displayhooks, history,
2550 2551 and logging. silent=True forces store_history=False.
2551 2552 """
2552 2553 if (not raw_cell) or raw_cell.isspace():
2553 2554 return
2554 2555
2555 2556 if silent:
2556 2557 store_history = False
2557 2558
2558 2559 self.input_splitter.push(raw_cell)
2559 2560
2560 2561 # Check for cell magics, which leave state behind. This interface is
2561 2562 # ugly, we need to do something cleaner later... Now the logic is
2562 2563 # simply that the input_splitter remembers if there was a cell magic,
2563 2564 # and in that case we grab the cell body.
2564 2565 if self.input_splitter.cell_magic_parts:
2565 2566 self._current_cell_magic_body = \
2566 2567 ''.join(self.input_splitter.cell_magic_parts)
2567 2568 cell = self.input_splitter.source_reset()
2568 2569
2569 2570 with self.builtin_trap:
2570 2571 prefilter_failed = False
2571 2572 if len(cell.splitlines()) == 1:
2572 2573 try:
2573 2574 # use prefilter_lines to handle trailing newlines
2574 2575 # restore trailing newline for ast.parse
2575 2576 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2576 2577 except AliasError as e:
2577 2578 error(e)
2578 2579 prefilter_failed = True
2579 2580 except Exception:
2580 2581 # don't allow prefilter errors to crash IPython
2581 2582 self.showtraceback()
2582 2583 prefilter_failed = True
2583 2584
2584 2585 # Store raw and processed history
2585 2586 if store_history:
2586 2587 self.history_manager.store_inputs(self.execution_count,
2587 2588 cell, raw_cell)
2588 2589 if not silent:
2589 2590 self.logger.log(cell, raw_cell)
2590 2591
2591 2592 if not prefilter_failed:
2592 2593 # don't run if prefilter failed
2593 2594 cell_name = self.compile.cache(cell, self.execution_count)
2594 2595
2595 2596 with self.display_trap:
2596 2597 try:
2597 2598 code_ast = self.compile.ast_parse(cell,
2598 2599 filename=cell_name)
2599 2600 except IndentationError:
2600 2601 self.showindentationerror()
2601 2602 if store_history:
2602 2603 self.execution_count += 1
2603 2604 return None
2604 2605 except (OverflowError, SyntaxError, ValueError, TypeError,
2605 2606 MemoryError):
2606 2607 self.showsyntaxerror()
2607 2608 if store_history:
2608 2609 self.execution_count += 1
2609 2610 return None
2610 2611
2611 2612 interactivity = "none" if silent else self.ast_node_interactivity
2612 2613 self.run_ast_nodes(code_ast.body, cell_name,
2613 2614 interactivity=interactivity)
2614 2615
2615 2616 # Execute any registered post-execution functions.
2616 2617 # unless we are silent
2617 2618 post_exec = [] if silent else self._post_execute.iteritems()
2618 2619
2619 2620 for func, status in post_exec:
2620 2621 if self.disable_failing_post_execute and not status:
2621 2622 continue
2622 2623 try:
2623 2624 func()
2624 2625 except KeyboardInterrupt:
2625 print >> io.stderr, "\nKeyboardInterrupt"
2626 print("\nKeyboardInterrupt", file=io.stderr)
2626 2627 except Exception:
2627 2628 # register as failing:
2628 2629 self._post_execute[func] = False
2629 2630 self.showtraceback()
2630 print >> io.stderr, '\n'.join([
2631 print('\n'.join([
2631 2632 "post-execution function %r produced an error." % func,
2632 2633 "If this problem persists, you can disable failing post-exec functions with:",
2633 2634 "",
2634 2635 " get_ipython().disable_failing_post_execute = True"
2635 ])
2636 ]), file=io.stderr)
2636 2637
2637 2638 if store_history:
2638 2639 # Write output to the database. Does nothing unless
2639 2640 # history output logging is enabled.
2640 2641 self.history_manager.store_output(self.execution_count)
2641 2642 # Each cell is a *single* input, regardless of how many lines it has
2642 2643 self.execution_count += 1
2643 2644
2644 2645 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2645 2646 """Run a sequence of AST nodes. The execution mode depends on the
2646 2647 interactivity parameter.
2647 2648
2648 2649 Parameters
2649 2650 ----------
2650 2651 nodelist : list
2651 2652 A sequence of AST nodes to run.
2652 2653 cell_name : str
2653 2654 Will be passed to the compiler as the filename of the cell. Typically
2654 2655 the value returned by ip.compile.cache(cell).
2655 2656 interactivity : str
2656 2657 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2657 2658 run interactively (displaying output from expressions). 'last_expr'
2658 2659 will run the last node interactively only if it is an expression (i.e.
2659 2660 expressions in loops or other blocks are not displayed. Other values
2660 2661 for this parameter will raise a ValueError.
2661 2662 """
2662 2663 if not nodelist:
2663 2664 return
2664 2665
2665 2666 if interactivity == 'last_expr':
2666 2667 if isinstance(nodelist[-1], ast.Expr):
2667 2668 interactivity = "last"
2668 2669 else:
2669 2670 interactivity = "none"
2670 2671
2671 2672 if interactivity == 'none':
2672 2673 to_run_exec, to_run_interactive = nodelist, []
2673 2674 elif interactivity == 'last':
2674 2675 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2675 2676 elif interactivity == 'all':
2676 2677 to_run_exec, to_run_interactive = [], nodelist
2677 2678 else:
2678 2679 raise ValueError("Interactivity was %r" % interactivity)
2679 2680
2680 2681 exec_count = self.execution_count
2681 2682
2682 2683 try:
2683 2684 for i, node in enumerate(to_run_exec):
2684 2685 mod = ast.Module([node])
2685 2686 code = self.compile(mod, cell_name, "exec")
2686 2687 if self.run_code(code):
2687 2688 return True
2688 2689
2689 2690 for i, node in enumerate(to_run_interactive):
2690 2691 mod = ast.Interactive([node])
2691 2692 code = self.compile(mod, cell_name, "single")
2692 2693 if self.run_code(code):
2693 2694 return True
2694 2695
2695 2696 # Flush softspace
2696 2697 if softspace(sys.stdout, 0):
2697 print
2698 print()
2698 2699
2699 2700 except:
2700 2701 # It's possible to have exceptions raised here, typically by
2701 2702 # compilation of odd code (such as a naked 'return' outside a
2702 2703 # function) that did parse but isn't valid. Typically the exception
2703 2704 # is a SyntaxError, but it's safest just to catch anything and show
2704 2705 # the user a traceback.
2705 2706
2706 2707 # We do only one try/except outside the loop to minimize the impact
2707 2708 # on runtime, and also because if any node in the node list is
2708 2709 # broken, we should stop execution completely.
2709 2710 self.showtraceback()
2710 2711
2711 2712 return False
2712 2713
2713 2714 def run_code(self, code_obj):
2714 2715 """Execute a code object.
2715 2716
2716 2717 When an exception occurs, self.showtraceback() is called to display a
2717 2718 traceback.
2718 2719
2719 2720 Parameters
2720 2721 ----------
2721 2722 code_obj : code object
2722 2723 A compiled code object, to be executed
2723 2724
2724 2725 Returns
2725 2726 -------
2726 2727 False : successful execution.
2727 2728 True : an error occurred.
2728 2729 """
2729 2730
2730 2731 # Set our own excepthook in case the user code tries to call it
2731 2732 # directly, so that the IPython crash handler doesn't get triggered
2732 2733 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2733 2734
2734 2735 # we save the original sys.excepthook in the instance, in case config
2735 2736 # code (such as magics) needs access to it.
2736 2737 self.sys_excepthook = old_excepthook
2737 2738 outflag = 1 # happens in more places, so it's easier as default
2738 2739 try:
2739 2740 try:
2740 2741 self.hooks.pre_run_code_hook()
2741 2742 #rprint('Running code', repr(code_obj)) # dbg
2742 2743 exec code_obj in self.user_global_ns, self.user_ns
2743 2744 finally:
2744 2745 # Reset our crash handler in place
2745 2746 sys.excepthook = old_excepthook
2746 2747 except SystemExit:
2747 2748 self.showtraceback(exception_only=True)
2748 2749 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2749 2750 except self.custom_exceptions:
2750 2751 etype,value,tb = sys.exc_info()
2751 2752 self.CustomTB(etype,value,tb)
2752 2753 except:
2753 2754 self.showtraceback()
2754 2755 else:
2755 2756 outflag = 0
2756 2757 return outflag
2757 2758
2758 2759 # For backwards compatibility
2759 2760 runcode = run_code
2760 2761
2761 2762 #-------------------------------------------------------------------------
2762 2763 # Things related to GUI support and pylab
2763 2764 #-------------------------------------------------------------------------
2764 2765
2765 2766 def enable_gui(self, gui=None):
2766 2767 raise NotImplementedError('Implement enable_gui in a subclass')
2767 2768
2768 2769 def enable_pylab(self, gui=None, import_all=True):
2769 2770 """Activate pylab support at runtime.
2770 2771
2771 2772 This turns on support for matplotlib, preloads into the interactive
2772 2773 namespace all of numpy and pylab, and configures IPython to correctly
2773 2774 interact with the GUI event loop. The GUI backend to be used can be
2774 2775 optionally selected with the optional :param:`gui` argument.
2775 2776
2776 2777 Parameters
2777 2778 ----------
2778 2779 gui : optional, string
2779 2780
2780 2781 If given, dictates the choice of matplotlib GUI backend to use
2781 2782 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2782 2783 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2783 2784 matplotlib (as dictated by the matplotlib build-time options plus the
2784 2785 user's matplotlibrc configuration file). Note that not all backends
2785 2786 make sense in all contexts, for example a terminal ipython can't
2786 2787 display figures inline.
2787 2788 """
2788 2789 from IPython.core.pylabtools import mpl_runner
2789 2790 # We want to prevent the loading of pylab to pollute the user's
2790 2791 # namespace as shown by the %who* magics, so we execute the activation
2791 2792 # code in an empty namespace, and we update *both* user_ns and
2792 2793 # user_ns_hidden with this information.
2793 2794 ns = {}
2794 2795 try:
2795 2796 gui = pylab_activate(ns, gui, import_all, self)
2796 2797 except KeyError:
2797 2798 error("Backend %r not supported" % gui)
2798 2799 return
2799 2800 self.user_ns.update(ns)
2800 2801 self.user_ns_hidden.update(ns)
2801 2802 # Now we must activate the gui pylab wants to use, and fix %run to take
2802 2803 # plot updates into account
2803 2804 self.enable_gui(gui)
2804 2805 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2805 2806 mpl_runner(self.safe_execfile)
2806 2807
2807 2808 #-------------------------------------------------------------------------
2808 2809 # Utilities
2809 2810 #-------------------------------------------------------------------------
2810 2811
2811 2812 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2812 2813 """Expand python variables in a string.
2813 2814
2814 2815 The depth argument indicates how many frames above the caller should
2815 2816 be walked to look for the local namespace where to expand variables.
2816 2817
2817 2818 The global namespace for expansion is always the user's interactive
2818 2819 namespace.
2819 2820 """
2820 2821 ns = self.user_ns.copy()
2821 2822 ns.update(sys._getframe(depth+1).f_locals)
2822 2823 ns.pop('self', None)
2823 2824 try:
2824 2825 cmd = formatter.format(cmd, **ns)
2825 2826 except Exception:
2826 2827 # if formatter couldn't format, just let it go untransformed
2827 2828 pass
2828 2829 return cmd
2829 2830
2830 2831 def mktempfile(self, data=None, prefix='ipython_edit_'):
2831 2832 """Make a new tempfile and return its filename.
2832 2833
2833 2834 This makes a call to tempfile.mktemp, but it registers the created
2834 2835 filename internally so ipython cleans it up at exit time.
2835 2836
2836 2837 Optional inputs:
2837 2838
2838 2839 - data(None): if data is given, it gets written out to the temp file
2839 2840 immediately, and the file is closed again."""
2840 2841
2841 2842 filename = tempfile.mktemp('.py', prefix)
2842 2843 self.tempfiles.append(filename)
2843 2844
2844 2845 if data:
2845 2846 tmp_file = open(filename,'w')
2846 2847 tmp_file.write(data)
2847 2848 tmp_file.close()
2848 2849 return filename
2849 2850
2850 2851 # TODO: This should be removed when Term is refactored.
2851 2852 def write(self,data):
2852 2853 """Write a string to the default output"""
2853 2854 io.stdout.write(data)
2854 2855
2855 2856 # TODO: This should be removed when Term is refactored.
2856 2857 def write_err(self,data):
2857 2858 """Write a string to the default error output"""
2858 2859 io.stderr.write(data)
2859 2860
2860 2861 def ask_yes_no(self, prompt, default=None):
2861 2862 if self.quiet:
2862 2863 return True
2863 2864 return ask_yes_no(prompt,default)
2864 2865
2865 2866 def show_usage(self):
2866 2867 """Show a usage message"""
2867 2868 page.page(IPython.core.usage.interactive_usage)
2868 2869
2869 2870 def extract_input_lines(self, range_str, raw=False):
2870 2871 """Return as a string a set of input history slices.
2871 2872
2872 2873 Parameters
2873 2874 ----------
2874 2875 range_str : string
2875 2876 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2876 2877 since this function is for use by magic functions which get their
2877 2878 arguments as strings. The number before the / is the session
2878 2879 number: ~n goes n back from the current session.
2879 2880
2880 2881 Optional Parameters:
2881 2882 - raw(False): by default, the processed input is used. If this is
2882 2883 true, the raw input history is used instead.
2883 2884
2884 2885 Note that slices can be called with two notations:
2885 2886
2886 2887 N:M -> standard python form, means including items N...(M-1).
2887 2888
2888 2889 N-M -> include items N..M (closed endpoint)."""
2889 2890 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2890 2891 return "\n".join(x for _, _, x in lines)
2891 2892
2892 2893 def find_user_code(self, target, raw=True, py_only=False):
2893 2894 """Get a code string from history, file, url, or a string or macro.
2894 2895
2895 2896 This is mainly used by magic functions.
2896 2897
2897 2898 Parameters
2898 2899 ----------
2899 2900
2900 2901 target : str
2901 2902
2902 2903 A string specifying code to retrieve. This will be tried respectively
2903 2904 as: ranges of input history (see %history for syntax), url,
2904 2905 correspnding .py file, filename, or an expression evaluating to a
2905 2906 string or Macro in the user namespace.
2906 2907
2907 2908 raw : bool
2908 2909 If true (default), retrieve raw history. Has no effect on the other
2909 2910 retrieval mechanisms.
2910 2911
2911 2912 py_only : bool (default False)
2912 2913 Only try to fetch python code, do not try alternative methods to decode file
2913 2914 if unicode fails.
2914 2915
2915 2916 Returns
2916 2917 -------
2917 2918 A string of code.
2918 2919
2919 2920 ValueError is raised if nothing is found, and TypeError if it evaluates
2920 2921 to an object of another type. In each case, .args[0] is a printable
2921 2922 message.
2922 2923 """
2923 2924 code = self.extract_input_lines(target, raw=raw) # Grab history
2924 2925 if code:
2925 2926 return code
2926 2927 utarget = unquote_filename(target)
2927 2928 try:
2928 2929 if utarget.startswith(('http://', 'https://')):
2929 2930 return openpy.read_py_url(utarget, skip_encoding_cookie=True)
2930 2931 except UnicodeDecodeError:
2931 2932 if not py_only :
2932 2933 response = urllib.urlopen(target)
2933 2934 return response.read().decode('latin1')
2934 2935 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2935 2936
2936 2937 potential_target = [target]
2937 2938 try :
2938 2939 potential_target.insert(0,get_py_filename(target))
2939 2940 except IOError:
2940 2941 pass
2941 2942
2942 2943 for tgt in potential_target :
2943 2944 if os.path.isfile(tgt): # Read file
2944 2945 try :
2945 2946 return openpy.read_py_file(tgt, skip_encoding_cookie=True)
2946 2947 except UnicodeDecodeError :
2947 2948 if not py_only :
2948 2949 with io_open(tgt,'r', encoding='latin1') as f :
2949 2950 return f.read()
2950 2951 raise ValueError(("'%s' seem to be unreadable.") % target)
2951 2952
2952 2953 try: # User namespace
2953 2954 codeobj = eval(target, self.user_ns)
2954 2955 except Exception:
2955 2956 raise ValueError(("'%s' was not found in history, as a file, url, "
2956 2957 "nor in the user namespace.") % target)
2957 2958 if isinstance(codeobj, basestring):
2958 2959 return codeobj
2959 2960 elif isinstance(codeobj, Macro):
2960 2961 return codeobj.value
2961 2962
2962 2963 raise TypeError("%s is neither a string nor a macro." % target,
2963 2964 codeobj)
2964 2965
2965 2966 #-------------------------------------------------------------------------
2966 2967 # Things related to IPython exiting
2967 2968 #-------------------------------------------------------------------------
2968 2969 def atexit_operations(self):
2969 2970 """This will be executed at the time of exit.
2970 2971
2971 2972 Cleanup operations and saving of persistent data that is done
2972 2973 unconditionally by IPython should be performed here.
2973 2974
2974 2975 For things that may depend on startup flags or platform specifics (such
2975 2976 as having readline or not), register a separate atexit function in the
2976 2977 code that has the appropriate information, rather than trying to
2977 2978 clutter
2978 2979 """
2979 2980 # Close the history session (this stores the end time and line count)
2980 2981 # this must be *before* the tempfile cleanup, in case of temporary
2981 2982 # history db
2982 2983 self.history_manager.end_session()
2983 2984
2984 2985 # Cleanup all tempfiles left around
2985 2986 for tfile in self.tempfiles:
2986 2987 try:
2987 2988 os.unlink(tfile)
2988 2989 except OSError:
2989 2990 pass
2990 2991
2991 2992 # Clear all user namespaces to release all references cleanly.
2992 2993 self.reset(new_session=False)
2993 2994
2994 2995 # Run user hooks
2995 2996 self.hooks.shutdown_hook()
2996 2997
2997 2998 def cleanup(self):
2998 2999 self.restore_sys_module_state()
2999 3000
3000 3001
3001 3002 class InteractiveShellABC(object):
3002 3003 """An abstract base class for InteractiveShell."""
3003 3004 __metaclass__ = abc.ABCMeta
3004 3005
3005 3006 InteractiveShellABC.register(InteractiveShell)
@@ -1,220 +1,220 b''
1 1 """Logger class for IPython's logging facilities.
2 2 """
3 3
4 4 #*****************************************************************************
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 7 #
8 8 # Distributed under the terms of the BSD License. The full license is in
9 9 # the file COPYING, distributed as part of this software.
10 10 #*****************************************************************************
11 11
12 12 #****************************************************************************
13 13 # Modules and globals
14 14
15 15 # Python standard modules
16 16 import glob
17 17 import io
18 18 import os
19 19 import time
20 20
21 21 from IPython.utils.py3compat import str_to_unicode
22 22
23 23 #****************************************************************************
24 24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
25 25 # ipython and does input cache management. Finish cleanup later...
26 26
27 27 class Logger(object):
28 28 """A Logfile class with different policies for file creation"""
29 29
30 30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
31 31 logmode='over'):
32 32
33 33 # this is the full ipython instance, we need some attributes from it
34 34 # which won't exist until later. What a mess, clean up later...
35 35 self.home_dir = home_dir
36 36
37 37 self.logfname = logfname
38 38 self.loghead = loghead
39 39 self.logmode = logmode
40 40 self.logfile = None
41 41
42 42 # Whether to log raw or processed input
43 43 self.log_raw_input = False
44 44
45 45 # whether to also log output
46 46 self.log_output = False
47 47
48 48 # whether to put timestamps before each log entry
49 49 self.timestamp = False
50 50
51 51 # activity control flags
52 52 self.log_active = False
53 53
54 54 # logmode is a validated property
55 55 def _set_mode(self,mode):
56 56 if mode not in ['append','backup','global','over','rotate']:
57 raise ValueError,'invalid log mode %s given' % mode
57 raise ValueError('invalid log mode %s given' % mode)
58 58 self._logmode = mode
59 59
60 60 def _get_mode(self):
61 61 return self._logmode
62 62
63 63 logmode = property(_get_mode,_set_mode)
64 64
65 65 def logstart(self, logfname=None, loghead=None, logmode=None,
66 66 log_output=False, timestamp=False, log_raw_input=False):
67 67 """Generate a new log-file with a default header.
68 68
69 69 Raises RuntimeError if the log has already been started"""
70 70
71 71 if self.logfile is not None:
72 72 raise RuntimeError('Log file is already active: %s' %
73 73 self.logfname)
74 74
75 75 # The parameters can override constructor defaults
76 76 if logfname is not None: self.logfname = logfname
77 77 if loghead is not None: self.loghead = loghead
78 78 if logmode is not None: self.logmode = logmode
79 79
80 80 # Parameters not part of the constructor
81 81 self.timestamp = timestamp
82 82 self.log_output = log_output
83 83 self.log_raw_input = log_raw_input
84 84
85 85 # init depending on the log mode requested
86 86 isfile = os.path.isfile
87 87 logmode = self.logmode
88 88
89 89 if logmode == 'append':
90 90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
91 91
92 92 elif logmode == 'backup':
93 93 if isfile(self.logfname):
94 94 backup_logname = self.logfname+'~'
95 95 # Manually remove any old backup, since os.rename may fail
96 96 # under Windows.
97 97 if isfile(backup_logname):
98 98 os.remove(backup_logname)
99 99 os.rename(self.logfname,backup_logname)
100 100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
101 101
102 102 elif logmode == 'global':
103 103 self.logfname = os.path.join(self.home_dir,self.logfname)
104 104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
105 105
106 106 elif logmode == 'over':
107 107 if isfile(self.logfname):
108 108 os.remove(self.logfname)
109 109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
110 110
111 111 elif logmode == 'rotate':
112 112 if isfile(self.logfname):
113 113 if isfile(self.logfname+'.001~'):
114 114 old = glob.glob(self.logfname+'.*~')
115 115 old.sort()
116 116 old.reverse()
117 117 for f in old:
118 118 root, ext = os.path.splitext(f)
119 119 num = int(ext[1:-1])+1
120 os.rename(f, root+'.'+`num`.zfill(3)+'~')
120 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
121 121 os.rename(self.logfname, self.logfname+'.001~')
122 122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
123 123
124 124 if logmode != 'append':
125 125 self.logfile.write(self.loghead)
126 126
127 127 self.logfile.flush()
128 128 self.log_active = True
129 129
130 130 def switch_log(self,val):
131 131 """Switch logging on/off. val should be ONLY a boolean."""
132 132
133 133 if val not in [False,True,0,1]:
134 raise ValueError, \
135 'Call switch_log ONLY with a boolean argument, not with:',val
134 raise ValueError('Call switch_log ONLY with a boolean argument, '
135 'not with: %s' % val)
136 136
137 137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 138
139 139 if self.logfile is None:
140 140 print """
141 141 Logging hasn't been started yet (use logstart for that).
142 142
143 143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 144 which already exists. But you must first start the logging process with
145 145 %logstart (optionally giving a logfile name)."""
146 146
147 147 else:
148 148 if self.log_active == val:
149 149 print 'Logging is already',label[val]
150 150 else:
151 151 print 'Switching logging',label[val]
152 152 self.log_active = not self.log_active
153 153 self.log_active_out = self.log_active
154 154
155 155 def logstate(self):
156 156 """Print a status message about the logger."""
157 157 if self.logfile is None:
158 158 print 'Logging has not been activated.'
159 159 else:
160 160 state = self.log_active and 'active' or 'temporarily suspended'
161 161 print 'Filename :',self.logfname
162 162 print 'Mode :',self.logmode
163 163 print 'Output logging :',self.log_output
164 164 print 'Raw input log :',self.log_raw_input
165 165 print 'Timestamping :',self.timestamp
166 166 print 'State :',state
167 167
168 168 def log(self, line_mod, line_ori):
169 169 """Write the sources to a log.
170 170
171 171 Inputs:
172 172
173 173 - line_mod: possibly modified input, such as the transformations made
174 174 by input prefilters or input handlers of various kinds. This should
175 175 always be valid Python.
176 176
177 177 - line_ori: unmodified input line from the user. This is not
178 178 necessarily valid Python.
179 179 """
180 180
181 181 # Write the log line, but decide which one according to the
182 182 # log_raw_input flag, set when the log is started.
183 183 if self.log_raw_input:
184 184 self.log_write(line_ori)
185 185 else:
186 186 self.log_write(line_mod)
187 187
188 188 def log_write(self, data, kind='input'):
189 189 """Write data to the log file, if active"""
190 190
191 191 #print 'data: %r' % data # dbg
192 192 if self.log_active and data:
193 193 write = self.logfile.write
194 194 if kind=='input':
195 195 if self.timestamp:
196 196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
197 197 time.localtime())))
198 198 write(data)
199 199 elif kind=='output' and self.log_output:
200 200 odata = u'\n'.join([u'#[Out]# %s' % s
201 201 for s in data.splitlines()])
202 202 write(u'%s\n' % odata)
203 203 self.logfile.flush()
204 204
205 205 def logstop(self):
206 206 """Fully stop logging and close log file.
207 207
208 208 In order to start logging again, a new logstart() call needs to be
209 209 made, possibly (though not necessarily) with a new filename, mode and
210 210 other options."""
211 211
212 212 if self.logfile is not None:
213 213 self.logfile.close()
214 214 self.logfile = None
215 215 else:
216 216 print "Logging hadn't been started."
217 217 self.log_active = False
218 218
219 219 # For backwards compatibility, in case anyone was using this.
220 220 close_log = logstop
@@ -1,617 +1,617 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17 # Stdlib
18 18 import os
19 19 import re
20 20 import sys
21 21 import types
22 22 from getopt import getopt, GetoptError
23 23
24 24 # Our own
25 25 from IPython.config.configurable import Configurable
26 26 from IPython.core import oinspect
27 27 from IPython.core.error import UsageError
28 28 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
29 29 from IPython.external.decorator import decorator
30 30 from IPython.utils.ipstruct import Struct
31 31 from IPython.utils.process import arg_split
32 32 from IPython.utils.text import dedent
33 33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
34 34 from IPython.utils.warn import error, warn
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Globals
38 38 #-----------------------------------------------------------------------------
39 39
40 40 # A dict we'll use for each class that has magics, used as temporary storage to
41 41 # pass information between the @line/cell_magic method decorators and the
42 42 # @magics_class class decorator, because the method decorators have no
43 43 # access to the class when they run. See for more details:
44 44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
45 45
46 46 magics = dict(line={}, cell={})
47 47
48 48 magic_kinds = ('line', 'cell')
49 49 magic_spec = ('line', 'cell', 'line_cell')
50 50 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
51 51
52 52 #-----------------------------------------------------------------------------
53 53 # Utility classes and functions
54 54 #-----------------------------------------------------------------------------
55 55
56 56 class Bunch: pass
57 57
58 58
59 59 def on_off(tag):
60 60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 61 return ['OFF','ON'][tag]
62 62
63 63
64 64 def compress_dhist(dh):
65 65 """Compress a directory history into a new one with at most 20 entries.
66 66
67 67 Return a new list made from the first and last 10 elements of dhist after
68 68 removal of duplicates.
69 69 """
70 70 head, tail = dh[:-10], dh[-10:]
71 71
72 72 newhead = []
73 73 done = set()
74 74 for h in head:
75 75 if h in done:
76 76 continue
77 77 newhead.append(h)
78 78 done.add(h)
79 79
80 80 return newhead + tail
81 81
82 82
83 83 def needs_local_scope(func):
84 84 """Decorator to mark magic functions which need to local scope to run."""
85 85 func.needs_local_scope = True
86 86 return func
87 87
88 88 #-----------------------------------------------------------------------------
89 89 # Class and method decorators for registering magics
90 90 #-----------------------------------------------------------------------------
91 91
92 92 def magics_class(cls):
93 93 """Class decorator for all subclasses of the main Magics class.
94 94
95 95 Any class that subclasses Magics *must* also apply this decorator, to
96 96 ensure that all the methods that have been decorated as line/cell magics
97 97 get correctly registered in the class instance. This is necessary because
98 98 when method decorators run, the class does not exist yet, so they
99 99 temporarily store their information into a module global. Application of
100 100 this class decorator copies that global data to the class instance and
101 101 clears the global.
102 102
103 103 Obviously, this mechanism is not thread-safe, which means that the
104 104 *creation* of subclasses of Magic should only be done in a single-thread
105 105 context. Instantiation of the classes has no restrictions. Given that
106 106 these classes are typically created at IPython startup time and before user
107 107 application code becomes active, in practice this should not pose any
108 108 problems.
109 109 """
110 110 cls.registered = True
111 111 cls.magics = dict(line = magics['line'],
112 112 cell = magics['cell'])
113 113 magics['line'] = {}
114 114 magics['cell'] = {}
115 115 return cls
116 116
117 117
118 118 def record_magic(dct, magic_kind, magic_name, func):
119 119 """Utility function to store a function as a magic of a specific kind.
120 120
121 121 Parameters
122 122 ----------
123 123 dct : dict
124 124 A dictionary with 'line' and 'cell' subdicts.
125 125
126 126 magic_kind : str
127 127 Kind of magic to be stored.
128 128
129 129 magic_name : str
130 130 Key to store the magic as.
131 131
132 132 func : function
133 133 Callable object to store.
134 134 """
135 135 if magic_kind == 'line_cell':
136 136 dct['line'][magic_name] = dct['cell'][magic_name] = func
137 137 else:
138 138 dct[magic_kind][magic_name] = func
139 139
140 140
141 141 def validate_type(magic_kind):
142 142 """Ensure that the given magic_kind is valid.
143 143
144 144 Check that the given magic_kind is one of the accepted spec types (stored
145 145 in the global `magic_spec`), raise ValueError otherwise.
146 146 """
147 147 if magic_kind not in magic_spec:
148 148 raise ValueError('magic_kind must be one of %s, %s given' %
149 149 magic_kinds, magic_kind)
150 150
151 151
152 152 # The docstrings for the decorator below will be fairly similar for the two
153 153 # types (method and function), so we generate them here once and reuse the
154 154 # templates below.
155 155 _docstring_template = \
156 156 """Decorate the given {0} as {1} magic.
157 157
158 158 The decorator can be used with or without arguments, as follows.
159 159
160 160 i) without arguments: it will create a {1} magic named as the {0} being
161 161 decorated::
162 162
163 163 @deco
164 164 def foo(...)
165 165
166 166 will create a {1} magic named `foo`.
167 167
168 168 ii) with one string argument: which will be used as the actual name of the
169 169 resulting magic::
170 170
171 171 @deco('bar')
172 172 def foo(...)
173 173
174 174 will create a {1} magic named `bar`.
175 175 """
176 176
177 177 # These two are decorator factories. While they are conceptually very similar,
178 178 # there are enough differences in the details that it's simpler to have them
179 179 # written as completely standalone functions rather than trying to share code
180 180 # and make a single one with convoluted logic.
181 181
182 182 def _method_magic_marker(magic_kind):
183 183 """Decorator factory for methods in Magics subclasses.
184 184 """
185 185
186 186 validate_type(magic_kind)
187 187
188 188 # This is a closure to capture the magic_kind. We could also use a class,
189 189 # but it's overkill for just that one bit of state.
190 190 def magic_deco(arg):
191 191 call = lambda f, *a, **k: f(*a, **k)
192 192
193 193 if callable(arg):
194 194 # "Naked" decorator call (just @foo, no args)
195 195 func = arg
196 196 name = func.func_name
197 197 retval = decorator(call, func)
198 198 record_magic(magics, magic_kind, name, name)
199 199 elif isinstance(arg, basestring):
200 200 # Decorator called with arguments (@foo('bar'))
201 201 name = arg
202 202 def mark(func, *a, **kw):
203 203 record_magic(magics, magic_kind, name, func.func_name)
204 204 return decorator(call, func)
205 205 retval = mark
206 206 else:
207 207 raise TypeError("Decorator can only be called with "
208 208 "string or function")
209 209 return retval
210 210
211 211 # Ensure the resulting decorator has a usable docstring
212 212 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
213 213 return magic_deco
214 214
215 215
216 216 def _function_magic_marker(magic_kind):
217 217 """Decorator factory for standalone functions.
218 218 """
219 219 validate_type(magic_kind)
220 220
221 221 # This is a closure to capture the magic_kind. We could also use a class,
222 222 # but it's overkill for just that one bit of state.
223 223 def magic_deco(arg):
224 224 call = lambda f, *a, **k: f(*a, **k)
225 225
226 226 # Find get_ipython() in the caller's namespace
227 227 caller = sys._getframe(1)
228 228 for ns in ['f_locals', 'f_globals', 'f_builtins']:
229 229 get_ipython = getattr(caller, ns).get('get_ipython')
230 230 if get_ipython is not None:
231 231 break
232 232 else:
233 233 raise NameError('Decorator can only run in context where '
234 234 '`get_ipython` exists')
235 235
236 236 ip = get_ipython()
237 237
238 238 if callable(arg):
239 239 # "Naked" decorator call (just @foo, no args)
240 240 func = arg
241 241 name = func.func_name
242 242 ip.register_magic_function(func, magic_kind, name)
243 243 retval = decorator(call, func)
244 244 elif isinstance(arg, basestring):
245 245 # Decorator called with arguments (@foo('bar'))
246 246 name = arg
247 247 def mark(func, *a, **kw):
248 248 ip.register_magic_function(func, magic_kind, name)
249 249 return decorator(call, func)
250 250 retval = mark
251 251 else:
252 252 raise TypeError("Decorator can only be called with "
253 253 "string or function")
254 254 return retval
255 255
256 256 # Ensure the resulting decorator has a usable docstring
257 257 ds = _docstring_template.format('function', magic_kind)
258 258
259 259 ds += dedent("""
260 260 Note: this decorator can only be used in a context where IPython is already
261 261 active, so that the `get_ipython()` call succeeds. You can therefore use
262 262 it in your startup files loaded after IPython initializes, but *not* in the
263 263 IPython configuration file itself, which is executed before IPython is
264 264 fully up and running. Any file located in the `startup` subdirectory of
265 265 your configuration profile will be OK in this sense.
266 266 """)
267 267
268 268 magic_deco.__doc__ = ds
269 269 return magic_deco
270 270
271 271
272 272 # Create the actual decorators for public use
273 273
274 274 # These three are used to decorate methods in class definitions
275 275 line_magic = _method_magic_marker('line')
276 276 cell_magic = _method_magic_marker('cell')
277 277 line_cell_magic = _method_magic_marker('line_cell')
278 278
279 279 # These three decorate standalone functions and perform the decoration
280 280 # immediately. They can only run where get_ipython() works
281 281 register_line_magic = _function_magic_marker('line')
282 282 register_cell_magic = _function_magic_marker('cell')
283 283 register_line_cell_magic = _function_magic_marker('line_cell')
284 284
285 285 #-----------------------------------------------------------------------------
286 286 # Core Magic classes
287 287 #-----------------------------------------------------------------------------
288 288
289 289 class MagicsManager(Configurable):
290 290 """Object that handles all magic-related functionality for IPython.
291 291 """
292 292 # Non-configurable class attributes
293 293
294 294 # A two-level dict, first keyed by magic type, then by magic function, and
295 295 # holding the actual callable object as value. This is the dict used for
296 296 # magic function dispatch
297 297 magics = Dict
298 298
299 299 # A registry of the original objects that we've been given holding magics.
300 300 registry = Dict
301 301
302 302 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
303 303
304 304 auto_magic = Bool(True, config=True, help=
305 305 "Automatically call line magics without requiring explicit % prefix")
306 306
307 307 _auto_status = [
308 308 'Automagic is OFF, % prefix IS needed for line magics.',
309 309 'Automagic is ON, % prefix IS NOT needed for line magics.']
310 310
311 311 user_magics = Instance('IPython.core.magics.UserMagics')
312 312
313 313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
314 314
315 315 super(MagicsManager, self).__init__(shell=shell, config=config,
316 316 user_magics=user_magics, **traits)
317 317 self.magics = dict(line={}, cell={})
318 318 # Let's add the user_magics to the registry for uniformity, so *all*
319 319 # registered magic containers can be found there.
320 320 self.registry[user_magics.__class__.__name__] = user_magics
321 321
322 322 def auto_status(self):
323 323 """Return descriptive string with automagic status."""
324 324 return self._auto_status[self.auto_magic]
325 325
326 326 def lsmagic_info(self):
327 327 magic_list = []
328 328 for m_type in self.magics :
329 329 for m_name,mgc in self.magics[m_type].items():
330 330 try :
331 331 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
332 332 except AttributeError :
333 333 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
334 334 return magic_list
335 335
336 336 def lsmagic(self):
337 337 """Return a dict of currently available magic functions.
338 338
339 339 The return dict has the keys 'line' and 'cell', corresponding to the
340 340 two types of magics we support. Each value is a list of names.
341 341 """
342 342 return self.magics
343 343
344 344 def lsmagic_docs(self, brief=False, missing=''):
345 345 """Return dict of documentation of magic functions.
346 346
347 347 The return dict has the keys 'line' and 'cell', corresponding to the
348 348 two types of magics we support. Each value is a dict keyed by magic
349 349 name whose value is the function docstring. If a docstring is
350 350 unavailable, the value of `missing` is used instead.
351 351
352 352 If brief is True, only the first line of each docstring will be returned.
353 353 """
354 354 docs = {}
355 355 for m_type in self.magics:
356 356 m_docs = {}
357 357 for m_name, m_func in self.magics[m_type].iteritems():
358 358 if m_func.__doc__:
359 359 if brief:
360 360 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
361 361 else:
362 362 m_docs[m_name] = m_func.__doc__.rstrip()
363 363 else:
364 364 m_docs[m_name] = missing
365 365 docs[m_type] = m_docs
366 366 return docs
367 367
368 368 def register(self, *magic_objects):
369 369 """Register one or more instances of Magics.
370 370
371 371 Take one or more classes or instances of classes that subclass the main
372 372 `core.Magic` class, and register them with IPython to use the magic
373 373 functions they provide. The registration process will then ensure that
374 374 any methods that have decorated to provide line and/or cell magics will
375 375 be recognized with the `%x`/`%%x` syntax as a line/cell magic
376 376 respectively.
377 377
378 378 If classes are given, they will be instantiated with the default
379 379 constructor. If your classes need a custom constructor, you should
380 380 instanitate them first and pass the instance.
381 381
382 382 The provided arguments can be an arbitrary mix of classes and instances.
383 383
384 384 Parameters
385 385 ----------
386 386 magic_objects : one or more classes or instances
387 387 """
388 388 # Start by validating them to ensure they have all had their magic
389 389 # methods registered at the instance level
390 390 for m in magic_objects:
391 391 if not m.registered:
392 392 raise ValueError("Class of magics %r was constructed without "
393 393 "the @register_magics class decorator")
394 394 if type(m) in (type, MetaHasTraits):
395 395 # If we're given an uninstantiated class
396 396 m = m(shell=self.shell)
397 397
398 398 # Now that we have an instance, we can register it and update the
399 399 # table of callables
400 400 self.registry[m.__class__.__name__] = m
401 401 for mtype in magic_kinds:
402 402 self.magics[mtype].update(m.magics[mtype])
403 403
404 404 def register_function(self, func, magic_kind='line', magic_name=None):
405 405 """Expose a standalone function as magic function for IPython.
406 406
407 407 This will create an IPython magic (line, cell or both) from a
408 408 standalone function. The functions should have the following
409 409 signatures:
410 410
411 411 * For line magics: `def f(line)`
412 412 * For cell magics: `def f(line, cell)`
413 413 * For a function that does both: `def f(line, cell=None)`
414 414
415 415 In the latter case, the function will be called with `cell==None` when
416 416 invoked as `%f`, and with cell as a string when invoked as `%%f`.
417 417
418 418 Parameters
419 419 ----------
420 420 func : callable
421 421 Function to be registered as a magic.
422 422
423 423 magic_kind : str
424 424 Kind of magic, one of 'line', 'cell' or 'line_cell'
425 425
426 426 magic_name : optional str
427 427 If given, the name the magic will have in the IPython namespace. By
428 428 default, the name of the function itself is used.
429 429 """
430 430
431 431 # Create the new method in the user_magics and register it in the
432 432 # global table
433 433 validate_type(magic_kind)
434 434 magic_name = func.func_name if magic_name is None else magic_name
435 435 setattr(self.user_magics, magic_name, func)
436 436 record_magic(self.magics, magic_kind, magic_name, func)
437 437
438 438 def define_magic(self, name, func):
439 439 """[Deprecated] Expose own function as magic function for IPython.
440 440
441 441 Example::
442 442
443 443 def foo_impl(self, parameter_s=''):
444 444 'My very own magic!. (Use docstrings, IPython reads them).'
445 445 print 'Magic function. Passed parameter is between < >:'
446 446 print '<%s>' % parameter_s
447 447 print 'The self object is:', self
448 448
449 449 ip.define_magic('foo',foo_impl)
450 450 """
451 451 meth = types.MethodType(func, self.user_magics)
452 452 setattr(self.user_magics, name, meth)
453 453 record_magic(self.magics, 'line', name, meth)
454 454
455 455 # Key base class that provides the central functionality for magics.
456 456
457 457 class Magics(object):
458 458 """Base class for implementing magic functions.
459 459
460 460 Shell functions which can be reached as %function_name. All magic
461 461 functions should accept a string, which they can parse for their own
462 462 needs. This can make some functions easier to type, eg `%cd ../`
463 463 vs. `%cd("../")`
464 464
465 465 Classes providing magic functions need to subclass this class, and they
466 466 MUST:
467 467
468 468 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
469 469 individual methods as magic functions, AND
470 470
471 471 - Use the class decorator `@magics_class` to ensure that the magic
472 472 methods are properly registered at the instance level upon instance
473 473 initialization.
474 474
475 475 See :mod:`magic_functions` for examples of actual implementation classes.
476 476 """
477 477 # Dict holding all command-line options for each magic.
478 478 options_table = None
479 479 # Dict for the mapping of magic names to methods, set by class decorator
480 480 magics = None
481 481 # Flag to check that the class decorator was properly applied
482 482 registered = False
483 483 # Instance of IPython shell
484 484 shell = None
485 485
486 486 def __init__(self, shell):
487 487 if not(self.__class__.registered):
488 488 raise ValueError('Magics subclass without registration - '
489 489 'did you forget to apply @magics_class?')
490 490 self.shell = shell
491 491 self.options_table = {}
492 492 # The method decorators are run when the instance doesn't exist yet, so
493 493 # they can only record the names of the methods they are supposed to
494 494 # grab. Only now, that the instance exists, can we create the proper
495 495 # mapping to bound methods. So we read the info off the original names
496 496 # table and replace each method name by the actual bound method.
497 497 # But we mustn't clobber the *class* mapping, in case of multiple instances.
498 498 class_magics = self.magics
499 499 self.magics = {}
500 500 for mtype in magic_kinds:
501 501 tab = self.magics[mtype] = {}
502 502 cls_tab = class_magics[mtype]
503 503 for magic_name, meth_name in cls_tab.iteritems():
504 504 if isinstance(meth_name, basestring):
505 505 # it's a method name, grab it
506 506 tab[magic_name] = getattr(self, meth_name)
507 507 else:
508 508 # it's the real thing
509 509 tab[magic_name] = meth_name
510 510
511 511 def arg_err(self,func):
512 512 """Print docstring if incorrect arguments were passed"""
513 513 print 'Error in arguments:'
514 514 print oinspect.getdoc(func)
515 515
516 516 def format_latex(self, strng):
517 517 """Format a string for latex inclusion."""
518 518
519 519 # Characters that need to be escaped for latex:
520 520 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
521 521 # Magic command names as headers:
522 522 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
523 523 re.MULTILINE)
524 524 # Magic commands
525 525 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
526 526 re.MULTILINE)
527 527 # Paragraph continue
528 528 par_re = re.compile(r'\\$',re.MULTILINE)
529 529
530 530 # The "\n" symbol
531 531 newline_re = re.compile(r'\\n')
532 532
533 533 # Now build the string for output:
534 534 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
535 535 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
536 536 strng)
537 537 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
538 538 strng = par_re.sub(r'\\\\',strng)
539 539 strng = escape_re.sub(r'\\\1',strng)
540 540 strng = newline_re.sub(r'\\textbackslash{}n',strng)
541 541 return strng
542 542
543 543 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
544 544 """Parse options passed to an argument string.
545 545
546 546 The interface is similar to that of getopt(), but it returns back a
547 547 Struct with the options as keys and the stripped argument string still
548 548 as a string.
549 549
550 550 arg_str is quoted as a true sys.argv vector by using shlex.split.
551 551 This allows us to easily expand variables, glob files, quote
552 552 arguments, etc.
553 553
554 554 Options:
555 555 -mode: default 'string'. If given as 'list', the argument string is
556 556 returned as a list (split on whitespace) instead of a string.
557 557
558 558 -list_all: put all option values in lists. Normally only options
559 559 appearing more than once are put in a list.
560 560
561 561 -posix (True): whether to split the input line in POSIX mode or not,
562 562 as per the conventions outlined in the shlex module from the
563 563 standard library."""
564 564
565 565 # inject default options at the beginning of the input line
566 566 caller = sys._getframe(1).f_code.co_name
567 567 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
568 568
569 569 mode = kw.get('mode','string')
570 570 if mode not in ['string','list']:
571 raise ValueError,'incorrect mode given: %s' % mode
571 raise ValueError('incorrect mode given: %s' % mode)
572 572 # Get options
573 573 list_all = kw.get('list_all',0)
574 574 posix = kw.get('posix', os.name == 'posix')
575 575 strict = kw.get('strict', True)
576 576
577 577 # Check if we have more than one argument to warrant extra processing:
578 578 odict = {} # Dictionary with options
579 579 args = arg_str.split()
580 580 if len(args) >= 1:
581 581 # If the list of inputs only has 0 or 1 thing in it, there's no
582 582 # need to look for options
583 583 argv = arg_split(arg_str, posix, strict)
584 584 # Do regular option processing
585 585 try:
586 586 opts,args = getopt(argv, opt_str, long_opts)
587 587 except GetoptError as e:
588 588 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
589 589 " ".join(long_opts)))
590 590 for o,a in opts:
591 591 if o.startswith('--'):
592 592 o = o[2:]
593 593 else:
594 594 o = o[1:]
595 595 try:
596 596 odict[o].append(a)
597 597 except AttributeError:
598 598 odict[o] = [odict[o],a]
599 599 except KeyError:
600 600 if list_all:
601 601 odict[o] = [a]
602 602 else:
603 603 odict[o] = a
604 604
605 605 # Prepare opts,args for return
606 606 opts = Struct(odict)
607 607 if mode == 'string':
608 608 args = ' '.join(args)
609 609
610 610 return opts,args
611 611
612 612 def default_option(self, fn, optstr):
613 613 """Make an entry in the options_table for fn, with value optstr"""
614 614
615 615 if fn not in self.lsmagic():
616 616 error("%s is not a magic function" % fn)
617 617 self.options_table[fn] = optstr
@@ -1,1022 +1,1022 b''
1 1 """Implementation of execution-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import __builtin__ as builtin_mod
17 17 import bdb
18 18 import os
19 19 import sys
20 20 import time
21 21 from StringIO import StringIO
22 22
23 23 # cProfile was added in Python2.5
24 24 try:
25 25 import cProfile as profile
26 26 import pstats
27 27 except ImportError:
28 28 # profile isn't bundled by default in Debian for license reasons
29 29 try:
30 30 import profile, pstats
31 31 except ImportError:
32 32 profile = pstats = None
33 33
34 34 # Our own packages
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import magic_arguments
37 37 from IPython.core import page
38 38 from IPython.core.error import UsageError
39 39 from IPython.core.macro import Macro
40 40 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
41 41 line_cell_magic, on_off, needs_local_scope)
42 42 from IPython.testing.skipdoctest import skip_doctest
43 43 from IPython.utils import py3compat
44 44 from IPython.utils.io import capture_output
45 45 from IPython.utils.ipstruct import Struct
46 46 from IPython.utils.module_paths import find_mod
47 47 from IPython.utils.path import get_py_filename, unquote_filename
48 48 from IPython.utils.timing import clock, clock2
49 49 from IPython.utils.warn import warn, error
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Magic implementation classes
53 53 #-----------------------------------------------------------------------------
54 54
55 55 @magics_class
56 56 class ExecutionMagics(Magics):
57 57 """Magics related to code execution, debugging, profiling, etc.
58 58
59 59 """
60 60
61 61 def __init__(self, shell):
62 62 super(ExecutionMagics, self).__init__(shell)
63 63 if profile is None:
64 64 self.prun = self.profile_missing_notice
65 65 # Default execution function used to actually run user code.
66 66 self.default_runner = None
67 67
68 68 def profile_missing_notice(self, *args, **kwargs):
69 69 error("""\
70 70 The profile module could not be found. It has been removed from the standard
71 71 python packages because of its non-free license. To use profiling, install the
72 72 python-profiler package from non-free.""")
73 73
74 74 @skip_doctest
75 75 @line_cell_magic
76 76 def prun(self, parameter_s='', cell=None, user_mode=True,
77 77 opts=None,arg_lst=None,prog_ns=None):
78 78
79 79 """Run a statement through the python code profiler.
80 80
81 81 Usage, in line mode:
82 82 %prun [options] statement
83 83
84 84 Usage, in cell mode:
85 85 %%prun [options] [statement]
86 86 code...
87 87 code...
88 88
89 89 In cell mode, the additional code lines are appended to the (possibly
90 90 empty) statement in the first line. Cell mode allows you to easily
91 91 profile multiline blocks without having to put them in a separate
92 92 function.
93 93
94 94 The given statement (which doesn't require quote marks) is run via the
95 95 python profiler in a manner similar to the profile.run() function.
96 96 Namespaces are internally managed to work correctly; profile.run
97 97 cannot be used in IPython because it makes certain assumptions about
98 98 namespaces which do not hold under IPython.
99 99
100 100 Options:
101 101
102 102 -l <limit>: you can place restrictions on what or how much of the
103 103 profile gets printed. The limit value can be:
104 104
105 105 * A string: only information for function names containing this string
106 106 is printed.
107 107
108 108 * An integer: only these many lines are printed.
109 109
110 110 * A float (between 0 and 1): this fraction of the report is printed
111 111 (for example, use a limit of 0.4 to see the topmost 40% only).
112 112
113 113 You can combine several limits with repeated use of the option. For
114 114 example, '-l __init__ -l 5' will print only the topmost 5 lines of
115 115 information about class constructors.
116 116
117 117 -r: return the pstats.Stats object generated by the profiling. This
118 118 object has all the information about the profile in it, and you can
119 119 later use it for further analysis or in other functions.
120 120
121 121 -s <key>: sort profile by given key. You can provide more than one key
122 122 by using the option several times: '-s key1 -s key2 -s key3...'. The
123 123 default sorting key is 'time'.
124 124
125 125 The following is copied verbatim from the profile documentation
126 126 referenced below:
127 127
128 128 When more than one key is provided, additional keys are used as
129 129 secondary criteria when the there is equality in all keys selected
130 130 before them.
131 131
132 132 Abbreviations can be used for any key names, as long as the
133 133 abbreviation is unambiguous. The following are the keys currently
134 134 defined:
135 135
136 136 Valid Arg Meaning
137 137 "calls" call count
138 138 "cumulative" cumulative time
139 139 "file" file name
140 140 "module" file name
141 141 "pcalls" primitive call count
142 142 "line" line number
143 143 "name" function name
144 144 "nfl" name/file/line
145 145 "stdname" standard name
146 146 "time" internal time
147 147
148 148 Note that all sorts on statistics are in descending order (placing
149 149 most time consuming items first), where as name, file, and line number
150 150 searches are in ascending order (i.e., alphabetical). The subtle
151 151 distinction between "nfl" and "stdname" is that the standard name is a
152 152 sort of the name as printed, which means that the embedded line
153 153 numbers get compared in an odd way. For example, lines 3, 20, and 40
154 154 would (if the file names were the same) appear in the string order
155 155 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
156 156 line numbers. In fact, sort_stats("nfl") is the same as
157 157 sort_stats("name", "file", "line").
158 158
159 159 -T <filename>: save profile results as shown on screen to a text
160 160 file. The profile is still shown on screen.
161 161
162 162 -D <filename>: save (via dump_stats) profile statistics to given
163 163 filename. This data is in a format understood by the pstats module, and
164 164 is generated by a call to the dump_stats() method of profile
165 165 objects. The profile is still shown on screen.
166 166
167 167 -q: suppress output to the pager. Best used with -T and/or -D above.
168 168
169 169 If you want to run complete programs under the profiler's control, use
170 170 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
171 171 contains profiler specific options as described here.
172 172
173 173 You can read the complete documentation for the profile module with::
174 174
175 175 In [1]: import profile; profile.help()
176 176 """
177 177
178 178 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
179 179
180 180 if user_mode: # regular user call
181 181 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
182 182 list_all=True, posix=False)
183 183 namespace = self.shell.user_ns
184 184 if cell is not None:
185 185 arg_str += '\n' + cell
186 186 else: # called to run a program by %run -p
187 187 try:
188 188 filename = get_py_filename(arg_lst[0])
189 189 except IOError as e:
190 190 try:
191 191 msg = str(e)
192 192 except UnicodeError:
193 193 msg = e.message
194 194 error(msg)
195 195 return
196 196
197 197 arg_str = 'execfile(filename,prog_ns)'
198 198 namespace = {
199 199 'execfile': self.shell.safe_execfile,
200 200 'prog_ns': prog_ns,
201 201 'filename': filename
202 202 }
203 203
204 204 opts.merge(opts_def)
205 205
206 206 prof = profile.Profile()
207 207 try:
208 208 prof = prof.runctx(arg_str,namespace,namespace)
209 209 sys_exit = ''
210 210 except SystemExit:
211 211 sys_exit = """*** SystemExit exception caught in code being profiled."""
212 212
213 213 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
214 214
215 215 lims = opts.l
216 216 if lims:
217 217 lims = [] # rebuild lims with ints/floats/strings
218 218 for lim in opts.l:
219 219 try:
220 220 lims.append(int(lim))
221 221 except ValueError:
222 222 try:
223 223 lims.append(float(lim))
224 224 except ValueError:
225 225 lims.append(lim)
226 226
227 227 # Trap output.
228 228 stdout_trap = StringIO()
229 229
230 230 if hasattr(stats,'stream'):
231 231 # In newer versions of python, the stats object has a 'stream'
232 232 # attribute to write into.
233 233 stats.stream = stdout_trap
234 234 stats.print_stats(*lims)
235 235 else:
236 236 # For older versions, we manually redirect stdout during printing
237 237 sys_stdout = sys.stdout
238 238 try:
239 239 sys.stdout = stdout_trap
240 240 stats.print_stats(*lims)
241 241 finally:
242 242 sys.stdout = sys_stdout
243 243
244 244 output = stdout_trap.getvalue()
245 245 output = output.rstrip()
246 246
247 247 if 'q' not in opts:
248 248 page.page(output)
249 249 print sys_exit,
250 250
251 251 dump_file = opts.D[0]
252 252 text_file = opts.T[0]
253 253 if dump_file:
254 254 dump_file = unquote_filename(dump_file)
255 255 prof.dump_stats(dump_file)
256 256 print '\n*** Profile stats marshalled to file',\
257 `dump_file`+'.',sys_exit
257 repr(dump_file)+'.',sys_exit
258 258 if text_file:
259 259 text_file = unquote_filename(text_file)
260 260 pfile = open(text_file,'w')
261 261 pfile.write(output)
262 262 pfile.close()
263 263 print '\n*** Profile printout saved to text file',\
264 `text_file`+'.',sys_exit
264 repr(text_file)+'.',sys_exit
265 265
266 266 if opts.has_key('r'):
267 267 return stats
268 268 else:
269 269 return None
270 270
271 271 @line_magic
272 272 def pdb(self, parameter_s=''):
273 273 """Control the automatic calling of the pdb interactive debugger.
274 274
275 275 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
276 276 argument it works as a toggle.
277 277
278 278 When an exception is triggered, IPython can optionally call the
279 279 interactive pdb debugger after the traceback printout. %pdb toggles
280 280 this feature on and off.
281 281
282 282 The initial state of this feature is set in your configuration
283 283 file (the option is ``InteractiveShell.pdb``).
284 284
285 285 If you want to just activate the debugger AFTER an exception has fired,
286 286 without having to type '%pdb on' and rerunning your code, you can use
287 287 the %debug magic."""
288 288
289 289 par = parameter_s.strip().lower()
290 290
291 291 if par:
292 292 try:
293 293 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
294 294 except KeyError:
295 295 print ('Incorrect argument. Use on/1, off/0, '
296 296 'or nothing for a toggle.')
297 297 return
298 298 else:
299 299 # toggle
300 300 new_pdb = not self.shell.call_pdb
301 301
302 302 # set on the shell
303 303 self.shell.call_pdb = new_pdb
304 304 print 'Automatic pdb calling has been turned',on_off(new_pdb)
305 305
306 306 @line_magic
307 307 def debug(self, parameter_s=''):
308 308 """Activate the interactive debugger in post-mortem mode.
309 309
310 310 If an exception has just occurred, this lets you inspect its stack
311 311 frames interactively. Note that this will always work only on the last
312 312 traceback that occurred, so you must call this quickly after an
313 313 exception that you wish to inspect has fired, because if another one
314 314 occurs, it clobbers the previous one.
315 315
316 316 If you want IPython to automatically do this on every exception, see
317 317 the %pdb magic for more details.
318 318 """
319 319 self.shell.debugger(force=True)
320 320
321 321 @line_magic
322 322 def tb(self, s):
323 323 """Print the last traceback with the currently active exception mode.
324 324
325 325 See %xmode for changing exception reporting modes."""
326 326 self.shell.showtraceback()
327 327
328 328 @skip_doctest
329 329 @line_magic
330 330 def run(self, parameter_s='', runner=None,
331 331 file_finder=get_py_filename):
332 332 """Run the named file inside IPython as a program.
333 333
334 334 Usage:\\
335 335 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
336 336
337 337 Parameters after the filename are passed as command-line arguments to
338 338 the program (put in sys.argv). Then, control returns to IPython's
339 339 prompt.
340 340
341 341 This is similar to running at a system prompt:\\
342 342 $ python file args\\
343 343 but with the advantage of giving you IPython's tracebacks, and of
344 344 loading all variables into your interactive namespace for further use
345 345 (unless -p is used, see below).
346 346
347 347 The file is executed in a namespace initially consisting only of
348 348 __name__=='__main__' and sys.argv constructed as indicated. It thus
349 349 sees its environment as if it were being run as a stand-alone program
350 350 (except for sharing global objects such as previously imported
351 351 modules). But after execution, the IPython interactive namespace gets
352 352 updated with all variables defined in the program (except for __name__
353 353 and sys.argv). This allows for very convenient loading of code for
354 354 interactive work, while giving each program a 'clean sheet' to run in.
355 355
356 356 Options:
357 357
358 358 -n: __name__ is NOT set to '__main__', but to the running file's name
359 359 without extension (as python does under import). This allows running
360 360 scripts and reloading the definitions in them without calling code
361 361 protected by an ' if __name__ == "__main__" ' clause.
362 362
363 363 -i: run the file in IPython's namespace instead of an empty one. This
364 364 is useful if you are experimenting with code written in a text editor
365 365 which depends on variables defined interactively.
366 366
367 367 -e: ignore sys.exit() calls or SystemExit exceptions in the script
368 368 being run. This is particularly useful if IPython is being used to
369 369 run unittests, which always exit with a sys.exit() call. In such
370 370 cases you are interested in the output of the test results, not in
371 371 seeing a traceback of the unittest module.
372 372
373 373 -t: print timing information at the end of the run. IPython will give
374 374 you an estimated CPU time consumption for your script, which under
375 375 Unix uses the resource module to avoid the wraparound problems of
376 376 time.clock(). Under Unix, an estimate of time spent on system tasks
377 377 is also given (for Windows platforms this is reported as 0.0).
378 378
379 379 If -t is given, an additional -N<N> option can be given, where <N>
380 380 must be an integer indicating how many times you want the script to
381 381 run. The final timing report will include total and per run results.
382 382
383 383 For example (testing the script uniq_stable.py)::
384 384
385 385 In [1]: run -t uniq_stable
386 386
387 387 IPython CPU timings (estimated):\\
388 388 User : 0.19597 s.\\
389 389 System: 0.0 s.\\
390 390
391 391 In [2]: run -t -N5 uniq_stable
392 392
393 393 IPython CPU timings (estimated):\\
394 394 Total runs performed: 5\\
395 395 Times : Total Per run\\
396 396 User : 0.910862 s, 0.1821724 s.\\
397 397 System: 0.0 s, 0.0 s.
398 398
399 399 -d: run your program under the control of pdb, the Python debugger.
400 400 This allows you to execute your program step by step, watch variables,
401 401 etc. Internally, what IPython does is similar to calling:
402 402
403 403 pdb.run('execfile("YOURFILENAME")')
404 404
405 405 with a breakpoint set on line 1 of your file. You can change the line
406 406 number for this automatic breakpoint to be <N> by using the -bN option
407 407 (where N must be an integer). For example::
408 408
409 409 %run -d -b40 myscript
410 410
411 411 will set the first breakpoint at line 40 in myscript.py. Note that
412 412 the first breakpoint must be set on a line which actually does
413 413 something (not a comment or docstring) for it to stop execution.
414 414
415 415 When the pdb debugger starts, you will see a (Pdb) prompt. You must
416 416 first enter 'c' (without quotes) to start execution up to the first
417 417 breakpoint.
418 418
419 419 Entering 'help' gives information about the use of the debugger. You
420 420 can easily see pdb's full documentation with "import pdb;pdb.help()"
421 421 at a prompt.
422 422
423 423 -p: run program under the control of the Python profiler module (which
424 424 prints a detailed report of execution times, function calls, etc).
425 425
426 426 You can pass other options after -p which affect the behavior of the
427 427 profiler itself. See the docs for %prun for details.
428 428
429 429 In this mode, the program's variables do NOT propagate back to the
430 430 IPython interactive namespace (because they remain in the namespace
431 431 where the profiler executes them).
432 432
433 433 Internally this triggers a call to %prun, see its documentation for
434 434 details on the options available specifically for profiling.
435 435
436 436 There is one special usage for which the text above doesn't apply:
437 437 if the filename ends with .ipy, the file is run as ipython script,
438 438 just as if the commands were written on IPython prompt.
439 439
440 440 -m: specify module name to load instead of script path. Similar to
441 441 the -m option for the python interpreter. Use this option last if you
442 442 want to combine with other %run options. Unlike the python interpreter
443 443 only source modules are allowed no .pyc or .pyo files.
444 444 For example::
445 445
446 446 %run -m example
447 447
448 448 will run the example module.
449 449
450 450 """
451 451
452 452 # get arguments and set sys.argv for program to be run.
453 453 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
454 454 mode='list', list_all=1)
455 455 if "m" in opts:
456 456 modulename = opts["m"][0]
457 457 modpath = find_mod(modulename)
458 458 if modpath is None:
459 459 warn('%r is not a valid modulename on sys.path'%modulename)
460 460 return
461 461 arg_lst = [modpath] + arg_lst
462 462 try:
463 463 filename = file_finder(arg_lst[0])
464 464 except IndexError:
465 465 warn('you must provide at least a filename.')
466 466 print '\n%run:\n', oinspect.getdoc(self.run)
467 467 return
468 468 except IOError as e:
469 469 try:
470 470 msg = str(e)
471 471 except UnicodeError:
472 472 msg = e.message
473 473 error(msg)
474 474 return
475 475
476 476 if filename.lower().endswith('.ipy'):
477 477 self.shell.safe_execfile_ipy(filename)
478 478 return
479 479
480 480 # Control the response to exit() calls made by the script being run
481 481 exit_ignore = 'e' in opts
482 482
483 483 # Make sure that the running script gets a proper sys.argv as if it
484 484 # were run from a system shell.
485 485 save_argv = sys.argv # save it for later restoring
486 486
487 487 # simulate shell expansion on arguments, at least tilde expansion
488 488 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
489 489
490 490 sys.argv = [filename] + args # put in the proper filename
491 491 # protect sys.argv from potential unicode strings on Python 2:
492 492 if not py3compat.PY3:
493 493 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
494 494
495 495 if 'i' in opts:
496 496 # Run in user's interactive namespace
497 497 prog_ns = self.shell.user_ns
498 498 __name__save = self.shell.user_ns['__name__']
499 499 prog_ns['__name__'] = '__main__'
500 500 main_mod = self.shell.new_main_mod(prog_ns)
501 501 else:
502 502 # Run in a fresh, empty namespace
503 503 if 'n' in opts:
504 504 name = os.path.splitext(os.path.basename(filename))[0]
505 505 else:
506 506 name = '__main__'
507 507
508 508 main_mod = self.shell.new_main_mod()
509 509 prog_ns = main_mod.__dict__
510 510 prog_ns['__name__'] = name
511 511
512 512 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
513 513 # set the __file__ global in the script's namespace
514 514 prog_ns['__file__'] = filename
515 515
516 516 # pickle fix. See interactiveshell for an explanation. But we need to
517 517 # make sure that, if we overwrite __main__, we replace it at the end
518 518 main_mod_name = prog_ns['__name__']
519 519
520 520 if main_mod_name == '__main__':
521 521 restore_main = sys.modules['__main__']
522 522 else:
523 523 restore_main = False
524 524
525 525 # This needs to be undone at the end to prevent holding references to
526 526 # every single object ever created.
527 527 sys.modules[main_mod_name] = main_mod
528 528
529 529 try:
530 530 stats = None
531 531 with self.shell.readline_no_record:
532 532 if 'p' in opts:
533 533 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
534 534 else:
535 535 if 'd' in opts:
536 536 deb = debugger.Pdb(self.shell.colors)
537 537 # reset Breakpoint state, which is moronically kept
538 538 # in a class
539 539 bdb.Breakpoint.next = 1
540 540 bdb.Breakpoint.bplist = {}
541 541 bdb.Breakpoint.bpbynumber = [None]
542 542 # Set an initial breakpoint to stop execution
543 543 maxtries = 10
544 544 bp = int(opts.get('b', [1])[0])
545 545 checkline = deb.checkline(filename, bp)
546 546 if not checkline:
547 547 for bp in range(bp + 1, bp + maxtries + 1):
548 548 if deb.checkline(filename, bp):
549 549 break
550 550 else:
551 551 msg = ("\nI failed to find a valid line to set "
552 552 "a breakpoint\n"
553 553 "after trying up to line: %s.\n"
554 554 "Please set a valid breakpoint manually "
555 555 "with the -b option." % bp)
556 556 error(msg)
557 557 return
558 558 # if we find a good linenumber, set the breakpoint
559 559 deb.do_break('%s:%s' % (filename, bp))
560 560 # Start file run
561 561 print "NOTE: Enter 'c' at the",
562 562 print "%s prompt to start your script." % deb.prompt
563 563 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
564 564 try:
565 565 deb.run('execfile("%s", prog_ns)' % filename, ns)
566 566
567 567 except:
568 568 etype, value, tb = sys.exc_info()
569 569 # Skip three frames in the traceback: the %run one,
570 570 # one inside bdb.py, and the command-line typed by the
571 571 # user (run by exec in pdb itself).
572 572 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
573 573 else:
574 574 if runner is None:
575 575 runner = self.default_runner
576 576 if runner is None:
577 577 runner = self.shell.safe_execfile
578 578 if 't' in opts:
579 579 # timed execution
580 580 try:
581 581 nruns = int(opts['N'][0])
582 582 if nruns < 1:
583 583 error('Number of runs must be >=1')
584 584 return
585 585 except (KeyError):
586 586 nruns = 1
587 587 twall0 = time.time()
588 588 if nruns == 1:
589 589 t0 = clock2()
590 590 runner(filename, prog_ns, prog_ns,
591 591 exit_ignore=exit_ignore)
592 592 t1 = clock2()
593 593 t_usr = t1[0] - t0[0]
594 594 t_sys = t1[1] - t0[1]
595 595 print "\nIPython CPU timings (estimated):"
596 596 print " User : %10.2f s." % t_usr
597 597 print " System : %10.2f s." % t_sys
598 598 else:
599 599 runs = range(nruns)
600 600 t0 = clock2()
601 601 for nr in runs:
602 602 runner(filename, prog_ns, prog_ns,
603 603 exit_ignore=exit_ignore)
604 604 t1 = clock2()
605 605 t_usr = t1[0] - t0[0]
606 606 t_sys = t1[1] - t0[1]
607 607 print "\nIPython CPU timings (estimated):"
608 608 print "Total runs performed:", nruns
609 609 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
610 610 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
611 611 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
612 612 twall1 = time.time()
613 613 print "Wall time: %10.2f s." % (twall1 - twall0)
614 614
615 615 else:
616 616 # regular execution
617 617 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
618 618
619 619 if 'i' in opts:
620 620 self.shell.user_ns['__name__'] = __name__save
621 621 else:
622 622 # The shell MUST hold a reference to prog_ns so after %run
623 623 # exits, the python deletion mechanism doesn't zero it out
624 624 # (leaving dangling references).
625 625 self.shell.cache_main_mod(prog_ns, filename)
626 626 # update IPython interactive namespace
627 627
628 628 # Some forms of read errors on the file may mean the
629 629 # __name__ key was never set; using pop we don't have to
630 630 # worry about a possible KeyError.
631 631 prog_ns.pop('__name__', None)
632 632
633 633 self.shell.user_ns.update(prog_ns)
634 634 finally:
635 635 # It's a bit of a mystery why, but __builtins__ can change from
636 636 # being a module to becoming a dict missing some key data after
637 637 # %run. As best I can see, this is NOT something IPython is doing
638 638 # at all, and similar problems have been reported before:
639 639 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
640 640 # Since this seems to be done by the interpreter itself, the best
641 641 # we can do is to at least restore __builtins__ for the user on
642 642 # exit.
643 643 self.shell.user_ns['__builtins__'] = builtin_mod
644 644
645 645 # Ensure key global structures are restored
646 646 sys.argv = save_argv
647 647 if restore_main:
648 648 sys.modules['__main__'] = restore_main
649 649 else:
650 650 # Remove from sys.modules the reference to main_mod we'd
651 651 # added. Otherwise it will trap references to objects
652 652 # contained therein.
653 653 del sys.modules[main_mod_name]
654 654
655 655 return stats
656 656
657 657 @skip_doctest
658 658 @line_cell_magic
659 659 def timeit(self, line='', cell=None):
660 660 """Time execution of a Python statement or expression
661 661
662 662 Usage, in line mode:
663 663 %timeit [-n<N> -r<R> [-t|-c]] statement
664 664 or in cell mode:
665 665 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
666 666 code
667 667 code...
668 668
669 669 Time execution of a Python statement or expression using the timeit
670 670 module. This function can be used both as a line and cell magic:
671 671
672 672 - In line mode you can time a single-line statement (though multiple
673 673 ones can be chained with using semicolons).
674 674
675 675 - In cell mode, the statement in the first line is used as setup code
676 676 (executed but not timed) and the body of the cell is timed. The cell
677 677 body has access to any variables created in the setup code.
678 678
679 679 Options:
680 680 -n<N>: execute the given statement <N> times in a loop. If this value
681 681 is not given, a fitting value is chosen.
682 682
683 683 -r<R>: repeat the loop iteration <R> times and take the best result.
684 684 Default: 3
685 685
686 686 -t: use time.time to measure the time, which is the default on Unix.
687 687 This function measures wall time.
688 688
689 689 -c: use time.clock to measure the time, which is the default on
690 690 Windows and measures wall time. On Unix, resource.getrusage is used
691 691 instead and returns the CPU user time.
692 692
693 693 -p<P>: use a precision of <P> digits to display the timing result.
694 694 Default: 3
695 695
696 696
697 697 Examples
698 698 --------
699 699 ::
700 700
701 701 In [1]: %timeit pass
702 702 10000000 loops, best of 3: 53.3 ns per loop
703 703
704 704 In [2]: u = None
705 705
706 706 In [3]: %timeit u is None
707 707 10000000 loops, best of 3: 184 ns per loop
708 708
709 709 In [4]: %timeit -r 4 u == None
710 710 1000000 loops, best of 4: 242 ns per loop
711 711
712 712 In [5]: import time
713 713
714 714 In [6]: %timeit -n1 time.sleep(2)
715 715 1 loops, best of 3: 2 s per loop
716 716
717 717
718 718 The times reported by %timeit will be slightly higher than those
719 719 reported by the timeit.py script when variables are accessed. This is
720 720 due to the fact that %timeit executes the statement in the namespace
721 721 of the shell, compared with timeit.py, which uses a single setup
722 722 statement to import function or create variables. Generally, the bias
723 723 does not matter as long as results from timeit.py are not mixed with
724 724 those from %timeit."""
725 725
726 726 import timeit
727 727 import math
728 728
729 729 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
730 730 # certain terminals. Until we figure out a robust way of
731 731 # auto-detecting if the terminal can deal with it, use plain 'us' for
732 732 # microseconds. I am really NOT happy about disabling the proper
733 733 # 'micro' prefix, but crashing is worse... If anyone knows what the
734 734 # right solution for this is, I'm all ears...
735 735 #
736 736 # Note: using
737 737 #
738 738 # s = u'\xb5'
739 739 # s.encode(sys.getdefaultencoding())
740 740 #
741 741 # is not sufficient, as I've seen terminals where that fails but
742 742 # print s
743 743 #
744 744 # succeeds
745 745 #
746 746 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
747 747
748 748 #units = [u"s", u"ms",u'\xb5',"ns"]
749 749 units = [u"s", u"ms",u'us',"ns"]
750 750
751 751 scaling = [1, 1e3, 1e6, 1e9]
752 752
753 753 opts, stmt = self.parse_options(line,'n:r:tcp:',
754 754 posix=False, strict=False)
755 755 if stmt == "" and cell is None:
756 756 return
757 757 timefunc = timeit.default_timer
758 758 number = int(getattr(opts, "n", 0))
759 759 repeat = int(getattr(opts, "r", timeit.default_repeat))
760 760 precision = int(getattr(opts, "p", 3))
761 761 if hasattr(opts, "t"):
762 762 timefunc = time.time
763 763 if hasattr(opts, "c"):
764 764 timefunc = clock
765 765
766 766 timer = timeit.Timer(timer=timefunc)
767 767 # this code has tight coupling to the inner workings of timeit.Timer,
768 768 # but is there a better way to achieve that the code stmt has access
769 769 # to the shell namespace?
770 770 transform = self.shell.input_splitter.transform_cell
771 771 if cell is None:
772 772 # called as line magic
773 773 setup = 'pass'
774 774 stmt = timeit.reindent(transform(stmt), 8)
775 775 else:
776 776 setup = timeit.reindent(transform(stmt), 4)
777 777 stmt = timeit.reindent(transform(cell), 8)
778 778
779 779 # From Python 3.3, this template uses new-style string formatting.
780 780 if sys.version_info >= (3, 3):
781 781 src = timeit.template.format(stmt=stmt, setup=setup)
782 782 else:
783 783 src = timeit.template % dict(stmt=stmt, setup=setup)
784 784
785 785 # Track compilation time so it can be reported if too long
786 786 # Minimum time above which compilation time will be reported
787 787 tc_min = 0.1
788 788
789 789 t0 = clock()
790 790 code = compile(src, "<magic-timeit>", "exec")
791 791 tc = clock()-t0
792 792
793 793 ns = {}
794 794 exec code in self.shell.user_ns, ns
795 795 timer.inner = ns["inner"]
796 796
797 797 if number == 0:
798 798 # determine number so that 0.2 <= total time < 2.0
799 799 number = 1
800 800 for i in range(1, 10):
801 801 if timer.timeit(number) >= 0.2:
802 802 break
803 803 number *= 10
804 804
805 805 best = min(timer.repeat(repeat, number)) / number
806 806
807 807 if best > 0.0 and best < 1000.0:
808 808 order = min(-int(math.floor(math.log10(best)) // 3), 3)
809 809 elif best >= 1000.0:
810 810 order = 0
811 811 else:
812 812 order = 3
813 813 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
814 814 precision,
815 815 best * scaling[order],
816 816 units[order])
817 817 if tc > tc_min:
818 818 print "Compiler time: %.2f s" % tc
819 819
820 820 @skip_doctest
821 821 @needs_local_scope
822 822 @line_magic
823 823 def time(self,parameter_s, user_locals):
824 824 """Time execution of a Python statement or expression.
825 825
826 826 The CPU and wall clock times are printed, and the value of the
827 827 expression (if any) is returned. Note that under Win32, system time
828 828 is always reported as 0, since it can not be measured.
829 829
830 830 This function provides very basic timing functionality. In Python
831 831 2.3, the timeit module offers more control and sophistication, so this
832 832 could be rewritten to use it (patches welcome).
833 833
834 834 Examples
835 835 --------
836 836 ::
837 837
838 838 In [1]: time 2**128
839 839 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
840 840 Wall time: 0.00
841 841 Out[1]: 340282366920938463463374607431768211456L
842 842
843 843 In [2]: n = 1000000
844 844
845 845 In [3]: time sum(range(n))
846 846 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
847 847 Wall time: 1.37
848 848 Out[3]: 499999500000L
849 849
850 850 In [4]: time print 'hello world'
851 851 hello world
852 852 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
853 853 Wall time: 0.00
854 854
855 855 Note that the time needed by Python to compile the given expression
856 856 will be reported if it is more than 0.1s. In this example, the
857 857 actual exponentiation is done by Python at compilation time, so while
858 858 the expression can take a noticeable amount of time to compute, that
859 859 time is purely due to the compilation:
860 860
861 861 In [5]: time 3**9999;
862 862 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
863 863 Wall time: 0.00 s
864 864
865 865 In [6]: time 3**999999;
866 866 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
867 867 Wall time: 0.00 s
868 868 Compiler : 0.78 s
869 869 """
870 870
871 871 # fail immediately if the given expression can't be compiled
872 872
873 873 expr = self.shell.prefilter(parameter_s,False)
874 874
875 875 # Minimum time above which compilation time will be reported
876 876 tc_min = 0.1
877 877
878 878 try:
879 879 mode = 'eval'
880 880 t0 = clock()
881 881 code = compile(expr,'<timed eval>',mode)
882 882 tc = clock()-t0
883 883 except SyntaxError:
884 884 mode = 'exec'
885 885 t0 = clock()
886 886 code = compile(expr,'<timed exec>',mode)
887 887 tc = clock()-t0
888 888 # skew measurement as little as possible
889 889 glob = self.shell.user_ns
890 890 wtime = time.time
891 891 # time execution
892 892 wall_st = wtime()
893 893 if mode=='eval':
894 894 st = clock2()
895 895 out = eval(code, glob, user_locals)
896 896 end = clock2()
897 897 else:
898 898 st = clock2()
899 899 exec code in glob, user_locals
900 900 end = clock2()
901 901 out = None
902 902 wall_end = wtime()
903 903 # Compute actual times and report
904 904 wall_time = wall_end-wall_st
905 905 cpu_user = end[0]-st[0]
906 906 cpu_sys = end[1]-st[1]
907 907 cpu_tot = cpu_user+cpu_sys
908 908 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
909 909 (cpu_user,cpu_sys,cpu_tot)
910 910 print "Wall time: %.2f s" % wall_time
911 911 if tc > tc_min:
912 912 print "Compiler : %.2f s" % tc
913 913 return out
914 914
915 915 @skip_doctest
916 916 @line_magic
917 917 def macro(self, parameter_s=''):
918 918 """Define a macro for future re-execution. It accepts ranges of history,
919 919 filenames or string objects.
920 920
921 921 Usage:\\
922 922 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
923 923
924 924 Options:
925 925
926 926 -r: use 'raw' input. By default, the 'processed' history is used,
927 927 so that magics are loaded in their transformed version to valid
928 928 Python. If this option is given, the raw input as typed as the
929 929 command line is used instead.
930 930
931 931 This will define a global variable called `name` which is a string
932 932 made of joining the slices and lines you specify (n1,n2,... numbers
933 933 above) from your input history into a single string. This variable
934 934 acts like an automatic function which re-executes those lines as if
935 935 you had typed them. You just type 'name' at the prompt and the code
936 936 executes.
937 937
938 938 The syntax for indicating input ranges is described in %history.
939 939
940 940 Note: as a 'hidden' feature, you can also use traditional python slice
941 941 notation, where N:M means numbers N through M-1.
942 942
943 943 For example, if your history contains (%hist prints it)::
944 944
945 945 44: x=1
946 946 45: y=3
947 947 46: z=x+y
948 948 47: print x
949 949 48: a=5
950 950 49: print 'x',x,'y',y
951 951
952 952 you can create a macro with lines 44 through 47 (included) and line 49
953 953 called my_macro with::
954 954
955 955 In [55]: %macro my_macro 44-47 49
956 956
957 957 Now, typing `my_macro` (without quotes) will re-execute all this code
958 958 in one pass.
959 959
960 960 You don't need to give the line-numbers in order, and any given line
961 961 number can appear multiple times. You can assemble macros with any
962 962 lines from your input history in any order.
963 963
964 964 The macro is a simple object which holds its value in an attribute,
965 965 but IPython's display system checks for macros and executes them as
966 966 code instead of printing them when you type their name.
967 967
968 968 You can view a macro's contents by explicitly printing it with::
969 969
970 970 print macro_name
971 971
972 972 """
973 973 opts,args = self.parse_options(parameter_s,'r',mode='list')
974 974 if not args: # List existing macros
975 975 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
976 976 isinstance(v, Macro))
977 977 if len(args) == 1:
978 978 raise UsageError(
979 979 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
980 980 name, codefrom = args[0], " ".join(args[1:])
981 981
982 982 #print 'rng',ranges # dbg
983 983 try:
984 984 lines = self.shell.find_user_code(codefrom, 'r' in opts)
985 985 except (ValueError, TypeError) as e:
986 986 print e.args[0]
987 987 return
988 988 macro = Macro(lines)
989 989 self.shell.define_macro(name, macro)
990 990 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
991 991 print '=== Macro contents: ==='
992 992 print macro,
993 993
994 994 @magic_arguments.magic_arguments()
995 995 @magic_arguments.argument('output', type=str, default='', nargs='?',
996 996 help="""The name of the variable in which to store output.
997 997 This is a utils.io.CapturedIO object with stdout/err attributes
998 998 for the text of the captured output.
999 999
1000 1000 CapturedOutput also has a show() method for displaying the output,
1001 1001 and __call__ as well, so you can use that to quickly display the
1002 1002 output.
1003 1003
1004 1004 If unspecified, captured output is discarded.
1005 1005 """
1006 1006 )
1007 1007 @magic_arguments.argument('--no-stderr', action="store_true",
1008 1008 help="""Don't capture stderr."""
1009 1009 )
1010 1010 @magic_arguments.argument('--no-stdout', action="store_true",
1011 1011 help="""Don't capture stdout."""
1012 1012 )
1013 1013 @cell_magic
1014 1014 def capture(self, line, cell):
1015 1015 """run the cell, capturing stdout/err"""
1016 1016 args = magic_arguments.parse_argstring(self.capture, line)
1017 1017 out = not args.no_stdout
1018 1018 err = not args.no_stderr
1019 1019 with capture_output(out, err) as io:
1020 1020 self.shell.run_cell(cell)
1021 1021 if args.output:
1022 1022 self.shell.user_ns[args.output] = io
@@ -1,841 +1,842 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 from __future__ import print_function
16 17
17 18 __all__ = ['Inspector','InspectColors']
18 19
19 20 # stdlib modules
20 21 import __builtin__
21 22 import inspect
22 23 import linecache
23 24 import os
24 25 import sys
25 26 import types
26 27 from collections import namedtuple
27 28 try:
28 29 from itertools import izip_longest
29 30 except ImportError:
30 31 from itertools import zip_longest as izip_longest
31 32
32 33 # IPython's own
33 34 from IPython.core import page
34 35 from IPython.testing.skipdoctest import skip_doctest_py3
35 36 from IPython.utils import PyColorize
36 37 from IPython.utils import io
37 38 from IPython.utils import py3compat
38 39 from IPython.utils.text import indent
39 40 from IPython.utils.wildcard import list_namespace
40 41 from IPython.utils.coloransi import *
41 42
42 43 #****************************************************************************
43 44 # Builtin color schemes
44 45
45 46 Colors = TermColors # just a shorthand
46 47
47 48 # Build a few color schemes
48 49 NoColor = ColorScheme(
49 50 'NoColor',{
50 51 'header' : Colors.NoColor,
51 52 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
52 53 } )
53 54
54 55 LinuxColors = ColorScheme(
55 56 'Linux',{
56 57 'header' : Colors.LightRed,
57 58 'normal' : Colors.Normal # color off (usu. Colors.Normal)
58 59 } )
59 60
60 61 LightBGColors = ColorScheme(
61 62 'LightBG',{
62 63 'header' : Colors.Red,
63 64 'normal' : Colors.Normal # color off (usu. Colors.Normal)
64 65 } )
65 66
66 67 # Build table of color schemes (needed by the parser)
67 68 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
68 69 'Linux')
69 70
70 71 #****************************************************************************
71 72 # Auxiliary functions and objects
72 73
73 74 # See the messaging spec for the definition of all these fields. This list
74 75 # effectively defines the order of display
75 76 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
76 77 'length', 'file', 'definition', 'docstring', 'source',
77 78 'init_definition', 'class_docstring', 'init_docstring',
78 79 'call_def', 'call_docstring',
79 80 # These won't be printed but will be used to determine how to
80 81 # format the object
81 82 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
82 83 ]
83 84
84 85
85 86 def object_info(**kw):
86 87 """Make an object info dict with all fields present."""
87 88 infodict = dict(izip_longest(info_fields, [None]))
88 89 infodict.update(kw)
89 90 return infodict
90 91
91 92
92 93 def getdoc(obj):
93 94 """Stable wrapper around inspect.getdoc.
94 95
95 96 This can't crash because of attribute problems.
96 97
97 98 It also attempts to call a getdoc() method on the given object. This
98 99 allows objects which provide their docstrings via non-standard mechanisms
99 100 (like Pyro proxies) to still be inspected by ipython's ? system."""
100 101 # Allow objects to offer customized documentation via a getdoc method:
101 102 try:
102 103 ds = obj.getdoc()
103 104 except Exception:
104 105 pass
105 106 else:
106 107 # if we get extra info, we add it to the normal docstring.
107 108 if isinstance(ds, basestring):
108 109 return inspect.cleandoc(ds)
109 110
110 111 try:
111 112 return inspect.getdoc(obj)
112 113 except Exception:
113 114 # Harden against an inspect failure, which can occur with
114 115 # SWIG-wrapped extensions.
115 116 return None
116 117
117 118
118 119 def getsource(obj,is_binary=False):
119 120 """Wrapper around inspect.getsource.
120 121
121 122 This can be modified by other projects to provide customized source
122 123 extraction.
123 124
124 125 Inputs:
125 126
126 127 - obj: an object whose source code we will attempt to extract.
127 128
128 129 Optional inputs:
129 130
130 131 - is_binary: whether the object is known to come from a binary source.
131 132 This implementation will skip returning any output for binary objects, but
132 133 custom extractors may know how to meaningfully process them."""
133 134
134 135 if is_binary:
135 136 return None
136 137 else:
137 138 # get source if obj was decorated with @decorator
138 139 if hasattr(obj,"__wrapped__"):
139 140 obj = obj.__wrapped__
140 141 try:
141 142 src = inspect.getsource(obj)
142 143 except TypeError:
143 144 if hasattr(obj,'__class__'):
144 145 src = inspect.getsource(obj.__class__)
145 146 return src
146 147
147 148 def getargspec(obj):
148 149 """Get the names and default values of a function's arguments.
149 150
150 151 A tuple of four things is returned: (args, varargs, varkw, defaults).
151 152 'args' is a list of the argument names (it may contain nested lists).
152 153 'varargs' and 'varkw' are the names of the * and ** arguments or None.
153 154 'defaults' is an n-tuple of the default values of the last n arguments.
154 155
155 156 Modified version of inspect.getargspec from the Python Standard
156 157 Library."""
157 158
158 159 if inspect.isfunction(obj):
159 160 func_obj = obj
160 161 elif inspect.ismethod(obj):
161 162 func_obj = obj.im_func
162 163 elif hasattr(obj, '__call__'):
163 164 func_obj = obj.__call__
164 165 else:
165 166 raise TypeError('arg is not a Python function')
166 167 args, varargs, varkw = inspect.getargs(func_obj.func_code)
167 168 return args, varargs, varkw, func_obj.func_defaults
168 169
169 170
170 171 def format_argspec(argspec):
171 172 """Format argspect, convenience wrapper around inspect's.
172 173
173 174 This takes a dict instead of ordered arguments and calls
174 175 inspect.format_argspec with the arguments in the necessary order.
175 176 """
176 177 return inspect.formatargspec(argspec['args'], argspec['varargs'],
177 178 argspec['varkw'], argspec['defaults'])
178 179
179 180
180 181 def call_tip(oinfo, format_call=True):
181 182 """Extract call tip data from an oinfo dict.
182 183
183 184 Parameters
184 185 ----------
185 186 oinfo : dict
186 187
187 188 format_call : bool, optional
188 189 If True, the call line is formatted and returned as a string. If not, a
189 190 tuple of (name, argspec) is returned.
190 191
191 192 Returns
192 193 -------
193 194 call_info : None, str or (str, dict) tuple.
194 195 When format_call is True, the whole call information is formattted as a
195 196 single string. Otherwise, the object's name and its argspec dict are
196 197 returned. If no call information is available, None is returned.
197 198
198 199 docstring : str or None
199 200 The most relevant docstring for calling purposes is returned, if
200 201 available. The priority is: call docstring for callable instances, then
201 202 constructor docstring for classes, then main object's docstring otherwise
202 203 (regular functions).
203 204 """
204 205 # Get call definition
205 206 argspec = oinfo.get('argspec')
206 207 if argspec is None:
207 208 call_line = None
208 209 else:
209 210 # Callable objects will have 'self' as their first argument, prune
210 211 # it out if it's there for clarity (since users do *not* pass an
211 212 # extra first argument explicitly).
212 213 try:
213 214 has_self = argspec['args'][0] == 'self'
214 215 except (KeyError, IndexError):
215 216 pass
216 217 else:
217 218 if has_self:
218 219 argspec['args'] = argspec['args'][1:]
219 220
220 221 call_line = oinfo['name']+format_argspec(argspec)
221 222
222 223 # Now get docstring.
223 224 # The priority is: call docstring, constructor docstring, main one.
224 225 doc = oinfo.get('call_docstring')
225 226 if doc is None:
226 227 doc = oinfo.get('init_docstring')
227 228 if doc is None:
228 229 doc = oinfo.get('docstring','')
229 230
230 231 return call_line, doc
231 232
232 233
233 234 def find_file(obj):
234 235 """Find the absolute path to the file where an object was defined.
235 236
236 237 This is essentially a robust wrapper around `inspect.getabsfile`.
237 238
238 239 Returns None if no file can be found.
239 240
240 241 Parameters
241 242 ----------
242 243 obj : any Python object
243 244
244 245 Returns
245 246 -------
246 247 fname : str
247 248 The absolute path to the file where the object was defined.
248 249 """
249 250 # get source if obj was decorated with @decorator
250 251 if hasattr(obj, '__wrapped__'):
251 252 obj = obj.__wrapped__
252 253
253 254 fname = None
254 255 try:
255 256 fname = inspect.getabsfile(obj)
256 257 except TypeError:
257 258 # For an instance, the file that matters is where its class was
258 259 # declared.
259 260 if hasattr(obj, '__class__'):
260 261 try:
261 262 fname = inspect.getabsfile(obj.__class__)
262 263 except TypeError:
263 264 # Can happen for builtins
264 265 pass
265 266 except:
266 267 pass
267 268 return fname
268 269
269 270
270 271 def find_source_lines(obj):
271 272 """Find the line number in a file where an object was defined.
272 273
273 274 This is essentially a robust wrapper around `inspect.getsourcelines`.
274 275
275 276 Returns None if no file can be found.
276 277
277 278 Parameters
278 279 ----------
279 280 obj : any Python object
280 281
281 282 Returns
282 283 -------
283 284 lineno : int
284 285 The line number where the object definition starts.
285 286 """
286 287 # get source if obj was decorated with @decorator
287 288 if hasattr(obj, '__wrapped__'):
288 289 obj = obj.__wrapped__
289 290
290 291 try:
291 292 try:
292 293 lineno = inspect.getsourcelines(obj)[1]
293 294 except TypeError:
294 295 # For instances, try the class object like getsource() does
295 296 if hasattr(obj, '__class__'):
296 297 lineno = inspect.getsourcelines(obj.__class__)[1]
297 298 except:
298 299 return None
299 300
300 301 return lineno
301 302
302 303
303 304 class Inspector:
304 305 def __init__(self, color_table=InspectColors,
305 306 code_color_table=PyColorize.ANSICodeColors,
306 307 scheme='NoColor',
307 308 str_detail_level=0):
308 309 self.color_table = color_table
309 310 self.parser = PyColorize.Parser(code_color_table,out='str')
310 311 self.format = self.parser.format
311 312 self.str_detail_level = str_detail_level
312 313 self.set_active_scheme(scheme)
313 314
314 315 def _getdef(self,obj,oname=''):
315 316 """Return the definition header for any callable object.
316 317
317 318 If any exception is generated, None is returned instead and the
318 319 exception is suppressed."""
319 320
320 321 try:
321 322 # We need a plain string here, NOT unicode!
322 323 hdef = oname + inspect.formatargspec(*getargspec(obj))
323 324 return py3compat.unicode_to_str(hdef, 'ascii')
324 325 except:
325 326 return None
326 327
327 328 def __head(self,h):
328 329 """Return a header string with proper colors."""
329 330 return '%s%s%s' % (self.color_table.active_colors.header,h,
330 331 self.color_table.active_colors.normal)
331 332
332 333 def set_active_scheme(self, scheme):
333 334 self.color_table.set_active_scheme(scheme)
334 335 self.parser.color_table.set_active_scheme(scheme)
335 336
336 337 def noinfo(self, msg, oname):
337 338 """Generic message when no information is found."""
338 print 'No %s found' % msg,
339 print('No %s found' % msg, end=' ')
339 340 if oname:
340 print 'for %s' % oname
341 print('for %s' % oname)
341 342 else:
342 print
343 print()
343 344
344 345 def pdef(self, obj, oname=''):
345 346 """Print the definition header for any callable object.
346 347
347 348 If the object is a class, print the constructor information."""
348 349
349 350 if not callable(obj):
350 print 'Object is not callable.'
351 print('Object is not callable.')
351 352 return
352 353
353 354 header = ''
354 355
355 356 if inspect.isclass(obj):
356 357 header = self.__head('Class constructor information:\n')
357 358 obj = obj.__init__
358 359 elif (not py3compat.PY3) and type(obj) is types.InstanceType:
359 360 obj = obj.__call__
360 361
361 362 output = self._getdef(obj,oname)
362 363 if output is None:
363 364 self.noinfo('definition header',oname)
364 365 else:
365 print >>io.stdout, header,self.format(output),
366 print(header,self.format(output), end=' ', file=io.stdout)
366 367
367 368 # In Python 3, all classes are new-style, so they all have __init__.
368 369 @skip_doctest_py3
369 370 def pdoc(self,obj,oname='',formatter = None):
370 371 """Print the docstring for any object.
371 372
372 373 Optional:
373 374 -formatter: a function to run the docstring through for specially
374 375 formatted docstrings.
375 376
376 377 Examples
377 378 --------
378 379
379 380 In [1]: class NoInit:
380 381 ...: pass
381 382
382 383 In [2]: class NoDoc:
383 384 ...: def __init__(self):
384 385 ...: pass
385 386
386 387 In [3]: %pdoc NoDoc
387 388 No documentation found for NoDoc
388 389
389 390 In [4]: %pdoc NoInit
390 391 No documentation found for NoInit
391 392
392 393 In [5]: obj = NoInit()
393 394
394 395 In [6]: %pdoc obj
395 396 No documentation found for obj
396 397
397 398 In [5]: obj2 = NoDoc()
398 399
399 400 In [6]: %pdoc obj2
400 401 No documentation found for obj2
401 402 """
402 403
403 404 head = self.__head # For convenience
404 405 lines = []
405 406 ds = getdoc(obj)
406 407 if formatter:
407 408 ds = formatter(ds)
408 409 if ds:
409 410 lines.append(head("Class Docstring:"))
410 411 lines.append(indent(ds))
411 412 if inspect.isclass(obj) and hasattr(obj, '__init__'):
412 413 init_ds = getdoc(obj.__init__)
413 414 if init_ds is not None:
414 415 lines.append(head("Constructor Docstring:"))
415 416 lines.append(indent(init_ds))
416 417 elif hasattr(obj,'__call__'):
417 418 call_ds = getdoc(obj.__call__)
418 419 if call_ds:
419 420 lines.append(head("Calling Docstring:"))
420 421 lines.append(indent(call_ds))
421 422
422 423 if not lines:
423 424 self.noinfo('documentation',oname)
424 425 else:
425 426 page.page('\n'.join(lines))
426 427
427 428 def psource(self,obj,oname=''):
428 429 """Print the source code for an object."""
429 430
430 431 # Flush the source cache because inspect can return out-of-date source
431 432 linecache.checkcache()
432 433 try:
433 434 src = getsource(obj)
434 435 except:
435 436 self.noinfo('source',oname)
436 437 else:
437 438 page.page(self.format(py3compat.unicode_to_str(src)))
438 439
439 440 def pfile(self, obj, oname=''):
440 441 """Show the whole file where an object was defined."""
441 442
442 443 lineno = find_source_lines(obj)
443 444 if lineno is None:
444 445 self.noinfo('file', oname)
445 446 return
446 447
447 448 ofile = find_file(obj)
448 449 # run contents of file through pager starting at line where the object
449 450 # is defined, as long as the file isn't binary and is actually on the
450 451 # filesystem.
451 452 if ofile.endswith(('.so', '.dll', '.pyd')):
452 print 'File %r is binary, not printing.' % ofile
453 print('File %r is binary, not printing.' % ofile)
453 454 elif not os.path.isfile(ofile):
454 print 'File %r does not exist, not printing.' % ofile
455 print('File %r does not exist, not printing.' % ofile)
455 456 else:
456 457 # Print only text files, not extension binaries. Note that
457 458 # getsourcelines returns lineno with 1-offset and page() uses
458 459 # 0-offset, so we must adjust.
459 460 page.page(self.format(open(ofile).read()), lineno-1)
460 461
461 462 def _format_fields(self, fields, title_width=12):
462 463 """Formats a list of fields for display.
463 464
464 465 Parameters
465 466 ----------
466 467 fields : list
467 468 A list of 2-tuples: (field_title, field_content)
468 469 title_width : int
469 470 How many characters to pad titles to. Default 12.
470 471 """
471 472 out = []
472 473 header = self.__head
473 474 for title, content in fields:
474 475 if len(content.splitlines()) > 1:
475 476 title = header(title + ":") + "\n"
476 477 else:
477 478 title = header((title+":").ljust(title_width))
478 479 out.append(title + content)
479 480 return "\n".join(out)
480 481
481 482 # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict)
482 483 pinfo_fields1 = [("Type", "type_name"),
483 484 ]
484 485
485 486 pinfo_fields2 = [("String Form", "string_form"),
486 487 ]
487 488
488 489 pinfo_fields3 = [("Length", "length"),
489 490 ("File", "file"),
490 491 ("Definition", "definition"),
491 492 ]
492 493
493 494 pinfo_fields_obj = [("Class Docstring", "class_docstring"),
494 495 ("Constructor Docstring","init_docstring"),
495 496 ("Call def", "call_def"),
496 497 ("Call docstring", "call_docstring")]
497 498
498 499 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
499 500 """Show detailed information about an object.
500 501
501 502 Optional arguments:
502 503
503 504 - oname: name of the variable pointing to the object.
504 505
505 506 - formatter: special formatter for docstrings (see pdoc)
506 507
507 508 - info: a structure with some information fields which may have been
508 509 precomputed already.
509 510
510 511 - detail_level: if set to 1, more information is given.
511 512 """
512 513 info = self.info(obj, oname=oname, formatter=formatter,
513 514 info=info, detail_level=detail_level)
514 515 displayfields = []
515 516 def add_fields(fields):
516 517 for title, key in fields:
517 518 field = info[key]
518 519 if field is not None:
519 520 displayfields.append((title, field.rstrip()))
520 521
521 522 add_fields(self.pinfo_fields1)
522 523
523 524 # Base class for old-style instances
524 525 if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
525 526 displayfields.append(("Base Class", info['base_class'].rstrip()))
526 527
527 528 add_fields(self.pinfo_fields2)
528 529
529 530 # Namespace
530 531 if info['namespace'] != 'Interactive':
531 532 displayfields.append(("Namespace", info['namespace'].rstrip()))
532 533
533 534 add_fields(self.pinfo_fields3)
534 535
535 536 # Source or docstring, depending on detail level and whether
536 537 # source found.
537 538 if detail_level > 0 and info['source'] is not None:
538 539 displayfields.append(("Source", self.format(py3compat.cast_bytes_py2(info['source']))))
539 540 elif info['docstring'] is not None:
540 541 displayfields.append(("Docstring", info["docstring"]))
541 542
542 543 # Constructor info for classes
543 544 if info['isclass']:
544 545 if info['init_definition'] or info['init_docstring']:
545 546 displayfields.append(("Constructor information", ""))
546 547 if info['init_definition'] is not None:
547 548 displayfields.append((" Definition",
548 549 info['init_definition'].rstrip()))
549 550 if info['init_docstring'] is not None:
550 551 displayfields.append((" Docstring",
551 552 indent(info['init_docstring'])))
552 553
553 554 # Info for objects:
554 555 else:
555 556 add_fields(self.pinfo_fields_obj)
556 557
557 558 # Finally send to printer/pager:
558 559 if displayfields:
559 560 page.page(self._format_fields(displayfields))
560 561
561 562 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
562 563 """Compute a dict with detailed information about an object.
563 564
564 565 Optional arguments:
565 566
566 567 - oname: name of the variable pointing to the object.
567 568
568 569 - formatter: special formatter for docstrings (see pdoc)
569 570
570 571 - info: a structure with some information fields which may have been
571 572 precomputed already.
572 573
573 574 - detail_level: if set to 1, more information is given.
574 575 """
575 576
576 577 obj_type = type(obj)
577 578
578 579 header = self.__head
579 580 if info is None:
580 581 ismagic = 0
581 582 isalias = 0
582 583 ospace = ''
583 584 else:
584 585 ismagic = info.ismagic
585 586 isalias = info.isalias
586 587 ospace = info.namespace
587 588
588 589 # Get docstring, special-casing aliases:
589 590 if isalias:
590 591 if not callable(obj):
591 592 try:
592 593 ds = "Alias to the system command:\n %s" % obj[1]
593 594 except:
594 595 ds = "Alias: " + str(obj)
595 596 else:
596 597 ds = "Alias to " + str(obj)
597 598 if obj.__doc__:
598 599 ds += "\nDocstring:\n" + obj.__doc__
599 600 else:
600 601 ds = getdoc(obj)
601 602 if ds is None:
602 603 ds = '<no docstring>'
603 604 if formatter is not None:
604 605 ds = formatter(ds)
605 606
606 607 # store output in a dict, we initialize it here and fill it as we go
607 608 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
608 609
609 610 string_max = 200 # max size of strings to show (snipped if longer)
610 611 shalf = int((string_max -5)/2)
611 612
612 613 if ismagic:
613 614 obj_type_name = 'Magic function'
614 615 elif isalias:
615 616 obj_type_name = 'System alias'
616 617 else:
617 618 obj_type_name = obj_type.__name__
618 619 out['type_name'] = obj_type_name
619 620
620 621 try:
621 622 bclass = obj.__class__
622 623 out['base_class'] = str(bclass)
623 624 except: pass
624 625
625 626 # String form, but snip if too long in ? form (full in ??)
626 627 if detail_level >= self.str_detail_level:
627 628 try:
628 629 ostr = str(obj)
629 630 str_head = 'string_form'
630 631 if not detail_level and len(ostr)>string_max:
631 632 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
632 633 ostr = ("\n" + " " * len(str_head.expandtabs())).\
633 634 join(q.strip() for q in ostr.split("\n"))
634 635 out[str_head] = ostr
635 636 except:
636 637 pass
637 638
638 639 if ospace:
639 640 out['namespace'] = ospace
640 641
641 642 # Length (for strings and lists)
642 643 try:
643 644 out['length'] = str(len(obj))
644 645 except: pass
645 646
646 647 # Filename where object was defined
647 648 binary_file = False
648 649 fname = find_file(obj)
649 650 if fname is None:
650 651 # if anything goes wrong, we don't want to show source, so it's as
651 652 # if the file was binary
652 653 binary_file = True
653 654 else:
654 655 if fname.endswith(('.so', '.dll', '.pyd')):
655 656 binary_file = True
656 657 elif fname.endswith('<string>'):
657 658 fname = 'Dynamically generated function. No source code available.'
658 659 out['file'] = fname
659 660
660 661 # reconstruct the function definition and print it:
661 662 defln = self._getdef(obj, oname)
662 663 if defln:
663 664 out['definition'] = self.format(defln)
664 665
665 666 # Docstrings only in detail 0 mode, since source contains them (we
666 667 # avoid repetitions). If source fails, we add them back, see below.
667 668 if ds and detail_level == 0:
668 669 out['docstring'] = ds
669 670
670 671 # Original source code for any callable
671 672 if detail_level:
672 673 # Flush the source cache because inspect can return out-of-date
673 674 # source
674 675 linecache.checkcache()
675 676 source = None
676 677 try:
677 678 try:
678 679 source = getsource(obj, binary_file)
679 680 except TypeError:
680 681 if hasattr(obj, '__class__'):
681 682 source = getsource(obj.__class__, binary_file)
682 683 if source is not None:
683 684 out['source'] = source.rstrip()
684 685 except Exception:
685 686 pass
686 687
687 688 if ds and source is None:
688 689 out['docstring'] = ds
689 690
690 691
691 692 # Constructor docstring for classes
692 693 if inspect.isclass(obj):
693 694 out['isclass'] = True
694 695 # reconstruct the function definition and print it:
695 696 try:
696 697 obj_init = obj.__init__
697 698 except AttributeError:
698 699 init_def = init_ds = None
699 700 else:
700 701 init_def = self._getdef(obj_init,oname)
701 702 init_ds = getdoc(obj_init)
702 703 # Skip Python's auto-generated docstrings
703 704 if init_ds and \
704 705 init_ds.startswith('x.__init__(...) initializes'):
705 706 init_ds = None
706 707
707 708 if init_def or init_ds:
708 709 if init_def:
709 710 out['init_definition'] = self.format(init_def)
710 711 if init_ds:
711 712 out['init_docstring'] = init_ds
712 713
713 714 # and class docstring for instances:
714 715 else:
715 716 # First, check whether the instance docstring is identical to the
716 717 # class one, and print it separately if they don't coincide. In
717 718 # most cases they will, but it's nice to print all the info for
718 719 # objects which use instance-customized docstrings.
719 720 if ds:
720 721 try:
721 722 cls = getattr(obj,'__class__')
722 723 except:
723 724 class_ds = None
724 725 else:
725 726 class_ds = getdoc(cls)
726 727 # Skip Python's auto-generated docstrings
727 728 if class_ds and \
728 729 (class_ds.startswith('function(code, globals[,') or \
729 730 class_ds.startswith('instancemethod(function, instance,') or \
730 731 class_ds.startswith('module(name[,') ):
731 732 class_ds = None
732 733 if class_ds and ds != class_ds:
733 734 out['class_docstring'] = class_ds
734 735
735 736 # Next, try to show constructor docstrings
736 737 try:
737 738 init_ds = getdoc(obj.__init__)
738 739 # Skip Python's auto-generated docstrings
739 740 if init_ds and \
740 741 init_ds.startswith('x.__init__(...) initializes'):
741 742 init_ds = None
742 743 except AttributeError:
743 744 init_ds = None
744 745 if init_ds:
745 746 out['init_docstring'] = init_ds
746 747
747 748 # Call form docstring for callable instances
748 749 if hasattr(obj, '__call__'):
749 750 call_def = self._getdef(obj.__call__, oname)
750 751 if call_def is not None:
751 752 out['call_def'] = self.format(call_def)
752 753 call_ds = getdoc(obj.__call__)
753 754 # Skip Python's auto-generated docstrings
754 755 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
755 756 call_ds = None
756 757 if call_ds:
757 758 out['call_docstring'] = call_ds
758 759
759 760 # Compute the object's argspec as a callable. The key is to decide
760 761 # whether to pull it from the object itself, from its __init__ or
761 762 # from its __call__ method.
762 763
763 764 if inspect.isclass(obj):
764 765 # Old-style classes need not have an __init__
765 766 callable_obj = getattr(obj, "__init__", None)
766 767 elif callable(obj):
767 768 callable_obj = obj
768 769 else:
769 770 callable_obj = None
770 771
771 772 if callable_obj:
772 773 try:
773 774 args, varargs, varkw, defaults = getargspec(callable_obj)
774 775 except (TypeError, AttributeError):
775 776 # For extensions/builtins we can't retrieve the argspec
776 777 pass
777 778 else:
778 779 out['argspec'] = dict(args=args, varargs=varargs,
779 780 varkw=varkw, defaults=defaults)
780 781
781 782 return object_info(**out)
782 783
783 784
784 785 def psearch(self,pattern,ns_table,ns_search=[],
785 786 ignore_case=False,show_all=False):
786 787 """Search namespaces with wildcards for objects.
787 788
788 789 Arguments:
789 790
790 791 - pattern: string containing shell-like wildcards to use in namespace
791 792 searches and optionally a type specification to narrow the search to
792 793 objects of that type.
793 794
794 795 - ns_table: dict of name->namespaces for search.
795 796
796 797 Optional arguments:
797 798
798 799 - ns_search: list of namespace names to include in search.
799 800
800 801 - ignore_case(False): make the search case-insensitive.
801 802
802 803 - show_all(False): show all names, including those starting with
803 804 underscores.
804 805 """
805 806 #print 'ps pattern:<%r>' % pattern # dbg
806 807
807 808 # defaults
808 809 type_pattern = 'all'
809 810 filter = ''
810 811
811 812 cmds = pattern.split()
812 813 len_cmds = len(cmds)
813 814 if len_cmds == 1:
814 815 # Only filter pattern given
815 816 filter = cmds[0]
816 817 elif len_cmds == 2:
817 818 # Both filter and type specified
818 819 filter,type_pattern = cmds
819 820 else:
820 821 raise ValueError('invalid argument string for psearch: <%s>' %
821 822 pattern)
822 823
823 824 # filter search namespaces
824 825 for name in ns_search:
825 826 if name not in ns_table:
826 827 raise ValueError('invalid namespace <%s>. Valid names: %s' %
827 828 (name,ns_table.keys()))
828 829
829 830 #print 'type_pattern:',type_pattern # dbg
830 831 search_result, namespaces_seen = set(), set()
831 832 for ns_name in ns_search:
832 833 ns = ns_table[ns_name]
833 834 # Normally, locals and globals are the same, so we just check one.
834 835 if id(ns) in namespaces_seen:
835 836 continue
836 837 namespaces_seen.add(id(ns))
837 838 tmp_res = list_namespace(ns, type_pattern, filter,
838 839 ignore_case=ignore_case, show_all=show_all)
839 840 search_result.update(tmp_res)
840 841
841 842 page.page('\n'.join(sorted(search_result)))
@@ -1,340 +1,341 b''
1 1 # encoding: utf-8
2 2 """
3 3 Paging capabilities for IPython.core
4 4
5 5 Authors:
6 6
7 7 * Brian Granger
8 8 * Fernando Perez
9 9
10 10 Notes
11 11 -----
12 12
13 13 For now this uses ipapi, so it can't be in IPython.utils. If we can get
14 14 rid of that dependency, we could move it there.
15 15 -----
16 16 """
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Copyright (C) 2008-2011 The IPython Development Team
20 20 #
21 21 # Distributed under the terms of the BSD License. The full license is in
22 22 # the file COPYING, distributed as part of this software.
23 23 #-----------------------------------------------------------------------------
24 24
25 25 #-----------------------------------------------------------------------------
26 26 # Imports
27 27 #-----------------------------------------------------------------------------
28 from __future__ import print_function
28 29
29 30 import os
30 31 import re
31 32 import sys
32 33 import tempfile
33 34
34 35 from io import UnsupportedOperation
35 36
36 37 from IPython.core import ipapi
37 38 from IPython.core.error import TryNext
38 39 from IPython.utils.cursesimport import use_curses
39 40 from IPython.utils.data import chop
40 41 from IPython.utils import io
41 42 from IPython.utils.process import system
42 43 from IPython.utils.terminal import get_terminal_size
43 44
44 45
45 46 #-----------------------------------------------------------------------------
46 47 # Classes and functions
47 48 #-----------------------------------------------------------------------------
48 49
49 50 esc_re = re.compile(r"(\x1b[^m]+m)")
50 51
51 52 def page_dumb(strng, start=0, screen_lines=25):
52 53 """Very dumb 'pager' in Python, for when nothing else works.
53 54
54 55 Only moves forward, same interface as page(), except for pager_cmd and
55 56 mode."""
56 57
57 58 out_ln = strng.splitlines()[start:]
58 59 screens = chop(out_ln,screen_lines-1)
59 60 if len(screens) == 1:
60 print >>io.stdout, os.linesep.join(screens[0])
61 print(os.linesep.join(screens[0]), file=io.stdout)
61 62 else:
62 63 last_escape = ""
63 64 for scr in screens[0:-1]:
64 65 hunk = os.linesep.join(scr)
65 print >>io.stdout, last_escape + hunk
66 print(last_escape + hunk, file=io.stdout)
66 67 if not page_more():
67 68 return
68 69 esc_list = esc_re.findall(hunk)
69 70 if len(esc_list) > 0:
70 71 last_escape = esc_list[-1]
71 print >>io.stdout, last_escape + os.linesep.join(screens[-1])
72 print(last_escape + os.linesep.join(screens[-1]), file=io.stdout)
72 73
73 74 def _detect_screen_size(use_curses, screen_lines_def):
74 75 """Attempt to work out the number of lines on the screen.
75 76
76 77 This is called by page(). It can raise an error (e.g. when run in the
77 78 test suite), so it's separated out so it can easily be called in a try block.
78 79 """
79 80 TERM = os.environ.get('TERM',None)
80 81 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
81 82 local_use_curses = use_curses
82 83 else:
83 84 # curses causes problems on many terminals other than xterm, and
84 85 # some termios calls lock up on Sun OS5.
85 86 local_use_curses = False
86 87 if local_use_curses:
87 88 import termios
88 89 import curses
89 90 # There is a bug in curses, where *sometimes* it fails to properly
90 91 # initialize, and then after the endwin() call is made, the
91 92 # terminal is left in an unusable state. Rather than trying to
92 93 # check everytime for this (by requesting and comparing termios
93 94 # flags each time), we just save the initial terminal state and
94 95 # unconditionally reset it every time. It's cheaper than making
95 96 # the checks.
96 97 term_flags = termios.tcgetattr(sys.stdout)
97 98
98 99 # Curses modifies the stdout buffer size by default, which messes
99 100 # up Python's normal stdout buffering. This would manifest itself
100 101 # to IPython users as delayed printing on stdout after having used
101 102 # the pager.
102 103 #
103 104 # We can prevent this by manually setting the NCURSES_NO_SETBUF
104 105 # environment variable. For more details, see:
105 106 # http://bugs.python.org/issue10144
106 107 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
107 108 os.environ['NCURSES_NO_SETBUF'] = ''
108 109
109 110 # Proceed with curses initialization
110 111 scr = curses.initscr()
111 112 screen_lines_real,screen_cols = scr.getmaxyx()
112 113 curses.endwin()
113 114
114 115 # Restore environment
115 116 if NCURSES_NO_SETBUF is None:
116 117 del os.environ['NCURSES_NO_SETBUF']
117 118 else:
118 119 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
119 120
120 121 # Restore terminal state in case endwin() didn't.
121 122 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
122 123 # Now we have what we needed: the screen size in rows/columns
123 124 return screen_lines_real
124 125 #print '***Screen size:',screen_lines_real,'lines x',\
125 126 #screen_cols,'columns.' # dbg
126 127 else:
127 128 return screen_lines_def
128 129
129 130 def page(strng, start=0, screen_lines=0, pager_cmd=None):
130 131 """Print a string, piping through a pager after a certain length.
131 132
132 133 The screen_lines parameter specifies the number of *usable* lines of your
133 134 terminal screen (total lines minus lines you need to reserve to show other
134 135 information).
135 136
136 137 If you set screen_lines to a number <=0, page() will try to auto-determine
137 138 your screen size and will only use up to (screen_size+screen_lines) for
138 139 printing, paging after that. That is, if you want auto-detection but need
139 140 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
140 141 auto-detection without any lines reserved simply use screen_lines = 0.
141 142
142 143 If a string won't fit in the allowed lines, it is sent through the
143 144 specified pager command. If none given, look for PAGER in the environment,
144 145 and ultimately default to less.
145 146
146 147 If no system pager works, the string is sent through a 'dumb pager'
147 148 written in python, very simplistic.
148 149 """
149 150
150 151 # Some routines may auto-compute start offsets incorrectly and pass a
151 152 # negative value. Offset to 0 for robustness.
152 153 start = max(0, start)
153 154
154 155 # first, try the hook
155 156 ip = ipapi.get()
156 157 if ip:
157 158 try:
158 159 ip.hooks.show_in_pager(strng)
159 160 return
160 161 except TryNext:
161 162 pass
162 163
163 164 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
164 165 TERM = os.environ.get('TERM','dumb')
165 166 if TERM in ['dumb','emacs'] and os.name != 'nt':
166 print strng
167 print(strng)
167 168 return
168 169 # chop off the topmost part of the string we don't want to see
169 170 str_lines = strng.splitlines()[start:]
170 171 str_toprint = os.linesep.join(str_lines)
171 172 num_newlines = len(str_lines)
172 173 len_str = len(str_toprint)
173 174
174 175 # Dumb heuristics to guesstimate number of on-screen lines the string
175 176 # takes. Very basic, but good enough for docstrings in reasonable
176 177 # terminals. If someone later feels like refining it, it's not hard.
177 178 numlines = max(num_newlines,int(len_str/80)+1)
178 179
179 180 screen_lines_def = get_terminal_size()[1]
180 181
181 182 # auto-determine screen size
182 183 if screen_lines <= 0:
183 184 try:
184 185 screen_lines += _detect_screen_size(use_curses, screen_lines_def)
185 186 except (TypeError, UnsupportedOperation):
186 print >>io.stdout, str_toprint
187 print(str_toprint, file=io.stdout)
187 188 return
188 189
189 190 #print 'numlines',numlines,'screenlines',screen_lines # dbg
190 191 if numlines <= screen_lines :
191 192 #print '*** normal print' # dbg
192 print >>io.stdout, str_toprint
193 print(str_toprint, file=io.stdout)
193 194 else:
194 195 # Try to open pager and default to internal one if that fails.
195 196 # All failure modes are tagged as 'retval=1', to match the return
196 197 # value of a failed system command. If any intermediate attempt
197 198 # sets retval to 1, at the end we resort to our own page_dumb() pager.
198 199 pager_cmd = get_pager_cmd(pager_cmd)
199 200 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
200 201 if os.name == 'nt':
201 202 if pager_cmd.startswith('type'):
202 203 # The default WinXP 'type' command is failing on complex strings.
203 204 retval = 1
204 205 else:
205 206 tmpname = tempfile.mktemp('.txt')
206 207 tmpfile = open(tmpname,'wt')
207 208 tmpfile.write(strng)
208 209 tmpfile.close()
209 210 cmd = "%s < %s" % (pager_cmd,tmpname)
210 211 if os.system(cmd):
211 212 retval = 1
212 213 else:
213 214 retval = None
214 215 os.remove(tmpname)
215 216 else:
216 217 try:
217 218 retval = None
218 219 # if I use popen4, things hang. No idea why.
219 220 #pager,shell_out = os.popen4(pager_cmd)
220 221 pager = os.popen(pager_cmd,'w')
221 222 pager.write(strng)
222 223 pager.close()
223 224 retval = pager.close() # success returns None
224 225 except IOError as msg: # broken pipe when user quits
225 226 if msg.args == (32,'Broken pipe'):
226 227 retval = None
227 228 else:
228 229 retval = 1
229 230 except OSError:
230 231 # Other strange problems, sometimes seen in Win2k/cygwin
231 232 retval = 1
232 233 if retval is not None:
233 234 page_dumb(strng,screen_lines=screen_lines)
234 235
235 236
236 237 def page_file(fname, start=0, pager_cmd=None):
237 238 """Page a file, using an optional pager command and starting line.
238 239 """
239 240
240 241 pager_cmd = get_pager_cmd(pager_cmd)
241 242 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
242 243
243 244 try:
244 245 if os.environ['TERM'] in ['emacs','dumb']:
245 246 raise EnvironmentError
246 247 system(pager_cmd + ' ' + fname)
247 248 except:
248 249 try:
249 250 if start > 0:
250 251 start -= 1
251 252 page(open(fname).read(),start)
252 253 except:
253 print 'Unable to show file',`fname`
254 print('Unable to show file',repr(fname))
254 255
255 256
256 257 def get_pager_cmd(pager_cmd=None):
257 258 """Return a pager command.
258 259
259 260 Makes some attempts at finding an OS-correct one.
260 261 """
261 262 if os.name == 'posix':
262 263 default_pager_cmd = 'less -r' # -r for color control sequences
263 264 elif os.name in ['nt','dos']:
264 265 default_pager_cmd = 'type'
265 266
266 267 if pager_cmd is None:
267 268 try:
268 269 pager_cmd = os.environ['PAGER']
269 270 except:
270 271 pager_cmd = default_pager_cmd
271 272 return pager_cmd
272 273
273 274
274 275 def get_pager_start(pager, start):
275 276 """Return the string for paging files with an offset.
276 277
277 278 This is the '+N' argument which less and more (under Unix) accept.
278 279 """
279 280
280 281 if pager in ['less','more']:
281 282 if start:
282 283 start_string = '+' + str(start)
283 284 else:
284 285 start_string = ''
285 286 else:
286 287 start_string = ''
287 288 return start_string
288 289
289 290
290 291 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
291 292 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
292 293 import msvcrt
293 294 def page_more():
294 295 """ Smart pausing between pages
295 296
296 297 @return: True if need print more lines, False if quit
297 298 """
298 299 io.stdout.write('---Return to continue, q to quit--- ')
299 300 ans = msvcrt.getch()
300 301 if ans in ("q", "Q"):
301 302 result = False
302 303 else:
303 304 result = True
304 305 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
305 306 return result
306 307 else:
307 308 def page_more():
308 309 ans = raw_input('---Return to continue, q to quit--- ')
309 310 if ans.lower().startswith('q'):
310 311 return False
311 312 else:
312 313 return True
313 314
314 315
315 316 def snip_print(str,width = 75,print_full = 0,header = ''):
316 317 """Print a string snipping the midsection to fit in width.
317 318
318 319 print_full: mode control:
319 320 - 0: only snip long strings
320 321 - 1: send to page() directly.
321 322 - 2: snip long strings and ask for full length viewing with page()
322 323 Return 1 if snipping was necessary, 0 otherwise."""
323 324
324 325 if print_full == 1:
325 326 page(header+str)
326 327 return 0
327 328
328 print header,
329 print(header, end=' ')
329 330 if len(str) < width:
330 print str
331 print(str)
331 332 snip = 0
332 333 else:
333 334 whalf = int((width -5)/2)
334 print str[:whalf] + ' <...> ' + str[-whalf:]
335 print(str[:whalf] + ' <...> ' + str[-whalf:])
335 336 snip = 1
336 337 if snip and print_full == 2:
337 338 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
338 339 page(str)
339 340 return snip
340 341
@@ -1,1244 +1,1244 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultratb.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultratb
13 13 sys.excepthook = ultratb.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultratb
41 41 sys.excepthook = ultratb.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 61 possible inclusion in future releases.
62 62 """
63 63
64 64 #*****************************************************************************
65 65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 67 #
68 68 # Distributed under the terms of the BSD License. The full license is in
69 69 # the file COPYING, distributed as part of this software.
70 70 #*****************************************************************************
71 71
72 72 from __future__ import with_statement
73 73
74 74 import inspect
75 75 import keyword
76 76 import linecache
77 77 import os
78 78 import pydoc
79 79 import re
80 80 import sys
81 81 import time
82 82 import tokenize
83 83 import traceback
84 84 import types
85 85
86 86 try: # Python 2
87 87 generate_tokens = tokenize.generate_tokens
88 88 except AttributeError: # Python 3
89 89 generate_tokens = tokenize.tokenize
90 90
91 91 # For purposes of monkeypatching inspect to fix a bug in it.
92 92 from inspect import getsourcefile, getfile, getmodule,\
93 93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
94 94
95 95 # IPython's own modules
96 96 # Modified pdb which doesn't damage IPython's readline handling
97 97 from IPython.core import debugger, ipapi
98 98 from IPython.core.display_trap import DisplayTrap
99 99 from IPython.core.excolors import exception_colors
100 100 from IPython.utils import PyColorize
101 101 from IPython.utils import io
102 102 from IPython.utils import py3compat
103 103 from IPython.utils import pyfile
104 104 from IPython.utils.data import uniq_stable
105 105 from IPython.utils.warn import info, error
106 106
107 107 # Globals
108 108 # amount of space to put line numbers before verbose tracebacks
109 109 INDENT_SIZE = 8
110 110
111 111 # Default color scheme. This is used, for example, by the traceback
112 112 # formatter. When running in an actual IPython instance, the user's rc.colors
113 113 # value is used, but havinga module global makes this functionality available
114 114 # to users of ultratb who are NOT running inside ipython.
115 115 DEFAULT_SCHEME = 'NoColor'
116 116
117 117 #---------------------------------------------------------------------------
118 118 # Code begins
119 119
120 120 # Utility functions
121 121 def inspect_error():
122 122 """Print a message about internal inspect errors.
123 123
124 124 These are unfortunately quite common."""
125 125
126 126 error('Internal Python error in the inspect module.\n'
127 127 'Below is the traceback from this internal error.\n')
128 128
129 129
130 130 # N.B. This function is a monkeypatch we are currently not applying.
131 131 # It was written some time ago, to fix an apparent Python bug with
132 132 # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions
133 133 # the bug occurred, so we can't tell if it has been fixed. If it reappears, we
134 134 # will apply the monkeypatch again. Also, note that findsource() is not called
135 135 # by our code at this time - we don't know if it was when the monkeypatch was
136 136 # written, or if the monkeypatch is needed for some other code (like a debugger).
137 137 # For the discussion about not applying it, see gh-1229. TK, Jan 2011.
138 138 def findsource(object):
139 139 """Return the entire source file and starting line number for an object.
140 140
141 141 The argument may be a module, class, method, function, traceback, frame,
142 142 or code object. The source code is returned as a list of all the lines
143 143 in the file and the line number indexes a line in that list. An IOError
144 144 is raised if the source code cannot be retrieved.
145 145
146 146 FIXED version with which we monkeypatch the stdlib to work around a bug."""
147 147
148 148 file = getsourcefile(object) or getfile(object)
149 149 # If the object is a frame, then trying to get the globals dict from its
150 150 # module won't work. Instead, the frame object itself has the globals
151 151 # dictionary.
152 152 globals_dict = None
153 153 if inspect.isframe(object):
154 154 # XXX: can this ever be false?
155 155 globals_dict = object.f_globals
156 156 else:
157 157 module = getmodule(object, file)
158 158 if module:
159 159 globals_dict = module.__dict__
160 160 lines = linecache.getlines(file, globals_dict)
161 161 if not lines:
162 162 raise IOError('could not get source code')
163 163
164 164 if ismodule(object):
165 165 return lines, 0
166 166
167 167 if isclass(object):
168 168 name = object.__name__
169 169 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
170 170 # make some effort to find the best matching class definition:
171 171 # use the one with the least indentation, which is the one
172 172 # that's most probably not inside a function definition.
173 173 candidates = []
174 174 for i in range(len(lines)):
175 175 match = pat.match(lines[i])
176 176 if match:
177 177 # if it's at toplevel, it's already the best one
178 178 if lines[i][0] == 'c':
179 179 return lines, i
180 180 # else add whitespace to candidate list
181 181 candidates.append((match.group(1), i))
182 182 if candidates:
183 183 # this will sort by whitespace, and by line number,
184 184 # less whitespace first
185 185 candidates.sort()
186 186 return lines, candidates[0][1]
187 187 else:
188 188 raise IOError('could not find class definition')
189 189
190 190 if ismethod(object):
191 191 object = object.im_func
192 192 if isfunction(object):
193 193 object = object.func_code
194 194 if istraceback(object):
195 195 object = object.tb_frame
196 196 if isframe(object):
197 197 object = object.f_code
198 198 if iscode(object):
199 199 if not hasattr(object, 'co_firstlineno'):
200 200 raise IOError('could not find function definition')
201 201 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
202 202 pmatch = pat.match
203 203 # fperez - fix: sometimes, co_firstlineno can give a number larger than
204 204 # the length of lines, which causes an error. Safeguard against that.
205 205 lnum = min(object.co_firstlineno,len(lines))-1
206 206 while lnum > 0:
207 207 if pmatch(lines[lnum]): break
208 208 lnum -= 1
209 209
210 210 return lines, lnum
211 211 raise IOError('could not find code object')
212 212
213 213 # Not applying the monkeypatch - see above the function for details. TK, Jan 2012
214 214 # Monkeypatch inspect to apply our bugfix. This code only works with py25
215 215 #if sys.version_info[:2] >= (2,5):
216 216 # inspect.findsource = findsource
217 217
218 218 def fix_frame_records_filenames(records):
219 219 """Try to fix the filenames in each record from inspect.getinnerframes().
220 220
221 221 Particularly, modules loaded from within zip files have useless filenames
222 222 attached to their code object, and inspect.getinnerframes() just uses it.
223 223 """
224 224 fixed_records = []
225 225 for frame, filename, line_no, func_name, lines, index in records:
226 226 # Look inside the frame's globals dictionary for __file__, which should
227 227 # be better.
228 228 better_fn = frame.f_globals.get('__file__', None)
229 229 if isinstance(better_fn, str):
230 230 # Check the type just in case someone did something weird with
231 231 # __file__. It might also be None if the error occurred during
232 232 # import.
233 233 filename = better_fn
234 234 fixed_records.append((frame, filename, line_no, func_name, lines, index))
235 235 return fixed_records
236 236
237 237
238 238 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
239 239 import linecache
240 240 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
241 241
242 242 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
243 243
244 244 # If the error is at the console, don't build any context, since it would
245 245 # otherwise produce 5 blank lines printed out (there is no file at the
246 246 # console)
247 247 rec_check = records[tb_offset:]
248 248 try:
249 249 rname = rec_check[0][1]
250 250 if rname == '<ipython console>' or rname.endswith('<string>'):
251 251 return rec_check
252 252 except IndexError:
253 253 pass
254 254
255 255 aux = traceback.extract_tb(etb)
256 256 assert len(records) == len(aux)
257 257 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
258 258 maybeStart = lnum-1 - context//2
259 259 start = max(maybeStart, 0)
260 260 end = start + context
261 261 lines = linecache.getlines(file)[start:end]
262 262 buf = list(records[i])
263 263 buf[LNUM_POS] = lnum
264 264 buf[INDEX_POS] = lnum - 1 - start
265 265 buf[LINES_POS] = lines
266 266 records[i] = tuple(buf)
267 267 return records[tb_offset:]
268 268
269 269 # Helper function -- largely belongs to VerboseTB, but we need the same
270 270 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
271 271 # can be recognized properly by ipython.el's py-traceback-line-re
272 272 # (SyntaxErrors have to be treated specially because they have no traceback)
273 273
274 274 _parser = PyColorize.Parser()
275 275
276 276 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
277 277 numbers_width = INDENT_SIZE - 1
278 278 res = []
279 279 i = lnum - index
280 280
281 281 # This lets us get fully syntax-highlighted tracebacks.
282 282 if scheme is None:
283 283 ipinst = ipapi.get()
284 284 if ipinst is not None:
285 285 scheme = ipinst.colors
286 286 else:
287 287 scheme = DEFAULT_SCHEME
288 288
289 289 _line_format = _parser.format2
290 290
291 291 for line in lines:
292 292 # FIXME: we need to ensure the source is a pure string at this point,
293 293 # else the coloring code makes a royal mess. This is in need of a
294 294 # serious refactoring, so that all of the ultratb and PyColorize code
295 295 # is unicode-safe. So for now this is rather an ugly hack, but
296 296 # necessary to at least have readable tracebacks. Improvements welcome!
297 297 line = py3compat.cast_bytes_py2(line, 'utf-8')
298 298
299 299 new_line, err = _line_format(line, 'str', scheme)
300 300 if not err: line = new_line
301 301
302 302 if i == lnum:
303 303 # This is the line with the error
304 304 pad = numbers_width - len(str(i))
305 305 if pad >= 3:
306 306 marker = '-'*(pad-3) + '-> '
307 307 elif pad == 2:
308 308 marker = '> '
309 309 elif pad == 1:
310 310 marker = '>'
311 311 else:
312 312 marker = ''
313 313 num = marker + str(i)
314 314 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
315 315 Colors.line, line, Colors.Normal)
316 316 else:
317 317 num = '%*s' % (numbers_width,i)
318 318 line = '%s%s%s %s' %(Colors.lineno, num,
319 319 Colors.Normal, line)
320 320
321 321 res.append(line)
322 322 if lvals and i == lnum:
323 323 res.append(lvals + '\n')
324 324 i = i + 1
325 325 return res
326 326
327 327
328 328 #---------------------------------------------------------------------------
329 329 # Module classes
330 330 class TBTools(object):
331 331 """Basic tools used by all traceback printer classes."""
332 332
333 333 # Number of frames to skip when reporting tracebacks
334 334 tb_offset = 0
335 335
336 336 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
337 337 # Whether to call the interactive pdb debugger after printing
338 338 # tracebacks or not
339 339 self.call_pdb = call_pdb
340 340
341 341 # Output stream to write to. Note that we store the original value in
342 342 # a private attribute and then make the public ostream a property, so
343 343 # that we can delay accessing io.stdout until runtime. The way
344 344 # things are written now, the io.stdout object is dynamically managed
345 345 # so a reference to it should NEVER be stored statically. This
346 346 # property approach confines this detail to a single location, and all
347 347 # subclasses can simply access self.ostream for writing.
348 348 self._ostream = ostream
349 349
350 350 # Create color table
351 351 self.color_scheme_table = exception_colors()
352 352
353 353 self.set_colors(color_scheme)
354 354 self.old_scheme = color_scheme # save initial value for toggles
355 355
356 356 if call_pdb:
357 357 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
358 358 else:
359 359 self.pdb = None
360 360
361 361 def _get_ostream(self):
362 362 """Output stream that exceptions are written to.
363 363
364 364 Valid values are:
365 365
366 366 - None: the default, which means that IPython will dynamically resolve
367 367 to io.stdout. This ensures compatibility with most tools, including
368 368 Windows (where plain stdout doesn't recognize ANSI escapes).
369 369
370 370 - Any object with 'write' and 'flush' attributes.
371 371 """
372 372 return io.stdout if self._ostream is None else self._ostream
373 373
374 374 def _set_ostream(self, val):
375 375 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
376 376 self._ostream = val
377 377
378 378 ostream = property(_get_ostream, _set_ostream)
379 379
380 380 def set_colors(self,*args,**kw):
381 381 """Shorthand access to the color table scheme selector method."""
382 382
383 383 # Set own color table
384 384 self.color_scheme_table.set_active_scheme(*args,**kw)
385 385 # for convenience, set Colors to the active scheme
386 386 self.Colors = self.color_scheme_table.active_colors
387 387 # Also set colors of debugger
388 388 if hasattr(self,'pdb') and self.pdb is not None:
389 389 self.pdb.set_colors(*args,**kw)
390 390
391 391 def color_toggle(self):
392 392 """Toggle between the currently active color scheme and NoColor."""
393 393
394 394 if self.color_scheme_table.active_scheme_name == 'NoColor':
395 395 self.color_scheme_table.set_active_scheme(self.old_scheme)
396 396 self.Colors = self.color_scheme_table.active_colors
397 397 else:
398 398 self.old_scheme = self.color_scheme_table.active_scheme_name
399 399 self.color_scheme_table.set_active_scheme('NoColor')
400 400 self.Colors = self.color_scheme_table.active_colors
401 401
402 402 def stb2text(self, stb):
403 403 """Convert a structured traceback (a list) to a string."""
404 404 return '\n'.join(stb)
405 405
406 406 def text(self, etype, value, tb, tb_offset=None, context=5):
407 407 """Return formatted traceback.
408 408
409 409 Subclasses may override this if they add extra arguments.
410 410 """
411 411 tb_list = self.structured_traceback(etype, value, tb,
412 412 tb_offset, context)
413 413 return self.stb2text(tb_list)
414 414
415 415 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
416 416 context=5, mode=None):
417 417 """Return a list of traceback frames.
418 418
419 419 Must be implemented by each class.
420 420 """
421 421 raise NotImplementedError()
422 422
423 423
424 424 #---------------------------------------------------------------------------
425 425 class ListTB(TBTools):
426 426 """Print traceback information from a traceback list, with optional color.
427 427
428 428 Calling: requires 3 arguments:
429 429 (etype, evalue, elist)
430 430 as would be obtained by:
431 431 etype, evalue, tb = sys.exc_info()
432 432 if tb:
433 433 elist = traceback.extract_tb(tb)
434 434 else:
435 435 elist = None
436 436
437 437 It can thus be used by programs which need to process the traceback before
438 438 printing (such as console replacements based on the code module from the
439 439 standard library).
440 440
441 441 Because they are meant to be called without a full traceback (only a
442 442 list), instances of this class can't call the interactive pdb debugger."""
443 443
444 444 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
445 445 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
446 446 ostream=ostream)
447 447
448 448 def __call__(self, etype, value, elist):
449 449 self.ostream.flush()
450 450 self.ostream.write(self.text(etype, value, elist))
451 451 self.ostream.write('\n')
452 452
453 453 def structured_traceback(self, etype, value, elist, tb_offset=None,
454 454 context=5):
455 455 """Return a color formatted string with the traceback info.
456 456
457 457 Parameters
458 458 ----------
459 459 etype : exception type
460 460 Type of the exception raised.
461 461
462 462 value : object
463 463 Data stored in the exception
464 464
465 465 elist : list
466 466 List of frames, see class docstring for details.
467 467
468 468 tb_offset : int, optional
469 469 Number of frames in the traceback to skip. If not given, the
470 470 instance value is used (set in constructor).
471 471
472 472 context : int, optional
473 473 Number of lines of context information to print.
474 474
475 475 Returns
476 476 -------
477 477 String with formatted exception.
478 478 """
479 479 tb_offset = self.tb_offset if tb_offset is None else tb_offset
480 480 Colors = self.Colors
481 481 out_list = []
482 482 if elist:
483 483
484 484 if tb_offset and len(elist) > tb_offset:
485 485 elist = elist[tb_offset:]
486 486
487 487 out_list.append('Traceback %s(most recent call last)%s:' %
488 488 (Colors.normalEm, Colors.Normal) + '\n')
489 489 out_list.extend(self._format_list(elist))
490 490 # The exception info should be a single entry in the list.
491 491 lines = ''.join(self._format_exception_only(etype, value))
492 492 out_list.append(lines)
493 493
494 494 # Note: this code originally read:
495 495
496 496 ## for line in lines[:-1]:
497 497 ## out_list.append(" "+line)
498 498 ## out_list.append(lines[-1])
499 499
500 500 # This means it was indenting everything but the last line by a little
501 501 # bit. I've disabled this for now, but if we see ugliness somewhre we
502 502 # can restore it.
503 503
504 504 return out_list
505 505
506 506 def _format_list(self, extracted_list):
507 507 """Format a list of traceback entry tuples for printing.
508 508
509 509 Given a list of tuples as returned by extract_tb() or
510 510 extract_stack(), return a list of strings ready for printing.
511 511 Each string in the resulting list corresponds to the item with the
512 512 same index in the argument list. Each string ends in a newline;
513 513 the strings may contain internal newlines as well, for those items
514 514 whose source text line is not None.
515 515
516 516 Lifted almost verbatim from traceback.py
517 517 """
518 518
519 519 Colors = self.Colors
520 520 list = []
521 521 for filename, lineno, name, line in extracted_list[:-1]:
522 522 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
523 523 (Colors.filename, filename, Colors.Normal,
524 524 Colors.lineno, lineno, Colors.Normal,
525 525 Colors.name, name, Colors.Normal)
526 526 if line:
527 527 item += ' %s\n' % line.strip()
528 528 list.append(item)
529 529 # Emphasize the last entry
530 530 filename, lineno, name, line = extracted_list[-1]
531 531 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
532 532 (Colors.normalEm,
533 533 Colors.filenameEm, filename, Colors.normalEm,
534 534 Colors.linenoEm, lineno, Colors.normalEm,
535 535 Colors.nameEm, name, Colors.normalEm,
536 536 Colors.Normal)
537 537 if line:
538 538 item += '%s %s%s\n' % (Colors.line, line.strip(),
539 539 Colors.Normal)
540 540 list.append(item)
541 541 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
542 542 return list
543 543
544 544 def _format_exception_only(self, etype, value):
545 545 """Format the exception part of a traceback.
546 546
547 547 The arguments are the exception type and value such as given by
548 548 sys.exc_info()[:2]. The return value is a list of strings, each ending
549 549 in a newline. Normally, the list contains a single string; however,
550 550 for SyntaxError exceptions, it contains several lines that (when
551 551 printed) display detailed information about where the syntax error
552 552 occurred. The message indicating which exception occurred is the
553 553 always last string in the list.
554 554
555 555 Also lifted nearly verbatim from traceback.py
556 556 """
557 557
558 558 have_filedata = False
559 559 Colors = self.Colors
560 560 list = []
561 561 stype = Colors.excName + etype.__name__ + Colors.Normal
562 562 if value is None:
563 563 # Not sure if this can still happen in Python 2.6 and above
564 564 list.append( str(stype) + '\n')
565 565 else:
566 566 if etype is SyntaxError:
567 567 have_filedata = True
568 568 #print 'filename is',filename # dbg
569 569 if not value.filename: value.filename = "<string>"
570 570 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
571 571 (Colors.normalEm,
572 572 Colors.filenameEm, value.filename, Colors.normalEm,
573 573 Colors.linenoEm, value.lineno, Colors.Normal ))
574 574 if value.text is not None:
575 575 i = 0
576 576 while i < len(value.text) and value.text[i].isspace():
577 577 i += 1
578 578 list.append('%s %s%s\n' % (Colors.line,
579 579 value.text.strip(),
580 580 Colors.Normal))
581 581 if value.offset is not None:
582 582 s = ' '
583 583 for c in value.text[i:value.offset-1]:
584 584 if c.isspace():
585 585 s += c
586 586 else:
587 587 s += ' '
588 588 list.append('%s%s^%s\n' % (Colors.caret, s,
589 589 Colors.Normal) )
590 590
591 591 try:
592 592 s = value.msg
593 593 except Exception:
594 594 s = self._some_str(value)
595 595 if s:
596 596 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
597 597 Colors.Normal, s))
598 598 else:
599 599 list.append('%s\n' % str(stype))
600 600
601 601 # sync with user hooks
602 602 if have_filedata:
603 603 ipinst = ipapi.get()
604 604 if ipinst is not None:
605 605 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
606 606
607 607 return list
608 608
609 609 def get_exception_only(self, etype, value):
610 610 """Only print the exception type and message, without a traceback.
611 611
612 612 Parameters
613 613 ----------
614 614 etype : exception type
615 615 value : exception value
616 616 """
617 617 return ListTB.structured_traceback(self, etype, value, [])
618 618
619 619
620 620 def show_exception_only(self, etype, evalue):
621 621 """Only print the exception type and message, without a traceback.
622 622
623 623 Parameters
624 624 ----------
625 625 etype : exception type
626 626 value : exception value
627 627 """
628 628 # This method needs to use __call__ from *this* class, not the one from
629 629 # a subclass whose signature or behavior may be different
630 630 ostream = self.ostream
631 631 ostream.flush()
632 632 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
633 633 ostream.flush()
634 634
635 635 def _some_str(self, value):
636 636 # Lifted from traceback.py
637 637 try:
638 638 return str(value)
639 639 except:
640 640 return '<unprintable %s object>' % type(value).__name__
641 641
642 642 #----------------------------------------------------------------------------
643 643 class VerboseTB(TBTools):
644 644 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
645 645 of HTML. Requires inspect and pydoc. Crazy, man.
646 646
647 647 Modified version which optionally strips the topmost entries from the
648 648 traceback, to be used with alternate interpreters (because their own code
649 649 would appear in the traceback)."""
650 650
651 651 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
652 652 tb_offset=0, long_header=False, include_vars=True,
653 653 check_cache=None):
654 654 """Specify traceback offset, headers and color scheme.
655 655
656 656 Define how many frames to drop from the tracebacks. Calling it with
657 657 tb_offset=1 allows use of this handler in interpreters which will have
658 658 their own code at the top of the traceback (VerboseTB will first
659 659 remove that frame before printing the traceback info)."""
660 660 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
661 661 ostream=ostream)
662 662 self.tb_offset = tb_offset
663 663 self.long_header = long_header
664 664 self.include_vars = include_vars
665 665 # By default we use linecache.checkcache, but the user can provide a
666 666 # different check_cache implementation. This is used by the IPython
667 667 # kernel to provide tracebacks for interactive code that is cached,
668 668 # by a compiler instance that flushes the linecache but preserves its
669 669 # own code cache.
670 670 if check_cache is None:
671 671 check_cache = linecache.checkcache
672 672 self.check_cache = check_cache
673 673
674 674 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
675 675 context=5):
676 676 """Return a nice text document describing the traceback."""
677 677
678 678 tb_offset = self.tb_offset if tb_offset is None else tb_offset
679 679
680 680 # some locals
681 681 try:
682 682 etype = etype.__name__
683 683 except AttributeError:
684 684 pass
685 685 Colors = self.Colors # just a shorthand + quicker name lookup
686 686 ColorsNormal = Colors.Normal # used a lot
687 687 col_scheme = self.color_scheme_table.active_scheme_name
688 688 indent = ' '*INDENT_SIZE
689 689 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
690 690 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
691 691 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
692 692
693 693 # some internal-use functions
694 694 def text_repr(value):
695 695 """Hopefully pretty robust repr equivalent."""
696 696 # this is pretty horrible but should always return *something*
697 697 try:
698 698 return pydoc.text.repr(value)
699 699 except KeyboardInterrupt:
700 700 raise
701 701 except:
702 702 try:
703 703 return repr(value)
704 704 except KeyboardInterrupt:
705 705 raise
706 706 except:
707 707 try:
708 708 # all still in an except block so we catch
709 709 # getattr raising
710 710 name = getattr(value, '__name__', None)
711 711 if name:
712 712 # ick, recursion
713 713 return text_repr(name)
714 714 klass = getattr(value, '__class__', None)
715 715 if klass:
716 716 return '%s instance' % text_repr(klass)
717 717 except KeyboardInterrupt:
718 718 raise
719 719 except:
720 720 return 'UNRECOVERABLE REPR FAILURE'
721 721 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
722 722 def nullrepr(value, repr=text_repr): return ''
723 723
724 724 # meat of the code begins
725 725 try:
726 726 etype = etype.__name__
727 727 except AttributeError:
728 728 pass
729 729
730 730 if self.long_header:
731 731 # Header with the exception type, python version, and date
732 732 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
733 733 date = time.ctime(time.time())
734 734
735 735 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
736 736 exc, ' '*(75-len(str(etype))-len(pyver)),
737 737 pyver, date.rjust(75) )
738 738 head += "\nA problem occured executing Python code. Here is the sequence of function"\
739 739 "\ncalls leading up to the error, with the most recent (innermost) call last."
740 740 else:
741 741 # Simplified header
742 742 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
743 743 'Traceback (most recent call last)'.\
744 744 rjust(75 - len(str(etype)) ) )
745 745 frames = []
746 746 # Flush cache before calling inspect. This helps alleviate some of the
747 747 # problems with python 2.3's inspect.py.
748 748 ##self.check_cache()
749 749 # Drop topmost frames if requested
750 750 try:
751 751 # Try the default getinnerframes and Alex's: Alex's fixes some
752 752 # problems, but it generates empty tracebacks for console errors
753 753 # (5 blanks lines) where none should be returned.
754 754 #records = inspect.getinnerframes(etb, context)[tb_offset:]
755 755 #print 'python records:', records # dbg
756 756 records = _fixed_getinnerframes(etb, context, tb_offset)
757 757 #print 'alex records:', records # dbg
758 758 except:
759 759
760 760 # FIXME: I've been getting many crash reports from python 2.3
761 761 # users, traceable to inspect.py. If I can find a small test-case
762 762 # to reproduce this, I should either write a better workaround or
763 763 # file a bug report against inspect (if that's the real problem).
764 764 # So far, I haven't been able to find an isolated example to
765 765 # reproduce the problem.
766 766 inspect_error()
767 767 traceback.print_exc(file=self.ostream)
768 768 info('\nUnfortunately, your original traceback can not be constructed.\n')
769 769 return ''
770 770
771 771 # build some color string templates outside these nested loops
772 772 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
773 773 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
774 774 ColorsNormal)
775 775 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
776 776 (Colors.vName, Colors.valEm, ColorsNormal)
777 777 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
778 778 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
779 779 Colors.vName, ColorsNormal)
780 780 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
781 781 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
782 782 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
783 783 ColorsNormal)
784 784
785 785 # now, loop over all records printing context and info
786 786 abspath = os.path.abspath
787 787 for frame, file, lnum, func, lines, index in records:
788 788 #print '*** record:',file,lnum,func,lines,index # dbg
789 789
790 790 if not file:
791 791 file = '?'
792 792 elif not(file.startswith("<") and file.endswith(">")):
793 793 # Guess that filenames like <string> aren't real filenames, so
794 794 # don't call abspath on them.
795 795 try:
796 796 file = abspath(file)
797 797 except OSError:
798 798 # Not sure if this can still happen: abspath now works with
799 799 # file names like <string>
800 800 pass
801 801
802 802 link = tpl_link % file
803 803 args, varargs, varkw, locals = inspect.getargvalues(frame)
804 804
805 805 if func == '?':
806 806 call = ''
807 807 else:
808 808 # Decide whether to include variable details or not
809 809 var_repr = self.include_vars and eqrepr or nullrepr
810 810 try:
811 811 call = tpl_call % (func,inspect.formatargvalues(args,
812 812 varargs, varkw,
813 813 locals,formatvalue=var_repr))
814 814 except KeyError:
815 815 # This happens in situations like errors inside generator
816 816 # expressions, where local variables are listed in the
817 817 # line, but can't be extracted from the frame. I'm not
818 818 # 100% sure this isn't actually a bug in inspect itself,
819 819 # but since there's no info for us to compute with, the
820 820 # best we can do is report the failure and move on. Here
821 821 # we must *not* call any traceback construction again,
822 822 # because that would mess up use of %debug later on. So we
823 823 # simply report the failure and move on. The only
824 824 # limitation will be that this frame won't have locals
825 825 # listed in the call signature. Quite subtle problem...
826 826 # I can't think of a good way to validate this in a unit
827 827 # test, but running a script consisting of:
828 828 # dict( (k,v.strip()) for (k,v) in range(10) )
829 829 # will illustrate the error, if this exception catch is
830 830 # disabled.
831 831 call = tpl_call_fail % func
832 832
833 833 # Don't attempt to tokenize binary files.
834 834 if file.endswith(('.so', '.pyd', '.dll')):
835 835 frames.append('%s %s\n' % (link,call))
836 836 continue
837 837 elif file.endswith(('.pyc','.pyo')):
838 838 # Look up the corresponding source file.
839 839 file = pyfile.source_from_cache(file)
840 840
841 841 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
842 842 line = getline(file, lnum[0])
843 843 lnum[0] += 1
844 844 return line
845 845
846 846 # Build the list of names on this line of code where the exception
847 847 # occurred.
848 848 try:
849 849 names = []
850 850 name_cont = False
851 851
852 852 for token_type, token, start, end, line in generate_tokens(linereader):
853 853 # build composite names
854 854 if token_type == tokenize.NAME and token not in keyword.kwlist:
855 855 if name_cont:
856 856 # Continuation of a dotted name
857 857 try:
858 858 names[-1].append(token)
859 859 except IndexError:
860 860 names.append([token])
861 861 name_cont = False
862 862 else:
863 863 # Regular new names. We append everything, the caller
864 864 # will be responsible for pruning the list later. It's
865 865 # very tricky to try to prune as we go, b/c composite
866 866 # names can fool us. The pruning at the end is easy
867 867 # to do (or the caller can print a list with repeated
868 868 # names if so desired.
869 869 names.append([token])
870 870 elif token == '.':
871 871 name_cont = True
872 872 elif token_type == tokenize.NEWLINE:
873 873 break
874 874
875 875 except (IndexError, UnicodeDecodeError):
876 876 # signals exit of tokenizer
877 877 pass
878 878 except tokenize.TokenError as msg:
879 879 _m = ("An unexpected error occurred while tokenizing input\n"
880 880 "The following traceback may be corrupted or invalid\n"
881 881 "The error message is: %s\n" % msg)
882 882 error(_m)
883 883
884 884 # Join composite names (e.g. "dict.fromkeys")
885 885 names = ['.'.join(n) for n in names]
886 886 # prune names list of duplicates, but keep the right order
887 887 unique_names = uniq_stable(names)
888 888
889 889 # Start loop over vars
890 890 lvals = []
891 891 if self.include_vars:
892 892 for name_full in unique_names:
893 893 name_base = name_full.split('.',1)[0]
894 894 if name_base in frame.f_code.co_varnames:
895 895 if locals.has_key(name_base):
896 896 try:
897 897 value = repr(eval(name_full,locals))
898 898 except:
899 899 value = undefined
900 900 else:
901 901 value = undefined
902 902 name = tpl_local_var % name_full
903 903 else:
904 904 if frame.f_globals.has_key(name_base):
905 905 try:
906 906 value = repr(eval(name_full,frame.f_globals))
907 907 except:
908 908 value = undefined
909 909 else:
910 910 value = undefined
911 911 name = tpl_global_var % name_full
912 912 lvals.append(tpl_name_val % (name,value))
913 913 if lvals:
914 914 lvals = '%s%s' % (indent,em_normal.join(lvals))
915 915 else:
916 916 lvals = ''
917 917
918 918 level = '%s %s\n' % (link,call)
919 919
920 920 if index is None:
921 921 frames.append(level)
922 922 else:
923 923 frames.append('%s%s' % (level,''.join(
924 924 _format_traceback_lines(lnum,index,lines,Colors,lvals,
925 925 col_scheme))))
926 926
927 927 # Get (safely) a string form of the exception info
928 928 try:
929 929 etype_str,evalue_str = map(str,(etype,evalue))
930 930 except:
931 931 # User exception is improperly defined.
932 932 etype,evalue = str,sys.exc_info()[:2]
933 933 etype_str,evalue_str = map(str,(etype,evalue))
934 934 # ... and format it
935 935 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
936 936 ColorsNormal, evalue_str)]
937 937 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
938 938 try:
939 939 names = [w for w in dir(evalue) if isinstance(w, basestring)]
940 940 except:
941 941 # Every now and then, an object with funny inernals blows up
942 942 # when dir() is called on it. We do the best we can to report
943 943 # the problem and continue
944 944 _m = '%sException reporting error (object with broken dir())%s:'
945 945 exception.append(_m % (Colors.excName,ColorsNormal))
946 946 etype_str,evalue_str = map(str,sys.exc_info()[:2])
947 947 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
948 948 ColorsNormal, evalue_str))
949 949 names = []
950 950 for name in names:
951 951 value = text_repr(getattr(evalue, name))
952 952 exception.append('\n%s%s = %s' % (indent, name, value))
953 953
954 954 # vds: >>
955 955 if records:
956 956 filepath, lnum = records[-1][1:3]
957 957 #print "file:", str(file), "linenb", str(lnum) # dbg
958 958 filepath = os.path.abspath(filepath)
959 959 ipinst = ipapi.get()
960 960 if ipinst is not None:
961 961 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
962 962 # vds: <<
963 963
964 964 # return all our info assembled as a single string
965 965 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
966 966 return [head] + frames + [''.join(exception[0])]
967 967
968 968 def debugger(self,force=False):
969 969 """Call up the pdb debugger if desired, always clean up the tb
970 970 reference.
971 971
972 972 Keywords:
973 973
974 974 - force(False): by default, this routine checks the instance call_pdb
975 975 flag and does not actually invoke the debugger if the flag is false.
976 976 The 'force' option forces the debugger to activate even if the flag
977 977 is false.
978 978
979 979 If the call_pdb flag is set, the pdb interactive debugger is
980 980 invoked. In all cases, the self.tb reference to the current traceback
981 981 is deleted to prevent lingering references which hamper memory
982 982 management.
983 983
984 984 Note that each call to pdb() does an 'import readline', so if your app
985 985 requires a special setup for the readline completers, you'll have to
986 986 fix that by hand after invoking the exception handler."""
987 987
988 988 if force or self.call_pdb:
989 989 if self.pdb is None:
990 990 self.pdb = debugger.Pdb(
991 991 self.color_scheme_table.active_scheme_name)
992 992 # the system displayhook may have changed, restore the original
993 993 # for pdb
994 994 display_trap = DisplayTrap(hook=sys.__displayhook__)
995 995 with display_trap:
996 996 self.pdb.reset()
997 997 # Find the right frame so we don't pop up inside ipython itself
998 998 if hasattr(self,'tb') and self.tb is not None:
999 999 etb = self.tb
1000 1000 else:
1001 1001 etb = self.tb = sys.last_traceback
1002 1002 while self.tb is not None and self.tb.tb_next is not None:
1003 1003 self.tb = self.tb.tb_next
1004 1004 if etb and etb.tb_next:
1005 1005 etb = etb.tb_next
1006 1006 self.pdb.botframe = etb.tb_frame
1007 1007 self.pdb.interaction(self.tb.tb_frame, self.tb)
1008 1008
1009 1009 if hasattr(self,'tb'):
1010 1010 del self.tb
1011 1011
1012 1012 def handler(self, info=None):
1013 1013 (etype, evalue, etb) = info or sys.exc_info()
1014 1014 self.tb = etb
1015 1015 ostream = self.ostream
1016 1016 ostream.flush()
1017 1017 ostream.write(self.text(etype, evalue, etb))
1018 1018 ostream.write('\n')
1019 1019 ostream.flush()
1020 1020
1021 1021 # Changed so an instance can just be called as VerboseTB_inst() and print
1022 1022 # out the right info on its own.
1023 1023 def __call__(self, etype=None, evalue=None, etb=None):
1024 1024 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1025 1025 if etb is None:
1026 1026 self.handler()
1027 1027 else:
1028 1028 self.handler((etype, evalue, etb))
1029 1029 try:
1030 1030 self.debugger()
1031 1031 except KeyboardInterrupt:
1032 1032 print "\nKeyboardInterrupt"
1033 1033
1034 1034 #----------------------------------------------------------------------------
1035 1035 class FormattedTB(VerboseTB, ListTB):
1036 1036 """Subclass ListTB but allow calling with a traceback.
1037 1037
1038 1038 It can thus be used as a sys.excepthook for Python > 2.1.
1039 1039
1040 1040 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1041 1041
1042 1042 Allows a tb_offset to be specified. This is useful for situations where
1043 1043 one needs to remove a number of topmost frames from the traceback (such as
1044 1044 occurs with python programs that themselves execute other python code,
1045 1045 like Python shells). """
1046 1046
1047 1047 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1048 1048 ostream=None,
1049 1049 tb_offset=0, long_header=False, include_vars=False,
1050 1050 check_cache=None):
1051 1051
1052 1052 # NEVER change the order of this list. Put new modes at the end:
1053 1053 self.valid_modes = ['Plain','Context','Verbose']
1054 1054 self.verbose_modes = self.valid_modes[1:3]
1055 1055
1056 1056 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1057 1057 ostream=ostream, tb_offset=tb_offset,
1058 1058 long_header=long_header, include_vars=include_vars,
1059 1059 check_cache=check_cache)
1060 1060
1061 1061 # Different types of tracebacks are joined with different separators to
1062 1062 # form a single string. They are taken from this dict
1063 1063 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1064 1064 # set_mode also sets the tb_join_char attribute
1065 1065 self.set_mode(mode)
1066 1066
1067 1067 def _extract_tb(self,tb):
1068 1068 if tb:
1069 1069 return traceback.extract_tb(tb)
1070 1070 else:
1071 1071 return None
1072 1072
1073 1073 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1074 1074 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 1075 mode = self.mode
1076 1076 if mode in self.verbose_modes:
1077 1077 # Verbose modes need a full traceback
1078 1078 return VerboseTB.structured_traceback(
1079 1079 self, etype, value, tb, tb_offset, context
1080 1080 )
1081 1081 else:
1082 1082 # We must check the source cache because otherwise we can print
1083 1083 # out-of-date source code.
1084 1084 self.check_cache()
1085 1085 # Now we can extract and format the exception
1086 1086 elist = self._extract_tb(tb)
1087 1087 return ListTB.structured_traceback(
1088 1088 self, etype, value, elist, tb_offset, context
1089 1089 )
1090 1090
1091 1091 def stb2text(self, stb):
1092 1092 """Convert a structured traceback (a list) to a string."""
1093 1093 return self.tb_join_char.join(stb)
1094 1094
1095 1095
1096 1096 def set_mode(self,mode=None):
1097 1097 """Switch to the desired mode.
1098 1098
1099 1099 If mode is not specified, cycles through the available modes."""
1100 1100
1101 1101 if not mode:
1102 1102 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1103 1103 len(self.valid_modes)
1104 1104 self.mode = self.valid_modes[new_idx]
1105 1105 elif mode not in self.valid_modes:
1106 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1107 'Valid modes: '+str(self.valid_modes)
1106 raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n'
1107 'Valid modes: '+str(self.valid_modes))
1108 1108 else:
1109 1109 self.mode = mode
1110 1110 # include variable details only in 'Verbose' mode
1111 1111 self.include_vars = (self.mode == self.valid_modes[2])
1112 1112 # Set the join character for generating text tracebacks
1113 1113 self.tb_join_char = self._join_chars[self.mode]
1114 1114
1115 1115 # some convenient shorcuts
1116 1116 def plain(self):
1117 1117 self.set_mode(self.valid_modes[0])
1118 1118
1119 1119 def context(self):
1120 1120 self.set_mode(self.valid_modes[1])
1121 1121
1122 1122 def verbose(self):
1123 1123 self.set_mode(self.valid_modes[2])
1124 1124
1125 1125 #----------------------------------------------------------------------------
1126 1126 class AutoFormattedTB(FormattedTB):
1127 1127 """A traceback printer which can be called on the fly.
1128 1128
1129 1129 It will find out about exceptions by itself.
1130 1130
1131 1131 A brief example:
1132 1132
1133 1133 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1134 1134 try:
1135 1135 ...
1136 1136 except:
1137 1137 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1138 1138 """
1139 1139
1140 1140 def __call__(self,etype=None,evalue=None,etb=None,
1141 1141 out=None,tb_offset=None):
1142 1142 """Print out a formatted exception traceback.
1143 1143
1144 1144 Optional arguments:
1145 1145 - out: an open file-like object to direct output to.
1146 1146
1147 1147 - tb_offset: the number of frames to skip over in the stack, on a
1148 1148 per-call basis (this overrides temporarily the instance's tb_offset
1149 1149 given at initialization time. """
1150 1150
1151 1151
1152 1152 if out is None:
1153 1153 out = self.ostream
1154 1154 out.flush()
1155 1155 out.write(self.text(etype, evalue, etb, tb_offset))
1156 1156 out.write('\n')
1157 1157 out.flush()
1158 1158 # FIXME: we should remove the auto pdb behavior from here and leave
1159 1159 # that to the clients.
1160 1160 try:
1161 1161 self.debugger()
1162 1162 except KeyboardInterrupt:
1163 1163 print "\nKeyboardInterrupt"
1164 1164
1165 1165 def structured_traceback(self, etype=None, value=None, tb=None,
1166 1166 tb_offset=None, context=5):
1167 1167 if etype is None:
1168 1168 etype,value,tb = sys.exc_info()
1169 1169 self.tb = tb
1170 1170 return FormattedTB.structured_traceback(
1171 1171 self, etype, value, tb, tb_offset, context)
1172 1172
1173 1173 #---------------------------------------------------------------------------
1174 1174
1175 1175 # A simple class to preserve Nathan's original functionality.
1176 1176 class ColorTB(FormattedTB):
1177 1177 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1178 1178 def __init__(self,color_scheme='Linux',call_pdb=0):
1179 1179 FormattedTB.__init__(self,color_scheme=color_scheme,
1180 1180 call_pdb=call_pdb)
1181 1181
1182 1182
1183 1183 class SyntaxTB(ListTB):
1184 1184 """Extension which holds some state: the last exception value"""
1185 1185
1186 1186 def __init__(self,color_scheme = 'NoColor'):
1187 1187 ListTB.__init__(self,color_scheme)
1188 1188 self.last_syntax_error = None
1189 1189
1190 1190 def __call__(self, etype, value, elist):
1191 1191 self.last_syntax_error = value
1192 1192 ListTB.__call__(self,etype,value,elist)
1193 1193
1194 1194 def clear_err_state(self):
1195 1195 """Return the current error state and clear it"""
1196 1196 e = self.last_syntax_error
1197 1197 self.last_syntax_error = None
1198 1198 return e
1199 1199
1200 1200 def stb2text(self, stb):
1201 1201 """Convert a structured traceback (a list) to a string."""
1202 1202 return ''.join(stb)
1203 1203
1204 1204
1205 1205 #----------------------------------------------------------------------------
1206 1206 # module testing (minimal)
1207 1207 if __name__ == "__main__":
1208 1208 def spam(c, (d, e)):
1209 1209 x = c + d
1210 1210 y = c * d
1211 1211 foo(x, y)
1212 1212
1213 1213 def foo(a, b, bar=1):
1214 1214 eggs(a, b + bar)
1215 1215
1216 1216 def eggs(f, g, z=globals()):
1217 1217 h = f + g
1218 1218 i = f - g
1219 1219 return h / i
1220 1220
1221 1221 print ''
1222 1222 print '*** Before ***'
1223 1223 try:
1224 1224 print spam(1, (2, 3))
1225 1225 except:
1226 1226 traceback.print_exc()
1227 1227 print ''
1228 1228
1229 1229 handler = ColorTB()
1230 1230 print '*** ColorTB ***'
1231 1231 try:
1232 1232 print spam(1, (2, 3))
1233 1233 except:
1234 apply(handler, sys.exc_info() )
1234 handler(*sys.exc_info())
1235 1235 print ''
1236 1236
1237 1237 handler = VerboseTB()
1238 1238 print '*** VerboseTB ***'
1239 1239 try:
1240 1240 print spam(1, (2, 3))
1241 1241 except:
1242 apply(handler, sys.exc_info() )
1242 handler(*sys.exc_info())
1243 1243 print ''
1244 1244
@@ -1,537 +1,538 b''
1 1 """IPython extension to reload modules before executing user code.
2 2
3 3 ``autoreload`` reloads modules automatically before entering the execution of
4 4 code typed at the IPython prompt.
5 5
6 6 This makes for example the following workflow possible:
7 7
8 8 .. sourcecode:: ipython
9 9
10 10 In [1]: %load_ext autoreload
11 11
12 12 In [2]: %autoreload 2
13 13
14 14 In [3]: from foo import some_function
15 15
16 16 In [4]: some_function()
17 17 Out[4]: 42
18 18
19 19 In [5]: # open foo.py in an editor and change some_function to return 43
20 20
21 21 In [6]: some_function()
22 22 Out[6]: 43
23 23
24 24 The module was reloaded without reloading it explicitly, and the object
25 25 imported with ``from foo import ...`` was also updated.
26 26
27 27 Usage
28 28 =====
29 29
30 30 The following magic commands are provided:
31 31
32 32 ``%autoreload``
33 33
34 34 Reload all modules (except those excluded by ``%aimport``)
35 35 automatically now.
36 36
37 37 ``%autoreload 0``
38 38
39 39 Disable automatic reloading.
40 40
41 41 ``%autoreload 1``
42 42
43 43 Reload all modules imported with ``%aimport`` every time before
44 44 executing the Python code typed.
45 45
46 46 ``%autoreload 2``
47 47
48 48 Reload all modules (except those excluded by ``%aimport``) every
49 49 time before executing the Python code typed.
50 50
51 51 ``%aimport``
52 52
53 53 List modules which are to be automatically imported or not to be imported.
54 54
55 55 ``%aimport foo``
56 56
57 57 Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``
58 58
59 59 ``%aimport -foo``
60 60
61 61 Mark module 'foo' to not be autoreloaded.
62 62
63 63 Caveats
64 64 =======
65 65
66 66 Reloading Python modules in a reliable way is in general difficult,
67 67 and unexpected things may occur. ``%autoreload`` tries to work around
68 68 common pitfalls by replacing function code objects and parts of
69 69 classes previously in the module with new versions. This makes the
70 70 following things to work:
71 71
72 72 - Functions and classes imported via 'from xxx import foo' are upgraded
73 73 to new versions when 'xxx' is reloaded.
74 74
75 75 - Methods and properties of classes are upgraded on reload, so that
76 76 calling 'c.foo()' on an object 'c' created before the reload causes
77 77 the new code for 'foo' to be executed.
78 78
79 79 Some of the known remaining caveats are:
80 80
81 81 - Replacing code objects does not always succeed: changing a @property
82 82 in a class to an ordinary method or a method to a member variable
83 83 can cause problems (but in old objects only).
84 84
85 85 - Functions that are removed (eg. via monkey-patching) from a module
86 86 before it is reloaded are not upgraded.
87 87
88 88 - C extension modules cannot be reloaded, and so cannot be autoreloaded.
89 89 """
90 from __future__ import print_function
90 91
91 92 skip_doctest = True
92 93
93 94 #-----------------------------------------------------------------------------
94 95 # Copyright (C) 2000 Thomas Heller
95 96 # Copyright (C) 2008 Pauli Virtanen <pav@iki.fi>
96 97 # Copyright (C) 2012 The IPython Development Team
97 98 #
98 99 # Distributed under the terms of the BSD License. The full license is in
99 100 # the file COPYING, distributed as part of this software.
100 101 #-----------------------------------------------------------------------------
101 102 #
102 103 # This IPython module is written by Pauli Virtanen, based on the autoreload
103 104 # code by Thomas Heller.
104 105
105 106 #-----------------------------------------------------------------------------
106 107 # Imports
107 108 #-----------------------------------------------------------------------------
108 109 import atexit
109 110 import imp
110 111 import inspect
111 112 import os
112 113 import sys
113 114 import threading
114 115 import time
115 116 import traceback
116 117 import types
117 118 import weakref
118 119
119 120 try:
120 121 # Reload is not defined by default in Python3.
121 122 reload
122 123 except NameError:
123 124 from imp import reload
124 125
125 126 from IPython.utils import pyfile
126 127 from IPython.utils.py3compat import PY3
127 128
128 129 #------------------------------------------------------------------------------
129 130 # Autoreload functionality
130 131 #------------------------------------------------------------------------------
131 132
132 133 def _get_compiled_ext():
133 134 """Official way to get the extension of compiled files (.pyc or .pyo)"""
134 135 for ext, mode, typ in imp.get_suffixes():
135 136 if typ == imp.PY_COMPILED:
136 137 return ext
137 138
138 139
139 140 PY_COMPILED_EXT = _get_compiled_ext()
140 141
141 142
142 143 class ModuleReloader(object):
143 144 enabled = False
144 145 """Whether this reloader is enabled"""
145 146
146 147 failed = {}
147 148 """Modules that failed to reload: {module: mtime-on-failed-reload, ...}"""
148 149
149 150 modules = {}
150 151 """Modules specially marked as autoreloadable."""
151 152
152 153 skip_modules = {}
153 154 """Modules specially marked as not autoreloadable."""
154 155
155 156 check_all = True
156 157 """Autoreload all modules, not just those listed in 'modules'"""
157 158
158 159 old_objects = {}
159 160 """(module-name, name) -> weakref, for replacing old code objects"""
160 161
161 162 def mark_module_skipped(self, module_name):
162 163 """Skip reloading the named module in the future"""
163 164 try:
164 165 del self.modules[module_name]
165 166 except KeyError:
166 167 pass
167 168 self.skip_modules[module_name] = True
168 169
169 170 def mark_module_reloadable(self, module_name):
170 171 """Reload the named module in the future (if it is imported)"""
171 172 try:
172 173 del self.skip_modules[module_name]
173 174 except KeyError:
174 175 pass
175 176 self.modules[module_name] = True
176 177
177 178 def aimport_module(self, module_name):
178 179 """Import a module, and mark it reloadable
179 180
180 181 Returns
181 182 -------
182 183 top_module : module
183 184 The imported module if it is top-level, or the top-level
184 185 top_name : module
185 186 Name of top_module
186 187
187 188 """
188 189 self.mark_module_reloadable(module_name)
189 190
190 191 __import__(module_name)
191 192 top_name = module_name.split('.')[0]
192 193 top_module = sys.modules[top_name]
193 194 return top_module, top_name
194 195
195 196 def check(self, check_all=False):
196 197 """Check whether some modules need to be reloaded."""
197 198
198 199 if not self.enabled and not check_all:
199 200 return
200 201
201 202 if check_all or self.check_all:
202 203 modules = sys.modules.keys()
203 204 else:
204 205 modules = self.modules.keys()
205 206
206 207 for modname in modules:
207 208 m = sys.modules.get(modname, None)
208 209
209 210 if modname in self.skip_modules:
210 211 continue
211 212
212 213 if not hasattr(m, '__file__'):
213 214 continue
214 215
215 216 if m.__name__ == '__main__':
216 217 # we cannot reload(__main__)
217 218 continue
218 219
219 220 filename = m.__file__
220 221 path, ext = os.path.splitext(filename)
221 222
222 223 if ext.lower() == '.py':
223 224 ext = PY_COMPILED_EXT
224 225 pyc_filename = pyfile.cache_from_source(filename)
225 226 py_filename = filename
226 227 else:
227 228 pyc_filename = filename
228 229 try:
229 230 py_filename = pyfile.source_from_cache(filename)
230 231 except ValueError:
231 232 continue
232 233
233 234 try:
234 235 pymtime = os.stat(py_filename).st_mtime
235 236 if pymtime <= os.stat(pyc_filename).st_mtime:
236 237 continue
237 238 if self.failed.get(py_filename, None) == pymtime:
238 239 continue
239 240 except OSError:
240 241 continue
241 242
242 243 try:
243 244 superreload(m, reload, self.old_objects)
244 245 if py_filename in self.failed:
245 246 del self.failed[py_filename]
246 247 except:
247 print >> sys.stderr, "[autoreload of %s failed: %s]" % (
248 modname, traceback.format_exc(1))
248 print("[autoreload of %s failed: %s]" % (
249 modname, traceback.format_exc(1)), file=sys.stderr)
249 250 self.failed[py_filename] = pymtime
250 251
251 252 #------------------------------------------------------------------------------
252 253 # superreload
253 254 #------------------------------------------------------------------------------
254 255
255 256 if PY3:
256 257 func_attrs = ['__code__', '__defaults__', '__doc__',
257 258 '__closure__', '__globals__', '__dict__']
258 259 else:
259 260 func_attrs = ['func_code', 'func_defaults', 'func_doc',
260 261 'func_closure', 'func_globals', 'func_dict']
261 262
262 263
263 264 def update_function(old, new):
264 265 """Upgrade the code object of a function"""
265 266 for name in func_attrs:
266 267 try:
267 268 setattr(old, name, getattr(new, name))
268 269 except (AttributeError, TypeError):
269 270 pass
270 271
271 272
272 273 def update_class(old, new):
273 274 """Replace stuff in the __dict__ of a class, and upgrade
274 275 method code objects"""
275 276 for key in old.__dict__.keys():
276 277 old_obj = getattr(old, key)
277 278
278 279 try:
279 280 new_obj = getattr(new, key)
280 281 except AttributeError:
281 282 # obsolete attribute: remove it
282 283 try:
283 284 delattr(old, key)
284 285 except (AttributeError, TypeError):
285 286 pass
286 287 continue
287 288
288 289 if update_generic(old_obj, new_obj): continue
289 290
290 291 try:
291 292 setattr(old, key, getattr(new, key))
292 293 except (AttributeError, TypeError):
293 294 pass # skip non-writable attributes
294 295
295 296
296 297 def update_property(old, new):
297 298 """Replace get/set/del functions of a property"""
298 299 update_generic(old.fdel, new.fdel)
299 300 update_generic(old.fget, new.fget)
300 301 update_generic(old.fset, new.fset)
301 302
302 303
303 304 def isinstance2(a, b, typ):
304 305 return isinstance(a, typ) and isinstance(b, typ)
305 306
306 307
307 308 UPDATE_RULES = [
308 309 (lambda a, b: isinstance2(a, b, type),
309 310 update_class),
310 311 (lambda a, b: isinstance2(a, b, types.FunctionType),
311 312 update_function),
312 313 (lambda a, b: isinstance2(a, b, property),
313 314 update_property),
314 315 ]
315 316
316 317
317 318 if PY3:
318 319 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType),
319 320 lambda a, b: update_function(a.__func__, b.__func__)),
320 321 ])
321 322 else:
322 323 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
323 324 update_class),
324 325 (lambda a, b: isinstance2(a, b, types.MethodType),
325 326 lambda a, b: update_function(a.im_func, b.im_func)),
326 327 ])
327 328
328 329
329 330 def update_generic(a, b):
330 331 for type_check, update in UPDATE_RULES:
331 332 if type_check(a, b):
332 333 update(a, b)
333 334 return True
334 335 return False
335 336
336 337
337 338 class StrongRef(object):
338 339 def __init__(self, obj):
339 340 self.obj = obj
340 341 def __call__(self):
341 342 return self.obj
342 343
343 344
344 345 def superreload(module, reload=reload, old_objects={}):
345 346 """Enhanced version of the builtin reload function.
346 347
347 348 superreload remembers objects previously in the module, and
348 349
349 350 - upgrades the class dictionary of every old class in the module
350 351 - upgrades the code object of every old function and method
351 352 - clears the module's namespace before reloading
352 353
353 354 """
354 355
355 356 # collect old objects in the module
356 357 for name, obj in module.__dict__.items():
357 358 if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
358 359 continue
359 360 key = (module.__name__, name)
360 361 try:
361 362 old_objects.setdefault(key, []).append(weakref.ref(obj))
362 363 except TypeError:
363 364 # weakref doesn't work for all types;
364 365 # create strong references for 'important' cases
365 366 if not PY3 and isinstance(obj, types.ClassType):
366 367 old_objects.setdefault(key, []).append(StrongRef(obj))
367 368
368 369 # reload module
369 370 try:
370 371 # clear namespace first from old cruft
371 372 old_dict = module.__dict__.copy()
372 373 old_name = module.__name__
373 374 module.__dict__.clear()
374 375 module.__dict__['__name__'] = old_name
375 376 module.__dict__['__loader__'] = old_dict['__loader__']
376 377 except (TypeError, AttributeError, KeyError):
377 378 pass
378 379
379 380 try:
380 381 module = reload(module)
381 382 except:
382 383 # restore module dictionary on failed reload
383 384 module.__dict__.update(old_dict)
384 385 raise
385 386
386 387 # iterate over all objects and update functions & classes
387 388 for name, new_obj in module.__dict__.items():
388 389 key = (module.__name__, name)
389 390 if key not in old_objects: continue
390 391
391 392 new_refs = []
392 393 for old_ref in old_objects[key]:
393 394 old_obj = old_ref()
394 395 if old_obj is None: continue
395 396 new_refs.append(old_ref)
396 397 update_generic(old_obj, new_obj)
397 398
398 399 if new_refs:
399 400 old_objects[key] = new_refs
400 401 else:
401 402 del old_objects[key]
402 403
403 404 return module
404 405
405 406 #------------------------------------------------------------------------------
406 407 # IPython connectivity
407 408 #------------------------------------------------------------------------------
408 409
409 410 from IPython.core.hooks import TryNext
410 411 from IPython.core.magic import Magics, magics_class, line_magic
411 412 from IPython.core.plugin import Plugin
412 413
413 414 @magics_class
414 415 class AutoreloadMagics(Magics):
415 416 def __init__(self, *a, **kw):
416 417 super(AutoreloadMagics, self).__init__(*a, **kw)
417 418 self._reloader = ModuleReloader()
418 419 self._reloader.check_all = False
419 420
420 421 @line_magic
421 422 def autoreload(self, parameter_s=''):
422 423 r"""%autoreload => Reload modules automatically
423 424
424 425 %autoreload
425 426 Reload all modules (except those excluded by %aimport) automatically
426 427 now.
427 428
428 429 %autoreload 0
429 430 Disable automatic reloading.
430 431
431 432 %autoreload 1
432 433 Reload all modules imported with %aimport every time before executing
433 434 the Python code typed.
434 435
435 436 %autoreload 2
436 437 Reload all modules (except those excluded by %aimport) every time
437 438 before executing the Python code typed.
438 439
439 440 Reloading Python modules in a reliable way is in general
440 441 difficult, and unexpected things may occur. %autoreload tries to
441 442 work around common pitfalls by replacing function code objects and
442 443 parts of classes previously in the module with new versions. This
443 444 makes the following things to work:
444 445
445 446 - Functions and classes imported via 'from xxx import foo' are upgraded
446 447 to new versions when 'xxx' is reloaded.
447 448
448 449 - Methods and properties of classes are upgraded on reload, so that
449 450 calling 'c.foo()' on an object 'c' created before the reload causes
450 451 the new code for 'foo' to be executed.
451 452
452 453 Some of the known remaining caveats are:
453 454
454 455 - Replacing code objects does not always succeed: changing a @property
455 456 in a class to an ordinary method or a method to a member variable
456 457 can cause problems (but in old objects only).
457 458
458 459 - Functions that are removed (eg. via monkey-patching) from a module
459 460 before it is reloaded are not upgraded.
460 461
461 462 - C extension modules cannot be reloaded, and so cannot be
462 463 autoreloaded.
463 464
464 465 """
465 466 if parameter_s == '':
466 467 self._reloader.check(True)
467 468 elif parameter_s == '0':
468 469 self._reloader.enabled = False
469 470 elif parameter_s == '1':
470 471 self._reloader.check_all = False
471 472 self._reloader.enabled = True
472 473 elif parameter_s == '2':
473 474 self._reloader.check_all = True
474 475 self._reloader.enabled = True
475 476
476 477 @line_magic
477 478 def aimport(self, parameter_s='', stream=None):
478 479 """%aimport => Import modules for automatic reloading.
479 480
480 481 %aimport
481 482 List modules to automatically import and not to import.
482 483
483 484 %aimport foo
484 485 Import module 'foo' and mark it to be autoreloaded for %autoreload 1
485 486
486 487 %aimport -foo
487 488 Mark module 'foo' to not be autoreloaded for %autoreload 1
488 489 """
489 490 modname = parameter_s
490 491 if not modname:
491 492 to_reload = self._reloader.modules.keys()
492 493 to_reload.sort()
493 494 to_skip = self._reloader.skip_modules.keys()
494 495 to_skip.sort()
495 496 if stream is None:
496 497 stream = sys.stdout
497 498 if self._reloader.check_all:
498 499 stream.write("Modules to reload:\nall-except-skipped\n")
499 500 else:
500 501 stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload))
501 502 stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip))
502 503 elif modname.startswith('-'):
503 504 modname = modname[1:]
504 505 self._reloader.mark_module_skipped(modname)
505 506 else:
506 507 top_module, top_name = self._reloader.aimport_module(modname)
507 508
508 509 # Inject module to user namespace
509 510 self.shell.push({top_name: top_module})
510 511
511 512 def pre_run_code_hook(self, ip):
512 513 if not self._reloader.enabled:
513 514 raise TryNext
514 515 try:
515 516 self._reloader.check()
516 517 except:
517 518 pass
518 519
519 520
520 521 class AutoreloadPlugin(Plugin):
521 522 def __init__(self, shell=None, config=None):
522 523 super(AutoreloadPlugin, self).__init__(shell=shell, config=config)
523 524 self.auto_magics = AutoreloadMagics(shell)
524 525 shell.register_magics(self.auto_magics)
525 526 shell.set_hook('pre_run_code_hook', self.auto_magics.pre_run_code_hook)
526 527
527 528
528 529 _loaded = False
529 530
530 531
531 532 def load_ipython_extension(ip):
532 533 """Load the extension in IPython."""
533 534 global _loaded
534 535 if not _loaded:
535 536 plugin = AutoreloadPlugin(shell=ip, config=ip.config)
536 537 ip.plugin_manager.register_plugin('autoreload', plugin)
537 538 _loaded = True
@@ -1,281 +1,281 b''
1 1 """
2 2 Decorators for labeling and modifying behavior of test objects.
3 3
4 4 Decorators that merely return a modified version of the original
5 5 function object are straightforward. Decorators that return a new
6 6 function object need to use
7 7 ::
8 8
9 9 nose.tools.make_decorator(original_function)(decorator)
10 10
11 11 in returning the decorator, in order to preserve meta-data such as
12 12 function name, setup and teardown functions and so on - see
13 13 ``nose.tools`` for more information.
14 14
15 15 """
16 16 import warnings
17 17
18 18 # IPython changes: make this work if numpy not available
19 19 # Original code:
20 20 #from numpy.testing.utils import \
21 21 # WarningManager, WarningMessage
22 22 # Our version:
23 23 from _numpy_testing_utils import WarningManager
24 24 try:
25 25 from _numpy_testing_noseclasses import KnownFailureTest
26 26 except:
27 27 pass
28 28
29 29 # End IPython changes
30 30
31 31 def slow(t):
32 32 """
33 33 Label a test as 'slow'.
34 34
35 35 The exact definition of a slow test is obviously both subjective and
36 36 hardware-dependent, but in general any individual test that requires more
37 37 than a second or two should be labeled as slow (the whole suite consists of
38 38 thousands of tests, so even a second is significant).
39 39
40 40 Parameters
41 41 ----------
42 42 t : callable
43 43 The test to label as slow.
44 44
45 45 Returns
46 46 -------
47 47 t : callable
48 48 The decorated test `t`.
49 49
50 50 Examples
51 51 --------
52 52 The `numpy.testing` module includes ``import decorators as dec``.
53 53 A test can be decorated as slow like this::
54 54
55 55 from numpy.testing import *
56 56
57 57 @dec.slow
58 58 def test_big(self):
59 59 print 'Big, slow test'
60 60
61 61 """
62 62
63 63 t.slow = True
64 64 return t
65 65
66 66 def setastest(tf=True):
67 67 """
68 68 Signals to nose that this function is or is not a test.
69 69
70 70 Parameters
71 71 ----------
72 72 tf : bool
73 73 If True, specifies that the decorated callable is a test.
74 74 If False, specifies that the decorated callable is not a test.
75 75 Default is True.
76 76
77 77 Notes
78 78 -----
79 79 This decorator can't use the nose namespace, because it can be
80 80 called from a non-test module. See also ``istest`` and ``nottest`` in
81 81 ``nose.tools``.
82 82
83 83 Examples
84 84 --------
85 85 `setastest` can be used in the following way::
86 86
87 87 from numpy.testing.decorators import setastest
88 88
89 89 @setastest(False)
90 90 def func_with_test_in_name(arg1, arg2):
91 91 pass
92 92
93 93 """
94 94 def set_test(t):
95 95 t.__test__ = tf
96 96 return t
97 97 return set_test
98 98
99 99 def skipif(skip_condition, msg=None):
100 100 """
101 101 Make function raise SkipTest exception if a given condition is true.
102 102
103 103 If the condition is a callable, it is used at runtime to dynamically
104 104 make the decision. This is useful for tests that may require costly
105 105 imports, to delay the cost until the test suite is actually executed.
106 106
107 107 Parameters
108 108 ----------
109 109 skip_condition : bool or callable
110 110 Flag to determine whether to skip the decorated test.
111 111 msg : str, optional
112 112 Message to give on raising a SkipTest exception. Default is None.
113 113
114 114 Returns
115 115 -------
116 116 decorator : function
117 117 Decorator which, when applied to a function, causes SkipTest
118 118 to be raised when `skip_condition` is True, and the function
119 119 to be called normally otherwise.
120 120
121 121 Notes
122 122 -----
123 123 The decorator itself is decorated with the ``nose.tools.make_decorator``
124 124 function in order to transmit function name, and various other metadata.
125 125
126 126 """
127 127
128 128 def skip_decorator(f):
129 129 # Local import to avoid a hard nose dependency and only incur the
130 130 # import time overhead at actual test-time.
131 131 import nose
132 132
133 133 # Allow for both boolean or callable skip conditions.
134 134 if callable(skip_condition):
135 135 skip_val = lambda : skip_condition()
136 136 else:
137 137 skip_val = lambda : skip_condition
138 138
139 139 def get_msg(func,msg=None):
140 140 """Skip message with information about function being skipped."""
141 141 if msg is None:
142 142 out = 'Test skipped due to test condition'
143 143 else:
144 144 out = '\n'+msg
145 145
146 146 return "Skipping test: %s%s" % (func.__name__,out)
147 147
148 148 # We need to define *two* skippers because Python doesn't allow both
149 149 # return with value and yield inside the same function.
150 150 def skipper_func(*args, **kwargs):
151 151 """Skipper for normal test functions."""
152 152 if skip_val():
153 153 raise nose.SkipTest(get_msg(f,msg))
154 154 else:
155 155 return f(*args, **kwargs)
156 156
157 157 def skipper_gen(*args, **kwargs):
158 158 """Skipper for test generators."""
159 159 if skip_val():
160 160 raise nose.SkipTest(get_msg(f,msg))
161 161 else:
162 162 for x in f(*args, **kwargs):
163 163 yield x
164 164
165 165 # Choose the right skipper to use when building the actual decorator.
166 166 if nose.util.isgenerator(f):
167 167 skipper = skipper_gen
168 168 else:
169 169 skipper = skipper_func
170 170
171 171 return nose.tools.make_decorator(f)(skipper)
172 172
173 173 return skip_decorator
174 174
175 175 def knownfailureif(fail_condition, msg=None):
176 176 """
177 177 Make function raise KnownFailureTest exception if given condition is true.
178 178
179 179 If the condition is a callable, it is used at runtime to dynamically
180 180 make the decision. This is useful for tests that may require costly
181 181 imports, to delay the cost until the test suite is actually executed.
182 182
183 183 Parameters
184 184 ----------
185 185 fail_condition : bool or callable
186 186 Flag to determine whether to mark the decorated test as a known
187 187 failure (if True) or not (if False).
188 188 msg : str, optional
189 189 Message to give on raising a KnownFailureTest exception.
190 190 Default is None.
191 191
192 192 Returns
193 193 -------
194 194 decorator : function
195 195 Decorator, which, when applied to a function, causes SkipTest
196 196 to be raised when `skip_condition` is True, and the function
197 197 to be called normally otherwise.
198 198
199 199 Notes
200 200 -----
201 201 The decorator itself is decorated with the ``nose.tools.make_decorator``
202 202 function in order to transmit function name, and various other metadata.
203 203
204 204 """
205 205 if msg is None:
206 206 msg = 'Test skipped due to known failure'
207 207
208 208 # Allow for both boolean or callable known failure conditions.
209 209 if callable(fail_condition):
210 210 fail_val = lambda : fail_condition()
211 211 else:
212 212 fail_val = lambda : fail_condition
213 213
214 214 def knownfail_decorator(f):
215 215 # Local import to avoid a hard nose dependency and only incur the
216 216 # import time overhead at actual test-time.
217 217 import nose
218 218 def knownfailer(*args, **kwargs):
219 219 if fail_val():
220 raise KnownFailureTest, msg
220 raise KnownFailureTest(msg)
221 221 else:
222 222 return f(*args, **kwargs)
223 223 return nose.tools.make_decorator(f)(knownfailer)
224 224
225 225 return knownfail_decorator
226 226
227 227 def deprecated(conditional=True):
228 228 """
229 229 Filter deprecation warnings while running the test suite.
230 230
231 231 This decorator can be used to filter DeprecationWarning's, to avoid
232 232 printing them during the test suite run, while checking that the test
233 233 actually raises a DeprecationWarning.
234 234
235 235 Parameters
236 236 ----------
237 237 conditional : bool or callable, optional
238 238 Flag to determine whether to mark test as deprecated or not. If the
239 239 condition is a callable, it is used at runtime to dynamically make the
240 240 decision. Default is True.
241 241
242 242 Returns
243 243 -------
244 244 decorator : function
245 245 The `deprecated` decorator itself.
246 246
247 247 Notes
248 248 -----
249 249 .. versionadded:: 1.4.0
250 250
251 251 """
252 252 def deprecate_decorator(f):
253 253 # Local import to avoid a hard nose dependency and only incur the
254 254 # import time overhead at actual test-time.
255 255 import nose
256 256
257 257 def _deprecated_imp(*args, **kwargs):
258 258 # Poor man's replacement for the with statement
259 259 ctx = WarningManager(record=True)
260 260 l = ctx.__enter__()
261 261 warnings.simplefilter('always')
262 262 try:
263 263 f(*args, **kwargs)
264 264 if not len(l) > 0:
265 265 raise AssertionError("No warning raised when calling %s"
266 266 % f.__name__)
267 267 if not l[0].category is DeprecationWarning:
268 268 raise AssertionError("First warning for %s is not a " \
269 269 "DeprecationWarning( is %s)" % (f.__name__, l[0]))
270 270 finally:
271 271 ctx.__exit__()
272 272
273 273 if callable(conditional):
274 274 cond = conditional()
275 275 else:
276 276 cond = conditional
277 277 if cond:
278 278 return nose.tools.make_decorator(f)(_deprecated_imp)
279 279 else:
280 280 return f
281 281 return deprecate_decorator
@@ -1,1900 +1,1900 b''
1 1 """Pexpect is a Python module for spawning child applications and controlling
2 2 them automatically. Pexpect can be used for automating interactive applications
3 3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4 4 scripts for duplicating software package installations on different servers. It
5 5 can be used for automated software testing. Pexpect is in the spirit of Don
6 6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7 7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
8 8 use C, Expect, or TCL extensions. It should work on any platform that supports
9 9 the standard Python pty module. The Pexpect interface focuses on ease of use so
10 10 that simple tasks are easy.
11 11
12 12 There are two main interfaces to the Pexpect system; these are the function,
13 13 run() and the class, spawn. The spawn class is more powerful. The run()
14 14 function is simpler than spawn, and is good for quickly calling program. When
15 15 you call the run() function it executes a given program and then returns the
16 16 output. This is a handy replacement for os.system().
17 17
18 18 For example::
19 19
20 20 pexpect.run('ls -la')
21 21
22 22 The spawn class is the more powerful interface to the Pexpect system. You can
23 23 use this to spawn a child program then interact with it by sending input and
24 24 expecting responses (waiting for patterns in the child's output).
25 25
26 26 For example::
27 27
28 28 child = pexpect.spawn('scp foo myname@host.example.com:.')
29 29 child.expect ('Password:')
30 30 child.sendline (mypassword)
31 31
32 32 This works even for commands that ask for passwords or other input outside of
33 33 the normal stdio streams. For example, ssh reads input directly from the TTY
34 34 device which bypasses stdin.
35 35
36 36 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
37 37 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
38 38 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
39 39 Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
40 40 Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
41 41 Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
42 42 Spiegel, Jan Grant, Shane Kerr and Thomas Kluyver. Let me know if I forgot anyone.
43 43
44 44 Pexpect is free, open source, and all that good stuff.
45 45
46 46 Permission is hereby granted, free of charge, to any person obtaining a copy of
47 47 this software and associated documentation files (the "Software"), to deal in
48 48 the Software without restriction, including without limitation the rights to
49 49 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
50 50 of the Software, and to permit persons to whom the Software is furnished to do
51 51 so, subject to the following conditions:
52 52
53 53 The above copyright notice and this permission notice shall be included in all
54 54 copies or substantial portions of the Software.
55 55
56 56 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
57 57 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
58 58 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
59 59 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
60 60 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
61 61 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
62 62 SOFTWARE.
63 63
64 64 Pexpect Copyright (c) 2008-2011 Noah Spurrier
65 65 http://pexpect.sourceforge.net/
66 66 """
67 67
68 68 try:
69 69 import os, sys, time
70 70 import select
71 71 import re
72 72 import struct
73 73 import resource
74 74 import types
75 75 import pty
76 76 import tty
77 77 import termios
78 78 import fcntl
79 79 import errno
80 80 import traceback
81 81 import signal
82 82 except ImportError as e:
83 83 raise ImportError (str(e) + """
84 84
85 85 A critical module was not found. Probably this operating system does not
86 86 support it. Pexpect is intended for UNIX-like operating systems.""")
87 87
88 88 __version__ = '2.6.dev'
89 89 version = __version__
90 90 version_info = (2,6,'dev')
91 91 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which',
92 92 'split_command_line', '__version__']
93 93
94 94 # Exception classes used by this module.
95 95 class ExceptionPexpect(Exception):
96 96
97 97 """Base class for all exceptions raised by this module.
98 98 """
99 99
100 100 def __init__(self, value):
101 101
102 102 self.value = value
103 103
104 104 def __str__(self):
105 105
106 106 return str(self.value)
107 107
108 108 def get_trace(self):
109 109
110 110 """This returns an abbreviated stack trace with lines that only concern
111 111 the caller. In other words, the stack trace inside the Pexpect module
112 112 is not included. """
113 113
114 114 tblist = traceback.extract_tb(sys.exc_info()[2])
115 115 #tblist = filter(self.__filter_not_pexpect, tblist)
116 116 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
117 117 tblist = traceback.format_list(tblist)
118 118 return ''.join(tblist)
119 119
120 120 def __filter_not_pexpect(self, trace_list_item):
121 121
122 122 """This returns True if list item 0 the string 'pexpect.py' in it. """
123 123
124 124 if trace_list_item[0].find('pexpect.py') == -1:
125 125 return True
126 126 else:
127 127 return False
128 128
129 129 class EOF(ExceptionPexpect):
130 130
131 131 """Raised when EOF is read from a child. This usually means the child has exited."""
132 132
133 133 class TIMEOUT(ExceptionPexpect):
134 134
135 135 """Raised when a read time exceeds the timeout. """
136 136
137 137 ##class TIMEOUT_PATTERN(TIMEOUT):
138 138 ## """Raised when the pattern match time exceeds the timeout.
139 139 ## This is different than a read TIMEOUT because the child process may
140 140 ## give output, thus never give a TIMEOUT, but the output
141 141 ## may never match a pattern.
142 142 ## """
143 143 ##class MAXBUFFER(ExceptionPexpect):
144 144 ## """Raised when a scan buffer fills before matching an expected pattern."""
145 145
146 146 PY3 = (sys.version_info[0] >= 3)
147 147
148 148 def _cast_bytes(s, enc):
149 149 if isinstance(s, unicode):
150 150 return s.encode(enc)
151 151 return s
152 152
153 153 def _cast_unicode(s, enc):
154 154 if isinstance(s, bytes):
155 155 return s.decode(enc)
156 156 return s
157 157
158 158 re_type = type(re.compile(''))
159 159
160 160 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None,
161 161 logfile=None, cwd=None, env=None, encoding='utf-8'):
162 162
163 163 """
164 164 This function runs the given command; waits for it to finish; then
165 165 returns all output as a string. STDERR is included in output. If the full
166 166 path to the command is not given then the path is searched.
167 167
168 168 Note that lines are terminated by CR/LF (\\r\\n) combination even on
169 169 UNIX-like systems because this is the standard for pseudo ttys. If you set
170 170 'withexitstatus' to true, then run will return a tuple of (command_output,
171 171 exitstatus). If 'withexitstatus' is false then this returns just
172 172 command_output.
173 173
174 174 The run() function can often be used instead of creating a spawn instance.
175 175 For example, the following code uses spawn::
176 176
177 177 from pexpect import *
178 178 child = spawn('scp foo myname@host.example.com:.')
179 179 child.expect ('(?i)password')
180 180 child.sendline (mypassword)
181 181
182 182 The previous code can be replace with the following::
183 183
184 184 from pexpect import *
185 185 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
186 186
187 187 Examples
188 188 ========
189 189
190 190 Start the apache daemon on the local machine::
191 191
192 192 from pexpect import *
193 193 run ("/usr/local/apache/bin/apachectl start")
194 194
195 195 Check in a file using SVN::
196 196
197 197 from pexpect import *
198 198 run ("svn ci -m 'automatic commit' my_file.py")
199 199
200 200 Run a command and capture exit status::
201 201
202 202 from pexpect import *
203 203 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
204 204
205 205 Tricky Examples
206 206 ===============
207 207
208 208 The following will run SSH and execute 'ls -l' on the remote machine. The
209 209 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
210 210
211 211 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
212 212
213 213 This will start mencoder to rip a video from DVD. This will also display
214 214 progress ticks every 5 seconds as it runs. For example::
215 215
216 216 from pexpect import *
217 217 def print_ticks(d):
218 218 print d['event_count'],
219 219 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
220 220
221 221 The 'events' argument should be a dictionary of patterns and responses.
222 222 Whenever one of the patterns is seen in the command out run() will send the
223 223 associated response string. Note that you should put newlines in your
224 224 string if Enter is necessary. The responses may also contain callback
225 225 functions. Any callback is function that takes a dictionary as an argument.
226 226 The dictionary contains all the locals from the run() function, so you can
227 227 access the child spawn object or any other variable defined in run()
228 228 (event_count, child, and extra_args are the most useful). A callback may
229 229 return True to stop the current run process otherwise run() continues until
230 230 the next event. A callback may also return a string which will be sent to
231 231 the child. 'extra_args' is not used by directly run(). It provides a way to
232 232 pass data to a callback function through run() through the locals
233 233 dictionary passed to a callback."""
234 234
235 235 if timeout == -1:
236 236 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
237 237 encoding=encoding)
238 238 else:
239 239 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
240 240 cwd=cwd, env=env, encoding=encoding)
241 241 if events is not None:
242 242 patterns = events.keys()
243 243 responses = events.values()
244 244 else:
245 245 patterns=None # We assume that EOF or TIMEOUT will save us.
246 246 responses=None
247 247 child_result_list = []
248 248 event_count = 0
249 249 while 1:
250 250 try:
251 251 index = child.expect (patterns)
252 252 if isinstance(child.after, basestring):
253 253 child_result_list.append(child.before + child.after)
254 254 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
255 255 child_result_list.append(child.before)
256 256 if isinstance(responses[index], basestring):
257 257 child.send(responses[index])
258 258 elif type(responses[index]) is types.FunctionType:
259 259 callback_result = responses[index](locals())
260 260 sys.stdout.flush()
261 261 if isinstance(callback_result, basestring):
262 262 child.send(callback_result)
263 263 elif callback_result:
264 264 break
265 265 else:
266 266 raise TypeError ('The callback must be a string or function type.')
267 267 event_count = event_count + 1
268 268 except TIMEOUT as e:
269 269 child_result_list.append(child.before)
270 270 break
271 271 except EOF as e:
272 272 child_result_list.append(child.before)
273 273 break
274 274 child_result = child._empty_buffer.join(child_result_list)
275 275 if withexitstatus:
276 276 child.close()
277 277 return (child_result, child.exitstatus)
278 278 else:
279 279 return child_result
280 280
281 281 class spawnb(object):
282 282 """Use this class to start and control child applications with a pure-bytes
283 283 interface."""
284 284
285 285 _buffer_type = bytes
286 286 def _cast_buffer_type(self, s):
287 287 return _cast_bytes(s, self.encoding)
288 288 _empty_buffer = b''
289 289 _pty_newline = b'\r\n'
290 290
291 291 # Some code needs this to exist, but it's mainly for the spawn subclass.
292 292 encoding = 'utf-8'
293 293
294 294 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None,
295 295 logfile=None, cwd=None, env=None):
296 296
297 297 """This is the constructor. The command parameter may be a string that
298 298 includes a command and any arguments to the command. For example::
299 299
300 300 child = pexpect.spawn ('/usr/bin/ftp')
301 301 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
302 302 child = pexpect.spawn ('ls -latr /tmp')
303 303
304 304 You may also construct it with a list of arguments like so::
305 305
306 306 child = pexpect.spawn ('/usr/bin/ftp', [])
307 307 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
308 308 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
309 309
310 310 After this the child application will be created and will be ready to
311 311 talk to. For normal use, see expect() and send() and sendline().
312 312
313 313 Remember that Pexpect does NOT interpret shell meta characters such as
314 314 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
315 315 If you want to run a command and pipe it through another command then
316 316 you must also start a shell. For example::
317 317
318 318 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
319 319 child.expect(pexpect.EOF)
320 320
321 321 The second form of spawn (where you pass a list of arguments) is useful
322 322 in situations where you wish to spawn a command and pass it its own
323 323 argument list. This can make syntax more clear. For example, the
324 324 following is equivalent to the previous example::
325 325
326 326 shell_cmd = 'ls -l | grep LOG > log_list.txt'
327 327 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
328 328 child.expect(pexpect.EOF)
329 329
330 330 The maxread attribute sets the read buffer size. This is maximum number
331 331 of bytes that Pexpect will try to read from a TTY at one time. Setting
332 332 the maxread size to 1 will turn off buffering. Setting the maxread
333 333 value higher may help performance in cases where large amounts of
334 334 output are read back from the child. This feature is useful in
335 335 conjunction with searchwindowsize.
336 336
337 337 The searchwindowsize attribute sets the how far back in the incomming
338 338 seach buffer Pexpect will search for pattern matches. Every time
339 339 Pexpect reads some data from the child it will append the data to the
340 340 incomming buffer. The default is to search from the beginning of the
341 341 imcomming buffer each time new data is read from the child. But this is
342 342 very inefficient if you are running a command that generates a large
343 343 amount of data where you want to match The searchwindowsize does not
344 344 effect the size of the incomming data buffer. You will still have
345 345 access to the full buffer after expect() returns.
346 346
347 347 The logfile member turns on or off logging. All input and output will
348 348 be copied to the given file object. Set logfile to None to stop
349 349 logging. This is the default. Set logfile to sys.stdout to echo
350 350 everything to standard output. The logfile is flushed after each write.
351 351
352 352 Example log input and output to a file::
353 353
354 354 child = pexpect.spawn('some_command')
355 355 fout = open('mylog.txt','w')
356 356 child.logfile = fout
357 357
358 358 Example log to stdout::
359 359
360 360 child = pexpect.spawn('some_command')
361 361 child.logfile = sys.stdout
362 362
363 363 The logfile_read and logfile_send members can be used to separately log
364 364 the input from the child and output sent to the child. Sometimes you
365 365 don't want to see everything you write to the child. You only want to
366 366 log what the child sends back. For example::
367 367
368 368 child = pexpect.spawn('some_command')
369 369 child.logfile_read = sys.stdout
370 370
371 371 To separately log output sent to the child use logfile_send::
372 372
373 373 self.logfile_send = fout
374 374
375 375 The delaybeforesend helps overcome a weird behavior that many users
376 376 were experiencing. The typical problem was that a user would expect() a
377 377 "Password:" prompt and then immediately call sendline() to send the
378 378 password. The user would then see that their password was echoed back
379 379 to them. Passwords don't normally echo. The problem is caused by the
380 380 fact that most applications print out the "Password" prompt and then
381 381 turn off stdin echo, but if you send your password before the
382 382 application turned off echo, then you get your password echoed.
383 383 Normally this wouldn't be a problem when interacting with a human at a
384 384 real keyboard. If you introduce a slight delay just before writing then
385 385 this seems to clear up the problem. This was such a common problem for
386 386 many users that I decided that the default pexpect behavior should be
387 387 to sleep just before writing to the child application. 1/20th of a
388 388 second (50 ms) seems to be enough to clear up the problem. You can set
389 389 delaybeforesend to 0 to return to the old behavior. Most Linux machines
390 390 don't like this to be below 0.03. I don't know why.
391 391
392 392 Note that spawn is clever about finding commands on your path.
393 393 It uses the same logic that "which" uses to find executables.
394 394
395 395 If you wish to get the exit status of the child you must call the
396 396 close() method. The exit or signal status of the child will be stored
397 397 in self.exitstatus or self.signalstatus. If the child exited normally
398 398 then exitstatus will store the exit return code and signalstatus will
399 399 be None. If the child was terminated abnormally with a signal then
400 400 signalstatus will store the signal value and exitstatus will be None.
401 401 If you need more detail you can also read the self.status member which
402 402 stores the status returned by os.waitpid. You can interpret this using
403 403 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
404 404
405 405 self.STDIN_FILENO = pty.STDIN_FILENO
406 406 self.STDOUT_FILENO = pty.STDOUT_FILENO
407 407 self.STDERR_FILENO = pty.STDERR_FILENO
408 408 self.stdin = sys.stdin
409 409 self.stdout = sys.stdout
410 410 self.stderr = sys.stderr
411 411
412 412 self.searcher = None
413 413 self.ignorecase = False
414 414 self.before = None
415 415 self.after = None
416 416 self.match = None
417 417 self.match_index = None
418 418 self.terminated = True
419 419 self.exitstatus = None
420 420 self.signalstatus = None
421 421 self.status = None # status returned by os.waitpid
422 422 self.flag_eof = False
423 423 self.pid = None
424 424 self.child_fd = -1 # initially closed
425 425 self.timeout = timeout
426 426 self.delimiter = EOF
427 427 self.logfile = logfile
428 428 self.logfile_read = None # input from child (read_nonblocking)
429 429 self.logfile_send = None # output to send (send, sendline)
430 430 self.maxread = maxread # max bytes to read at one time into buffer
431 431 self.buffer = self._empty_buffer # This is the read buffer. See maxread.
432 432 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
433 433 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
434 434 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
435 435 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
436 436 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
437 437 self.softspace = False # File-like object.
438 438 self.name = '<' + repr(self) + '>' # File-like object.
439 439 self.closed = True # File-like object.
440 440 self.cwd = cwd
441 441 self.env = env
442 442 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
443 443 # Solaris uses internal __fork_pty(). All others use pty.fork().
444 444 if 'solaris' in sys.platform.lower() or 'sunos5' in sys.platform.lower():
445 445 self.use_native_pty_fork = False
446 446 else:
447 447 self.use_native_pty_fork = True
448 448
449 449
450 450 # allow dummy instances for subclasses that may not use command or args.
451 451 if command is None:
452 452 self.command = None
453 453 self.args = None
454 454 self.name = '<pexpect factory incomplete>'
455 455 else:
456 456 self._spawn (command, args)
457 457
458 458 def __del__(self):
459 459
460 460 """This makes sure that no system resources are left open. Python only
461 461 garbage collects Python objects. OS file descriptors are not Python
462 462 objects, so they must be handled explicitly. If the child file
463 463 descriptor was opened outside of this class (passed to the constructor)
464 464 then this does not close it. """
465 465
466 466 if not self.closed:
467 467 # It is possible for __del__ methods to execute during the
468 468 # teardown of the Python VM itself. Thus self.close() may
469 469 # trigger an exception because os.close may be None.
470 470 # -- Fernando Perez
471 471 try:
472 472 self.close()
473 473 except:
474 474 pass
475 475
476 476 def __str__(self):
477 477
478 478 """This returns a human-readable string that represents the state of
479 479 the object. """
480 480
481 481 s = []
482 482 s.append(repr(self))
483 483 s.append('version: ' + __version__)
484 484 s.append('command: ' + str(self.command))
485 485 s.append('args: ' + str(self.args))
486 486 s.append('searcher: ' + str(self.searcher))
487 487 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
488 488 s.append('before (last 100 chars): ' + str(self.before)[-100:])
489 489 s.append('after: ' + str(self.after))
490 490 s.append('match: ' + str(self.match))
491 491 s.append('match_index: ' + str(self.match_index))
492 492 s.append('exitstatus: ' + str(self.exitstatus))
493 493 s.append('flag_eof: ' + str(self.flag_eof))
494 494 s.append('pid: ' + str(self.pid))
495 495 s.append('child_fd: ' + str(self.child_fd))
496 496 s.append('closed: ' + str(self.closed))
497 497 s.append('timeout: ' + str(self.timeout))
498 498 s.append('delimiter: ' + str(self.delimiter))
499 499 s.append('logfile: ' + str(self.logfile))
500 500 s.append('logfile_read: ' + str(self.logfile_read))
501 501 s.append('logfile_send: ' + str(self.logfile_send))
502 502 s.append('maxread: ' + str(self.maxread))
503 503 s.append('ignorecase: ' + str(self.ignorecase))
504 504 s.append('searchwindowsize: ' + str(self.searchwindowsize))
505 505 s.append('delaybeforesend: ' + str(self.delaybeforesend))
506 506 s.append('delayafterclose: ' + str(self.delayafterclose))
507 507 s.append('delayafterterminate: ' + str(self.delayafterterminate))
508 508 return '\n'.join(s)
509 509
510 510 def _spawn(self,command,args=[]):
511 511
512 512 """This starts the given command in a child process. This does all the
513 513 fork/exec type of stuff for a pty. This is called by __init__. If args
514 514 is empty then command will be parsed (split on spaces) and args will be
515 515 set to parsed arguments. """
516 516
517 517 # The pid and child_fd of this object get set by this method.
518 518 # Note that it is difficult for this method to fail.
519 519 # You cannot detect if the child process cannot start.
520 520 # So the only way you can tell if the child process started
521 521 # or not is to try to read from the file descriptor. If you get
522 522 # EOF immediately then it means that the child is already dead.
523 523 # That may not necessarily be bad because you may haved spawned a child
524 524 # that performs some task; creates no stdout output; and then dies.
525 525
526 526 # If command is an int type then it may represent a file descriptor.
527 527 if type(command) == type(0):
528 528 raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.')
529 529
530 530 if type (args) != type([]):
531 531 raise TypeError ('The argument, args, must be a list.')
532 532
533 533 if args == []:
534 534 self.args = split_command_line(command)
535 535 self.command = self.args[0]
536 536 else:
537 537 self.args = args[:] # work with a copy
538 538 self.args.insert (0, command)
539 539 self.command = command
540 540
541 541 command_with_path = which(self.command)
542 542 if command_with_path is None:
543 543 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
544 544 self.command = command_with_path
545 545 self.args[0] = self.command
546 546
547 547 self.name = '<' + ' '.join (self.args) + '>'
548 548
549 549 assert self.pid is None, 'The pid member should be None.'
550 550 assert self.command is not None, 'The command member should not be None.'
551 551
552 552 if self.use_native_pty_fork:
553 553 try:
554 554 self.pid, self.child_fd = pty.fork()
555 555 except OSError as e:
556 556 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
557 557 else: # Use internal __fork_pty
558 558 self.pid, self.child_fd = self.__fork_pty()
559 559
560 560 if self.pid == 0: # Child
561 561 try:
562 562 self.child_fd = sys.stdout.fileno() # used by setwinsize()
563 563 self.setwinsize(24, 80)
564 564 except:
565 565 # Some platforms do not like setwinsize (Cygwin).
566 566 # This will cause problem when running applications that
567 567 # are very picky about window size.
568 568 # This is a serious limitation, but not a show stopper.
569 569 pass
570 570 # Do not allow child to inherit open file descriptors from parent.
571 571 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
572 572 for i in range (3, max_fd):
573 573 try:
574 574 os.close (i)
575 575 except OSError:
576 576 pass
577 577
578 578 # I don't know why this works, but ignoring SIGHUP fixes a
579 579 # problem when trying to start a Java daemon with sudo
580 580 # (specifically, Tomcat).
581 581 signal.signal(signal.SIGHUP, signal.SIG_IGN)
582 582
583 583 if self.cwd is not None:
584 584 os.chdir(self.cwd)
585 585 if self.env is None:
586 586 os.execv(self.command, self.args)
587 587 else:
588 588 os.execvpe(self.command, self.args, self.env)
589 589
590 590 # Parent
591 591 self.terminated = False
592 592 self.closed = False
593 593
594 594 def __fork_pty(self):
595 595
596 596 """This implements a substitute for the forkpty system call. This
597 597 should be more portable than the pty.fork() function. Specifically,
598 598 this should work on Solaris.
599 599
600 600 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
601 601 resolve the issue with Python's pty.fork() not supporting Solaris,
602 602 particularly ssh. Based on patch to posixmodule.c authored by Noah
603 603 Spurrier::
604 604
605 605 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
606 606
607 607 """
608 608
609 609 parent_fd, child_fd = os.openpty()
610 610 if parent_fd < 0 or child_fd < 0:
611 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
611 raise ExceptionPexpect("Error! Could not open pty with os.openpty().")
612 612
613 613 pid = os.fork()
614 614 if pid < 0:
615 raise ExceptionPexpect, "Error! Failed os.fork()."
615 raise ExceptionPexpect("Error! Failed os.fork().")
616 616 elif pid == 0:
617 617 # Child.
618 618 os.close(parent_fd)
619 619 self.__pty_make_controlling_tty(child_fd)
620 620
621 621 os.dup2(child_fd, 0)
622 622 os.dup2(child_fd, 1)
623 623 os.dup2(child_fd, 2)
624 624
625 625 if child_fd > 2:
626 626 os.close(child_fd)
627 627 else:
628 628 # Parent.
629 629 os.close(child_fd)
630 630
631 631 return pid, parent_fd
632 632
633 633 def __pty_make_controlling_tty(self, tty_fd):
634 634
635 635 """This makes the pseudo-terminal the controlling tty. This should be
636 636 more portable than the pty.fork() function. Specifically, this should
637 637 work on Solaris. """
638 638
639 639 child_name = os.ttyname(tty_fd)
640 640
641 641 # Disconnect from controlling tty. Harmless if not already connected.
642 642 try:
643 643 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
644 644 if fd >= 0:
645 645 os.close(fd)
646 646 except:
647 647 # Already disconnected. This happens if running inside cron.
648 648 pass
649 649
650 650 os.setsid()
651 651
652 652 # Verify we are disconnected from controlling tty
653 653 # by attempting to open it again.
654 654 try:
655 655 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
656 656 if fd >= 0:
657 657 os.close(fd)
658 raise ExceptionPexpect, "Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty."
658 raise ExceptionPexpect("Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty.")
659 659 except:
660 660 # Good! We are disconnected from a controlling tty.
661 661 pass
662 662
663 663 # Verify we can open child pty.
664 664 fd = os.open(child_name, os.O_RDWR);
665 665 if fd < 0:
666 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
666 raise ExceptionPexpect("Error! Could not open child pty, " + child_name)
667 667 else:
668 668 os.close(fd)
669 669
670 670 # Verify we now have a controlling tty.
671 671 fd = os.open("/dev/tty", os.O_WRONLY)
672 672 if fd < 0:
673 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
673 raise ExceptionPexpect("Error! Could not open controlling tty, /dev/tty")
674 674 else:
675 675 os.close(fd)
676 676
677 677 def fileno (self): # File-like object.
678 678
679 679 """This returns the file descriptor of the pty for the child.
680 680 """
681 681
682 682 return self.child_fd
683 683
684 684 def close (self, force=True): # File-like object.
685 685
686 686 """This closes the connection with the child application. Note that
687 687 calling close() more than once is valid. This emulates standard Python
688 688 behavior with files. Set force to True if you want to make sure that
689 689 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
690 690 and SIGINT). """
691 691
692 692 if not self.closed:
693 693 self.flush()
694 694 os.close (self.child_fd)
695 695 time.sleep(self.delayafterclose) # Give kernel time to update process status.
696 696 if self.isalive():
697 697 if not self.terminate(force):
698 698 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
699 699 self.child_fd = -1
700 700 self.closed = True
701 701 #self.pid = None
702 702
703 703 def flush (self): # File-like object.
704 704
705 705 """This does nothing. It is here to support the interface for a
706 706 File-like object. """
707 707
708 708 pass
709 709
710 710 def isatty (self): # File-like object.
711 711
712 712 """This returns True if the file descriptor is open and connected to a
713 713 tty(-like) device, else False. """
714 714
715 715 return os.isatty(self.child_fd)
716 716
717 717 def waitnoecho (self, timeout=-1):
718 718
719 719 """This waits until the terminal ECHO flag is set False. This returns
720 720 True if the echo mode is off. This returns False if the ECHO flag was
721 721 not set False before the timeout. This can be used to detect when the
722 722 child is waiting for a password. Usually a child application will turn
723 723 off echo mode when it is waiting for the user to enter a password. For
724 724 example, instead of expecting the "password:" prompt you can wait for
725 725 the child to set ECHO off::
726 726
727 727 p = pexpect.spawn ('ssh user@example.com')
728 728 p.waitnoecho()
729 729 p.sendline(mypassword)
730 730
731 731 If timeout==-1 then this method will use the value in self.timeout.
732 732 If timeout==None then this method to block until ECHO flag is False.
733 733 """
734 734
735 735 if timeout == -1:
736 736 timeout = self.timeout
737 737 if timeout is not None:
738 738 end_time = time.time() + timeout
739 739 while True:
740 740 if not self.getecho():
741 741 return True
742 742 if timeout < 0 and timeout is not None:
743 743 return False
744 744 if timeout is not None:
745 745 timeout = end_time - time.time()
746 746 time.sleep(0.1)
747 747
748 748 def getecho (self):
749 749
750 750 """This returns the terminal echo mode. This returns True if echo is
751 751 on or False if echo is off. Child applications that are expecting you
752 752 to enter a password often set ECHO False. See waitnoecho(). """
753 753
754 754 attr = termios.tcgetattr(self.child_fd)
755 755 if attr[3] & termios.ECHO:
756 756 return True
757 757 return False
758 758
759 759 def setecho (self, state):
760 760
761 761 """This sets the terminal echo mode on or off. Note that anything the
762 762 child sent before the echo will be lost, so you should be sure that
763 763 your input buffer is empty before you call setecho(). For example, the
764 764 following will work as expected::
765 765
766 766 p = pexpect.spawn('cat')
767 767 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
768 768 p.expect (['1234'])
769 769 p.expect (['1234'])
770 770 p.setecho(False) # Turn off tty echo
771 771 p.sendline ('abcd') # We will set this only once (echoed by cat).
772 772 p.sendline ('wxyz') # We will set this only once (echoed by cat)
773 773 p.expect (['abcd'])
774 774 p.expect (['wxyz'])
775 775
776 776 The following WILL NOT WORK because the lines sent before the setecho
777 777 will be lost::
778 778
779 779 p = pexpect.spawn('cat')
780 780 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
781 781 p.setecho(False) # Turn off tty echo
782 782 p.sendline ('abcd') # We will set this only once (echoed by cat).
783 783 p.sendline ('wxyz') # We will set this only once (echoed by cat)
784 784 p.expect (['1234'])
785 785 p.expect (['1234'])
786 786 p.expect (['abcd'])
787 787 p.expect (['wxyz'])
788 788 """
789 789
790 790 self.child_fd
791 791 attr = termios.tcgetattr(self.child_fd)
792 792 if state:
793 793 attr[3] = attr[3] | termios.ECHO
794 794 else:
795 795 attr[3] = attr[3] & ~termios.ECHO
796 796 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
797 797 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
798 798 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
799 799
800 800 def read_nonblocking (self, size = 1, timeout = -1):
801 801
802 802 """This reads at most size bytes from the child application. It
803 803 includes a timeout. If the read does not complete within the timeout
804 804 period then a TIMEOUT exception is raised. If the end of file is read
805 805 then an EOF exception will be raised. If a log file was set using
806 806 setlog() then all data will also be written to the log file.
807 807
808 808 If timeout is None then the read may block indefinitely. If timeout is -1
809 809 then the self.timeout value is used. If timeout is 0 then the child is
810 810 polled and if there was no data immediately ready then this will raise
811 811 a TIMEOUT exception.
812 812
813 813 The timeout refers only to the amount of time to read at least one
814 814 character. This is not effected by the 'size' parameter, so if you call
815 815 read_nonblocking(size=100, timeout=30) and only one character is
816 816 available right away then one character will be returned immediately.
817 817 It will not wait for 30 seconds for another 99 characters to come in.
818 818
819 819 This is a wrapper around os.read(). It uses select.select() to
820 820 implement the timeout. """
821 821
822 822 if self.closed:
823 823 raise ValueError ('I/O operation on closed file in read_nonblocking().')
824 824
825 825 if timeout == -1:
826 826 timeout = self.timeout
827 827
828 828 # Note that some systems such as Solaris do not give an EOF when
829 829 # the child dies. In fact, you can still try to read
830 830 # from the child_fd -- it will block forever or until TIMEOUT.
831 831 # For this case, I test isalive() before doing any reading.
832 832 # If isalive() is false, then I pretend that this is the same as EOF.
833 833 if not self.isalive():
834 834 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
835 835 if not r:
836 836 self.flag_eof = True
837 837 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
838 838 elif self.__irix_hack:
839 839 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
840 840 # This adds a 2 second delay, but only when the child is terminated.
841 841 r, w, e = self.__select([self.child_fd], [], [], 2)
842 842 if not r and not self.isalive():
843 843 self.flag_eof = True
844 844 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
845 845
846 846 r,w,e = self.__select([self.child_fd], [], [], timeout)
847 847
848 848 if not r:
849 849 if not self.isalive():
850 850 # Some platforms, such as Irix, will claim that their processes are alive;
851 851 # then timeout on the select; and then finally admit that they are not alive.
852 852 self.flag_eof = True
853 853 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
854 854 else:
855 855 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
856 856
857 857 if self.child_fd in r:
858 858 try:
859 859 s = os.read(self.child_fd, size)
860 860 except OSError as e: # Linux does this
861 861 self.flag_eof = True
862 862 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
863 863 if s == b'': # BSD style
864 864 self.flag_eof = True
865 865 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
866 866
867 867 s2 = self._cast_buffer_type(s)
868 868 if self.logfile is not None:
869 869 self.logfile.write(s2)
870 870 self.logfile.flush()
871 871 if self.logfile_read is not None:
872 872 self.logfile_read.write(s2)
873 873 self.logfile_read.flush()
874 874
875 875 return s
876 876
877 877 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
878 878
879 879 def read (self, size = -1): # File-like object.
880 880 """This reads at most "size" bytes from the file (less if the read hits
881 881 EOF before obtaining size bytes). If the size argument is negative or
882 882 omitted, read all data until EOF is reached. The bytes are returned as
883 883 a string object. An empty string is returned when EOF is encountered
884 884 immediately. """
885 885
886 886 if size == 0:
887 887 return self._empty_buffer
888 888 if size < 0:
889 889 self.expect (self.delimiter) # delimiter default is EOF
890 890 return self.before
891 891
892 892 # I could have done this more directly by not using expect(), but
893 893 # I deliberately decided to couple read() to expect() so that
894 894 # I would catch any bugs early and ensure consistant behavior.
895 895 # It's a little less efficient, but there is less for me to
896 896 # worry about if I have to later modify read() or expect().
897 897 # Note, it's OK if size==-1 in the regex. That just means it
898 898 # will never match anything in which case we stop only on EOF.
899 899 if self._buffer_type is bytes:
900 900 pat = (u'.{%d}' % size).encode('ascii')
901 901 else:
902 902 pat = u'.{%d}' % size
903 903 cre = re.compile(pat, re.DOTALL)
904 904 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
905 905 if index == 0:
906 906 return self.after ### self.before should be ''. Should I assert this?
907 907 return self.before
908 908
909 909 def readline(self, size = -1):
910 910 """This reads and returns one entire line. A trailing newline is kept
911 911 in the string, but may be absent when a file ends with an incomplete
912 912 line. Note: This readline() looks for a \\r\\n pair even on UNIX
913 913 because this is what the pseudo tty device returns. So contrary to what
914 914 you may expect you will receive the newline as \\r\\n. An empty string
915 915 is returned when EOF is hit immediately. Currently, the size argument is
916 916 mostly ignored, so this behavior is not standard for a file-like
917 917 object. If size is 0 then an empty string is returned. """
918 918
919 919 if size == 0:
920 920 return self._empty_buffer
921 921 index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF
922 922 if index == 0:
923 923 return self.before + self._pty_newline
924 924 return self.before
925 925
926 926 def __iter__ (self): # File-like object.
927 927
928 928 """This is to support iterators over a file-like object.
929 929 """
930 930
931 931 return self
932 932
933 933 def next (self): # File-like object.
934 934
935 935 """This is to support iterators over a file-like object.
936 936 """
937 937
938 938 result = self.readline()
939 939 if result == self._empty_buffer:
940 940 raise StopIteration
941 941 return result
942 942
943 943 def readlines (self, sizehint = -1): # File-like object.
944 944
945 945 """This reads until EOF using readline() and returns a list containing
946 946 the lines thus read. The optional "sizehint" argument is ignored. """
947 947
948 948 lines = []
949 949 while True:
950 950 line = self.readline()
951 951 if not line:
952 952 break
953 953 lines.append(line)
954 954 return lines
955 955
956 956 def write(self, s): # File-like object.
957 957
958 958 """This is similar to send() except that there is no return value.
959 959 """
960 960
961 961 self.send (s)
962 962
963 963 def writelines (self, sequence): # File-like object.
964 964
965 965 """This calls write() for each element in the sequence. The sequence
966 966 can be any iterable object producing strings, typically a list of
967 967 strings. This does not add line separators There is no return value.
968 968 """
969 969
970 970 for s in sequence:
971 971 self.write (s)
972 972
973 973 def send(self, s):
974 974
975 975 """This sends a string to the child process. This returns the number of
976 976 bytes written. If a log file was set then the data is also written to
977 977 the log. """
978 978
979 979 time.sleep(self.delaybeforesend)
980 980
981 981 s2 = self._cast_buffer_type(s)
982 982 if self.logfile is not None:
983 983 self.logfile.write(s2)
984 984 self.logfile.flush()
985 985 if self.logfile_send is not None:
986 986 self.logfile_send.write(s2)
987 987 self.logfile_send.flush()
988 988 c = os.write (self.child_fd, _cast_bytes(s, self.encoding))
989 989 return c
990 990
991 991 def sendline(self, s=''):
992 992
993 993 """This is like send(), but it adds a line feed (os.linesep). This
994 994 returns the number of bytes written. """
995 995
996 996 n = self.send (s)
997 997 n = n + self.send (os.linesep)
998 998 return n
999 999
1000 1000 def sendcontrol(self, char):
1001 1001
1002 1002 """This sends a control character to the child such as Ctrl-C or
1003 1003 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
1004 1004
1005 1005 child.sendcontrol('g')
1006 1006
1007 1007 See also, sendintr() and sendeof().
1008 1008 """
1009 1009
1010 1010 char = char.lower()
1011 1011 a = ord(char)
1012 1012 if a>=97 and a<=122:
1013 1013 a = a - ord('a') + 1
1014 1014 return self.send (chr(a))
1015 1015 d = {'@':0, '`':0,
1016 1016 '[':27, '{':27,
1017 1017 '\\':28, '|':28,
1018 1018 ']':29, '}': 29,
1019 1019 '^':30, '~':30,
1020 1020 '_':31,
1021 1021 '?':127}
1022 1022 if char not in d:
1023 1023 return 0
1024 1024 return self.send (chr(d[char]))
1025 1025
1026 1026 def sendeof(self):
1027 1027
1028 1028 """This sends an EOF to the child. This sends a character which causes
1029 1029 the pending parent output buffer to be sent to the waiting child
1030 1030 program without waiting for end-of-line. If it is the first character
1031 1031 of the line, the read() in the user program returns 0, which signifies
1032 1032 end-of-file. This means to work as expected a sendeof() has to be
1033 1033 called at the beginning of a line. This method does not send a newline.
1034 1034 It is the responsibility of the caller to ensure the eof is sent at the
1035 1035 beginning of a line. """
1036 1036
1037 1037 ### Hmmm... how do I send an EOF?
1038 1038 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1039 1039 ###C return (errno == EWOULDBLOCK) ? n : -1;
1040 1040 #fd = sys.stdin.fileno()
1041 1041 #old = termios.tcgetattr(fd) # remember current state
1042 1042 #attr = termios.tcgetattr(fd)
1043 1043 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1044 1044 #try: # use try/finally to ensure state gets restored
1045 1045 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1046 1046 # if hasattr(termios, 'CEOF'):
1047 1047 # os.write (self.child_fd, '%c' % termios.CEOF)
1048 1048 # else:
1049 1049 # # Silly platform does not define CEOF so assume CTRL-D
1050 1050 # os.write (self.child_fd, '%c' % 4)
1051 1051 #finally: # restore state
1052 1052 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1053 1053 if hasattr(termios, 'VEOF'):
1054 1054 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1055 1055 else:
1056 1056 # platform does not define VEOF so assume CTRL-D
1057 1057 char = chr(4)
1058 1058 self.send(char)
1059 1059
1060 1060 def sendintr(self):
1061 1061
1062 1062 """This sends a SIGINT to the child. It does not require
1063 1063 the SIGINT to be the first character on a line. """
1064 1064
1065 1065 if hasattr(termios, 'VINTR'):
1066 1066 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1067 1067 else:
1068 1068 # platform does not define VINTR so assume CTRL-C
1069 1069 char = chr(3)
1070 1070 self.send (char)
1071 1071
1072 1072 def eof (self):
1073 1073
1074 1074 """This returns True if the EOF exception was ever raised.
1075 1075 """
1076 1076
1077 1077 return self.flag_eof
1078 1078
1079 1079 def terminate(self, force=False):
1080 1080
1081 1081 """This forces a child process to terminate. It starts nicely with
1082 1082 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1083 1083 returns True if the child was terminated. This returns False if the
1084 1084 child could not be terminated. """
1085 1085
1086 1086 if not self.isalive():
1087 1087 return True
1088 1088 try:
1089 1089 self.kill(signal.SIGHUP)
1090 1090 time.sleep(self.delayafterterminate)
1091 1091 if not self.isalive():
1092 1092 return True
1093 1093 self.kill(signal.SIGCONT)
1094 1094 time.sleep(self.delayafterterminate)
1095 1095 if not self.isalive():
1096 1096 return True
1097 1097 self.kill(signal.SIGINT)
1098 1098 time.sleep(self.delayafterterminate)
1099 1099 if not self.isalive():
1100 1100 return True
1101 1101 if force:
1102 1102 self.kill(signal.SIGKILL)
1103 1103 time.sleep(self.delayafterterminate)
1104 1104 if not self.isalive():
1105 1105 return True
1106 1106 else:
1107 1107 return False
1108 1108 return False
1109 1109 except OSError as e:
1110 1110 # I think there are kernel timing issues that sometimes cause
1111 1111 # this to happen. I think isalive() reports True, but the
1112 1112 # process is dead to the kernel.
1113 1113 # Make one last attempt to see if the kernel is up to date.
1114 1114 time.sleep(self.delayafterterminate)
1115 1115 if not self.isalive():
1116 1116 return True
1117 1117 else:
1118 1118 return False
1119 1119
1120 1120 def wait(self):
1121 1121
1122 1122 """This waits until the child exits. This is a blocking call. This will
1123 1123 not read any data from the child, so this will block forever if the
1124 1124 child has unread output and has terminated. In other words, the child
1125 1125 may have printed output then called exit(); but, technically, the child
1126 1126 is still alive until its output is read. """
1127 1127
1128 1128 if self.isalive():
1129 1129 pid, status = os.waitpid(self.pid, 0)
1130 1130 else:
1131 1131 raise ExceptionPexpect ('Cannot wait for dead child process.')
1132 1132 self.exitstatus = os.WEXITSTATUS(status)
1133 1133 if os.WIFEXITED (status):
1134 1134 self.status = status
1135 1135 self.exitstatus = os.WEXITSTATUS(status)
1136 1136 self.signalstatus = None
1137 1137 self.terminated = True
1138 1138 elif os.WIFSIGNALED (status):
1139 1139 self.status = status
1140 1140 self.exitstatus = None
1141 1141 self.signalstatus = os.WTERMSIG(status)
1142 1142 self.terminated = True
1143 1143 elif os.WIFSTOPPED (status):
1144 1144 raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?')
1145 1145 return self.exitstatus
1146 1146
1147 1147 def isalive(self):
1148 1148
1149 1149 """This tests if the child process is running or not. This is
1150 1150 non-blocking. If the child was terminated then this will read the
1151 1151 exitstatus or signalstatus of the child. This returns True if the child
1152 1152 process appears to be running or False if not. It can take literally
1153 1153 SECONDS for Solaris to return the right status. """
1154 1154
1155 1155 if self.terminated:
1156 1156 return False
1157 1157
1158 1158 if self.flag_eof:
1159 1159 # This is for Linux, which requires the blocking form of waitpid to get
1160 1160 # status of a defunct process. This is super-lame. The flag_eof would have
1161 1161 # been set in read_nonblocking(), so this should be safe.
1162 1162 waitpid_options = 0
1163 1163 else:
1164 1164 waitpid_options = os.WNOHANG
1165 1165
1166 1166 try:
1167 1167 pid, status = os.waitpid(self.pid, waitpid_options)
1168 1168 except OSError as e: # No child processes
1169 1169 if e.errno == errno.ECHILD:
1170 1170 raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
1171 1171 else:
1172 1172 raise e
1173 1173
1174 1174 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1175 1175 # If waitpid() returns 0 it means that no child process wishes to
1176 1176 # report, and the value of status is undefined.
1177 1177 if pid == 0:
1178 1178 try:
1179 1179 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1180 1180 except OSError as e: # This should never happen...
1181 1181 if e[0] == errno.ECHILD:
1182 1182 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1183 1183 else:
1184 1184 raise e
1185 1185
1186 1186 # If pid is still 0 after two calls to waitpid() then
1187 1187 # the process really is alive. This seems to work on all platforms, except
1188 1188 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1189 1189 # take care of this situation (unfortunately, this requires waiting through the timeout).
1190 1190 if pid == 0:
1191 1191 return True
1192 1192
1193 1193 if pid == 0:
1194 1194 return True
1195 1195
1196 1196 if os.WIFEXITED (status):
1197 1197 self.status = status
1198 1198 self.exitstatus = os.WEXITSTATUS(status)
1199 1199 self.signalstatus = None
1200 1200 self.terminated = True
1201 1201 elif os.WIFSIGNALED (status):
1202 1202 self.status = status
1203 1203 self.exitstatus = None
1204 1204 self.signalstatus = os.WTERMSIG(status)
1205 1205 self.terminated = True
1206 1206 elif os.WIFSTOPPED (status):
1207 1207 raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?')
1208 1208 return False
1209 1209
1210 1210 def kill(self, sig):
1211 1211
1212 1212 """This sends the given signal to the child application. In keeping
1213 1213 with UNIX tradition it has a misleading name. It does not necessarily
1214 1214 kill the child unless you send the right signal. """
1215 1215
1216 1216 # Same as os.kill, but the pid is given for you.
1217 1217 if self.isalive():
1218 1218 os.kill(self.pid, sig)
1219 1219
1220 1220 def compile_pattern_list(self, patterns):
1221 1221
1222 1222 """This compiles a pattern-string or a list of pattern-strings.
1223 1223 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1224 1224 those. Patterns may also be None which results in an empty list (you
1225 1225 might do this if waiting for an EOF or TIMEOUT condition without
1226 1226 expecting any pattern).
1227 1227
1228 1228 This is used by expect() when calling expect_list(). Thus expect() is
1229 1229 nothing more than::
1230 1230
1231 1231 cpl = self.compile_pattern_list(pl)
1232 1232 return self.expect_list(cpl, timeout)
1233 1233
1234 1234 If you are using expect() within a loop it may be more
1235 1235 efficient to compile the patterns first and then call expect_list().
1236 1236 This avoid calls in a loop to compile_pattern_list()::
1237 1237
1238 1238 cpl = self.compile_pattern_list(my_pattern)
1239 1239 while some_condition:
1240 1240 ...
1241 1241 i = self.expect_list(clp, timeout)
1242 1242 ...
1243 1243 """
1244 1244
1245 1245 if patterns is None:
1246 1246 return []
1247 1247 if not isinstance(patterns, list):
1248 1248 patterns = [patterns]
1249 1249
1250 1250 compile_flags = re.DOTALL # Allow dot to match \n
1251 1251 if self.ignorecase:
1252 1252 compile_flags = compile_flags | re.IGNORECASE
1253 1253 compiled_pattern_list = []
1254 1254 for p in patterns:
1255 1255 if isinstance(p, (bytes, unicode)):
1256 1256 p = self._cast_buffer_type(p)
1257 1257 compiled_pattern_list.append(re.compile(p, compile_flags))
1258 1258 elif p is EOF:
1259 1259 compiled_pattern_list.append(EOF)
1260 1260 elif p is TIMEOUT:
1261 1261 compiled_pattern_list.append(TIMEOUT)
1262 1262 elif type(p) is re_type:
1263 1263 p = self._prepare_regex_pattern(p)
1264 1264 compiled_pattern_list.append(p)
1265 1265 else:
1266 1266 raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
1267 1267
1268 1268 return compiled_pattern_list
1269 1269
1270 1270 def _prepare_regex_pattern(self, p):
1271 1271 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1272 1272 if isinstance(p.pattern, unicode):
1273 1273 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1274 1274 return p
1275 1275
1276 1276 def expect(self, pattern, timeout = -1, searchwindowsize=-1):
1277 1277
1278 1278 """This seeks through the stream until a pattern is matched. The
1279 1279 pattern is overloaded and may take several types. The pattern can be a
1280 1280 StringType, EOF, a compiled re, or a list of any of those types.
1281 1281 Strings will be compiled to re types. This returns the index into the
1282 1282 pattern list. If the pattern was not a list this returns index 0 on a
1283 1283 successful match. This may raise exceptions for EOF or TIMEOUT. To
1284 1284 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1285 1285 list. That will cause expect to match an EOF or TIMEOUT condition
1286 1286 instead of raising an exception.
1287 1287
1288 1288 If you pass a list of patterns and more than one matches, the first match
1289 1289 in the stream is chosen. If more than one pattern matches at that point,
1290 1290 the leftmost in the pattern list is chosen. For example::
1291 1291
1292 1292 # the input is 'foobar'
1293 1293 index = p.expect (['bar', 'foo', 'foobar'])
1294 1294 # returns 1 ('foo') even though 'foobar' is a "better" match
1295 1295
1296 1296 Please note, however, that buffering can affect this behavior, since
1297 1297 input arrives in unpredictable chunks. For example::
1298 1298
1299 1299 # the input is 'foobar'
1300 1300 index = p.expect (['foobar', 'foo'])
1301 1301 # returns 0 ('foobar') if all input is available at once,
1302 1302 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1303 1303
1304 1304 After a match is found the instance attributes 'before', 'after' and
1305 1305 'match' will be set. You can see all the data read before the match in
1306 1306 'before'. You can see the data that was matched in 'after'. The
1307 1307 re.MatchObject used in the re match will be in 'match'. If an error
1308 1308 occurred then 'before' will be set to all the data read so far and
1309 1309 'after' and 'match' will be None.
1310 1310
1311 1311 If timeout is -1 then timeout will be set to the self.timeout value.
1312 1312
1313 1313 A list entry may be EOF or TIMEOUT instead of a string. This will
1314 1314 catch these exceptions and return the index of the list entry instead
1315 1315 of raising the exception. The attribute 'after' will be set to the
1316 1316 exception type. The attribute 'match' will be None. This allows you to
1317 1317 write code like this::
1318 1318
1319 1319 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1320 1320 if index == 0:
1321 1321 do_something()
1322 1322 elif index == 1:
1323 1323 do_something_else()
1324 1324 elif index == 2:
1325 1325 do_some_other_thing()
1326 1326 elif index == 3:
1327 1327 do_something_completely_different()
1328 1328
1329 1329 instead of code like this::
1330 1330
1331 1331 try:
1332 1332 index = p.expect (['good', 'bad'])
1333 1333 if index == 0:
1334 1334 do_something()
1335 1335 elif index == 1:
1336 1336 do_something_else()
1337 1337 except EOF:
1338 1338 do_some_other_thing()
1339 1339 except TIMEOUT:
1340 1340 do_something_completely_different()
1341 1341
1342 1342 These two forms are equivalent. It all depends on what you want. You
1343 1343 can also just expect the EOF if you are waiting for all output of a
1344 1344 child to finish. For example::
1345 1345
1346 1346 p = pexpect.spawn('/bin/ls')
1347 1347 p.expect (pexpect.EOF)
1348 1348 print p.before
1349 1349
1350 1350 If you are trying to optimize for speed then see expect_list().
1351 1351 """
1352 1352
1353 1353 compiled_pattern_list = self.compile_pattern_list(pattern)
1354 1354 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1355 1355
1356 1356 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1357 1357
1358 1358 """This takes a list of compiled regular expressions and returns the
1359 1359 index into the pattern_list that matched the child output. The list may
1360 1360 also contain EOF or TIMEOUT (which are not compiled regular
1361 1361 expressions). This method is similar to the expect() method except that
1362 1362 expect_list() does not recompile the pattern list on every call. This
1363 1363 may help if you are trying to optimize for speed, otherwise just use
1364 1364 the expect() method. This is called by expect(). If timeout==-1 then
1365 1365 the self.timeout value is used. If searchwindowsize==-1 then the
1366 1366 self.searchwindowsize value is used. """
1367 1367
1368 1368 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1369 1369
1370 1370 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1371 1371
1372 1372 """This is similar to expect(), but uses plain string matching instead
1373 1373 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1374 1374 may be a string; a list or other sequence of strings; or TIMEOUT and
1375 1375 EOF.
1376 1376
1377 1377 This call might be faster than expect() for two reasons: string
1378 1378 searching is faster than RE matching and it is possible to limit the
1379 1379 search to just the end of the input buffer.
1380 1380
1381 1381 This method is also useful when you don't want to have to worry about
1382 1382 escaping regular expression characters that you want to match."""
1383 1383
1384 1384 if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF):
1385 1385 pattern_list = [pattern_list]
1386 1386 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1387 1387
1388 1388 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1389 1389
1390 1390 """This is the common loop used inside expect. The 'searcher' should be
1391 1391 an instance of searcher_re or searcher_string, which describes how and what
1392 1392 to search for in the input.
1393 1393
1394 1394 See expect() for other arguments, return value and exceptions. """
1395 1395
1396 1396 self.searcher = searcher
1397 1397
1398 1398 if timeout == -1:
1399 1399 timeout = self.timeout
1400 1400 if timeout is not None:
1401 1401 end_time = time.time() + timeout
1402 1402 if searchwindowsize == -1:
1403 1403 searchwindowsize = self.searchwindowsize
1404 1404
1405 1405 try:
1406 1406 incoming = self.buffer
1407 1407 freshlen = len(incoming)
1408 1408 while True: # Keep reading until exception or return.
1409 1409 index = searcher.search(incoming, freshlen, searchwindowsize)
1410 1410 if index >= 0:
1411 1411 self.buffer = incoming[searcher.end : ]
1412 1412 self.before = incoming[ : searcher.start]
1413 1413 self.after = incoming[searcher.start : searcher.end]
1414 1414 self.match = searcher.match
1415 1415 self.match_index = index
1416 1416 return self.match_index
1417 1417 # No match at this point
1418 1418 if timeout is not None and timeout < 0:
1419 1419 raise TIMEOUT ('Timeout exceeded in expect_any().')
1420 1420 # Still have time left, so read more data
1421 1421 c = self.read_nonblocking (self.maxread, timeout)
1422 1422 freshlen = len(c)
1423 1423 time.sleep (0.0001)
1424 1424 incoming = incoming + c
1425 1425 if timeout is not None:
1426 1426 timeout = end_time - time.time()
1427 1427 except EOF as e:
1428 1428 self.buffer = self._empty_buffer
1429 1429 self.before = incoming
1430 1430 self.after = EOF
1431 1431 index = searcher.eof_index
1432 1432 if index >= 0:
1433 1433 self.match = EOF
1434 1434 self.match_index = index
1435 1435 return self.match_index
1436 1436 else:
1437 1437 self.match = None
1438 1438 self.match_index = None
1439 1439 raise EOF (str(e) + '\n' + str(self))
1440 1440 except TIMEOUT as e:
1441 1441 self.buffer = incoming
1442 1442 self.before = incoming
1443 1443 self.after = TIMEOUT
1444 1444 index = searcher.timeout_index
1445 1445 if index >= 0:
1446 1446 self.match = TIMEOUT
1447 1447 self.match_index = index
1448 1448 return self.match_index
1449 1449 else:
1450 1450 self.match = None
1451 1451 self.match_index = None
1452 1452 raise TIMEOUT (str(e) + '\n' + str(self))
1453 1453 except:
1454 1454 self.before = incoming
1455 1455 self.after = None
1456 1456 self.match = None
1457 1457 self.match_index = None
1458 1458 raise
1459 1459
1460 1460 def getwinsize(self):
1461 1461
1462 1462 """This returns the terminal window size of the child tty. The return
1463 1463 value is a tuple of (rows, cols). """
1464 1464
1465 1465 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1466 1466 s = struct.pack('HHHH', 0, 0, 0, 0)
1467 1467 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1468 1468 return struct.unpack('HHHH', x)[0:2]
1469 1469
1470 1470 def setwinsize(self, r, c):
1471 1471
1472 1472 """This sets the terminal window size of the child tty. This will cause
1473 1473 a SIGWINCH signal to be sent to the child. This does not change the
1474 1474 physical window size. It changes the size reported to TTY-aware
1475 1475 applications like vi or curses -- applications that respond to the
1476 1476 SIGWINCH signal. """
1477 1477
1478 1478 # Check for buggy platforms. Some Python versions on some platforms
1479 1479 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1480 1480 # termios.TIOCSWINSZ. It is not clear why this happens.
1481 1481 # These platforms don't seem to handle the signed int very well;
1482 1482 # yet other platforms like OpenBSD have a large negative value for
1483 1483 # TIOCSWINSZ and they don't have a truncate problem.
1484 1484 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1485 1485 # Note that this fix is a hack.
1486 1486 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1487 1487 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1488 1488 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1489 1489 # Note, assume ws_xpixel and ws_ypixel are zero.
1490 1490 s = struct.pack('HHHH', r, c, 0, 0)
1491 1491 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1492 1492
1493 1493 def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None):
1494 1494
1495 1495 """This gives control of the child process to the interactive user (the
1496 1496 human at the keyboard). Keystrokes are sent to the child process, and
1497 1497 the stdout and stderr output of the child process is printed. This
1498 1498 simply echos the child stdout and child stderr to the real stdout and
1499 1499 it echos the real stdin to the child stdin. When the user types the
1500 1500 escape_character this method will stop. The default for
1501 1501 escape_character is ^]. This should not be confused with ASCII 27 --
1502 1502 the ESC character. ASCII 29 was chosen for historical merit because
1503 1503 this is the character used by 'telnet' as the escape character. The
1504 1504 escape_character will not be sent to the child process.
1505 1505
1506 1506 You may pass in optional input and output filter functions. These
1507 1507 functions should take a string and return a string. The output_filter
1508 1508 will be passed all the output from the child process. The input_filter
1509 1509 will be passed all the keyboard input from the user. The input_filter
1510 1510 is run BEFORE the check for the escape_character.
1511 1511
1512 1512 Note that if you change the window size of the parent the SIGWINCH
1513 1513 signal will not be passed through to the child. If you want the child
1514 1514 window size to change when the parent's window size changes then do
1515 1515 something like the following example::
1516 1516
1517 1517 import pexpect, struct, fcntl, termios, signal, sys
1518 1518 def sigwinch_passthrough (sig, data):
1519 1519 s = struct.pack("HHHH", 0, 0, 0, 0)
1520 1520 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1521 1521 global p
1522 1522 p.setwinsize(a[0],a[1])
1523 1523 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1524 1524 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1525 1525 p.interact()
1526 1526 """
1527 1527
1528 1528 # Flush the buffer.
1529 1529 if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding))
1530 1530 else: self.stdout.write(self.buffer)
1531 1531 self.stdout.flush()
1532 1532 self.buffer = self._empty_buffer
1533 1533 mode = tty.tcgetattr(self.STDIN_FILENO)
1534 1534 tty.setraw(self.STDIN_FILENO)
1535 1535 try:
1536 1536 self.__interact_copy(escape_character, input_filter, output_filter)
1537 1537 finally:
1538 1538 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1539 1539
1540 1540 def __interact_writen(self, fd, data):
1541 1541
1542 1542 """This is used by the interact() method.
1543 1543 """
1544 1544
1545 1545 while data != b'' and self.isalive():
1546 1546 n = os.write(fd, data)
1547 1547 data = data[n:]
1548 1548
1549 1549 def __interact_read(self, fd):
1550 1550
1551 1551 """This is used by the interact() method.
1552 1552 """
1553 1553
1554 1554 return os.read(fd, 1000)
1555 1555
1556 1556 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1557 1557
1558 1558 """This is used by the interact() method.
1559 1559 """
1560 1560
1561 1561 while self.isalive():
1562 1562 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1563 1563 if self.child_fd in r:
1564 1564 data = self.__interact_read(self.child_fd)
1565 1565 if output_filter: data = output_filter(data)
1566 1566 if self.logfile is not None:
1567 1567 self.logfile.write (data)
1568 1568 self.logfile.flush()
1569 1569 os.write(self.STDOUT_FILENO, data)
1570 1570 if self.STDIN_FILENO in r:
1571 1571 data = self.__interact_read(self.STDIN_FILENO)
1572 1572 if input_filter: data = input_filter(data)
1573 1573 i = data.rfind(escape_character)
1574 1574 if i != -1:
1575 1575 data = data[:i]
1576 1576 self.__interact_writen(self.child_fd, data)
1577 1577 break
1578 1578 self.__interact_writen(self.child_fd, data)
1579 1579
1580 1580 def __select (self, iwtd, owtd, ewtd, timeout=None):
1581 1581
1582 1582 """This is a wrapper around select.select() that ignores signals. If
1583 1583 select.select raises a select.error exception and errno is an EINTR
1584 1584 error then it is ignored. Mainly this is used to ignore sigwinch
1585 1585 (terminal resize). """
1586 1586
1587 1587 # if select() is interrupted by a signal (errno==EINTR) then
1588 1588 # we loop back and enter the select() again.
1589 1589 if timeout is not None:
1590 1590 end_time = time.time() + timeout
1591 1591 while True:
1592 1592 try:
1593 1593 return select.select (iwtd, owtd, ewtd, timeout)
1594 1594 except select.error as e:
1595 1595 if e.args[0] == errno.EINTR:
1596 1596 # if we loop back we have to subtract the amount of time we already waited.
1597 1597 if timeout is not None:
1598 1598 timeout = end_time - time.time()
1599 1599 if timeout < 0:
1600 1600 return ([],[],[])
1601 1601 else: # something else caused the select.error, so this really is an exception
1602 1602 raise
1603 1603
1604 1604 class spawn(spawnb):
1605 1605 """This is the main class interface for Pexpect. Use this class to start
1606 1606 and control child applications."""
1607 1607
1608 1608 _buffer_type = unicode
1609 1609 def _cast_buffer_type(self, s):
1610 1610 return _cast_unicode(s, self.encoding)
1611 1611 _empty_buffer = u''
1612 1612 _pty_newline = u'\r\n'
1613 1613
1614 1614 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None,
1615 1615 logfile=None, cwd=None, env=None, encoding='utf-8'):
1616 1616 super(spawn, self).__init__(command, args, timeout=timeout, maxread=maxread,
1617 1617 searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env)
1618 1618 self.encoding = encoding
1619 1619
1620 1620 def _prepare_regex_pattern(self, p):
1621 1621 "Recompile bytes regexes as unicode regexes."
1622 1622 if isinstance(p.pattern, bytes):
1623 1623 p = re.compile(p.pattern.decode(self.encoding), p.flags)
1624 1624 return p
1625 1625
1626 1626 def read_nonblocking(self, size=1, timeout=-1):
1627 1627 return super(spawn, self).read_nonblocking(size=size, timeout=timeout)\
1628 1628 .decode(self.encoding)
1629 1629
1630 1630 read_nonblocking.__doc__ = spawnb.read_nonblocking.__doc__
1631 1631
1632 1632
1633 1633 ##############################################################################
1634 1634 # End of spawn class
1635 1635 ##############################################################################
1636 1636
1637 1637 class searcher_string (object):
1638 1638
1639 1639 """This is a plain string search helper for the spawn.expect_any() method.
1640 1640 This helper class is for speed. For more powerful regex patterns
1641 1641 see the helper class, searcher_re.
1642 1642
1643 1643 Attributes:
1644 1644
1645 1645 eof_index - index of EOF, or -1
1646 1646 timeout_index - index of TIMEOUT, or -1
1647 1647
1648 1648 After a successful match by the search() method the following attributes
1649 1649 are available:
1650 1650
1651 1651 start - index into the buffer, first byte of match
1652 1652 end - index into the buffer, first byte after match
1653 1653 match - the matching string itself
1654 1654
1655 1655 """
1656 1656
1657 1657 def __init__(self, strings):
1658 1658
1659 1659 """This creates an instance of searcher_string. This argument 'strings'
1660 1660 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1661 1661
1662 1662 self.eof_index = -1
1663 1663 self.timeout_index = -1
1664 1664 self._strings = []
1665 1665 for n, s in enumerate(strings):
1666 1666 if s is EOF:
1667 1667 self.eof_index = n
1668 1668 continue
1669 1669 if s is TIMEOUT:
1670 1670 self.timeout_index = n
1671 1671 continue
1672 1672 self._strings.append((n, s))
1673 1673
1674 1674 def __str__(self):
1675 1675
1676 1676 """This returns a human-readable string that represents the state of
1677 1677 the object."""
1678 1678
1679 1679 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1680 1680 ss.append((-1,'searcher_string:'))
1681 1681 if self.eof_index >= 0:
1682 1682 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1683 1683 if self.timeout_index >= 0:
1684 1684 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1685 1685 ss.sort()
1686 1686 return '\n'.join(a[1] for a in ss)
1687 1687
1688 1688 def search(self, buffer, freshlen, searchwindowsize=None):
1689 1689
1690 1690 """This searches 'buffer' for the first occurence of one of the search
1691 1691 strings. 'freshlen' must indicate the number of bytes at the end of
1692 1692 'buffer' which have not been searched before. It helps to avoid
1693 1693 searching the same, possibly big, buffer over and over again.
1694 1694
1695 1695 See class spawn for the 'searchwindowsize' argument.
1696 1696
1697 1697 If there is a match this returns the index of that string, and sets
1698 1698 'start', 'end' and 'match'. Otherwise, this returns -1. """
1699 1699
1700 1700 absurd_match = len(buffer)
1701 1701 first_match = absurd_match
1702 1702
1703 1703 # 'freshlen' helps a lot here. Further optimizations could
1704 1704 # possibly include:
1705 1705 #
1706 1706 # using something like the Boyer-Moore Fast String Searching
1707 1707 # Algorithm; pre-compiling the search through a list of
1708 1708 # strings into something that can scan the input once to
1709 1709 # search for all N strings; realize that if we search for
1710 1710 # ['bar', 'baz'] and the input is '...foo' we need not bother
1711 1711 # rescanning until we've read three more bytes.
1712 1712 #
1713 1713 # Sadly, I don't know enough about this interesting topic. /grahn
1714 1714
1715 1715 for index, s in self._strings:
1716 1716 if searchwindowsize is None:
1717 1717 # the match, if any, can only be in the fresh data,
1718 1718 # or at the very end of the old data
1719 1719 offset = -(freshlen+len(s))
1720 1720 else:
1721 1721 # better obey searchwindowsize
1722 1722 offset = -searchwindowsize
1723 1723 n = buffer.find(s, offset)
1724 1724 if n >= 0 and n < first_match:
1725 1725 first_match = n
1726 1726 best_index, best_match = index, s
1727 1727 if first_match == absurd_match:
1728 1728 return -1
1729 1729 self.match = best_match
1730 1730 self.start = first_match
1731 1731 self.end = self.start + len(self.match)
1732 1732 return best_index
1733 1733
1734 1734 class searcher_re (object):
1735 1735
1736 1736 """This is regular expression string search helper for the
1737 1737 spawn.expect_any() method. This helper class is for powerful
1738 1738 pattern matching. For speed, see the helper class, searcher_string.
1739 1739
1740 1740 Attributes:
1741 1741
1742 1742 eof_index - index of EOF, or -1
1743 1743 timeout_index - index of TIMEOUT, or -1
1744 1744
1745 1745 After a successful match by the search() method the following attributes
1746 1746 are available:
1747 1747
1748 1748 start - index into the buffer, first byte of match
1749 1749 end - index into the buffer, first byte after match
1750 1750 match - the re.match object returned by a succesful re.search
1751 1751
1752 1752 """
1753 1753
1754 1754 def __init__(self, patterns):
1755 1755
1756 1756 """This creates an instance that searches for 'patterns' Where
1757 1757 'patterns' may be a list or other sequence of compiled regular
1758 1758 expressions, or the EOF or TIMEOUT types."""
1759 1759
1760 1760 self.eof_index = -1
1761 1761 self.timeout_index = -1
1762 1762 self._searches = []
1763 1763 for n, s in enumerate(patterns):
1764 1764 if s is EOF:
1765 1765 self.eof_index = n
1766 1766 continue
1767 1767 if s is TIMEOUT:
1768 1768 self.timeout_index = n
1769 1769 continue
1770 1770 self._searches.append((n, s))
1771 1771
1772 1772 def __str__(self):
1773 1773
1774 1774 """This returns a human-readable string that represents the state of
1775 1775 the object."""
1776 1776
1777 1777 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1778 1778 ss.append((-1,'searcher_re:'))
1779 1779 if self.eof_index >= 0:
1780 1780 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1781 1781 if self.timeout_index >= 0:
1782 1782 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1783 1783 ss.sort()
1784 1784 return '\n'.join(a[1] for a in ss)
1785 1785
1786 1786 def search(self, buffer, freshlen, searchwindowsize=None):
1787 1787
1788 1788 """This searches 'buffer' for the first occurence of one of the regular
1789 1789 expressions. 'freshlen' must indicate the number of bytes at the end of
1790 1790 'buffer' which have not been searched before.
1791 1791
1792 1792 See class spawn for the 'searchwindowsize' argument.
1793 1793
1794 1794 If there is a match this returns the index of that string, and sets
1795 1795 'start', 'end' and 'match'. Otherwise, returns -1."""
1796 1796
1797 1797 absurd_match = len(buffer)
1798 1798 first_match = absurd_match
1799 1799 # 'freshlen' doesn't help here -- we cannot predict the
1800 1800 # length of a match, and the re module provides no help.
1801 1801 if searchwindowsize is None:
1802 1802 searchstart = 0
1803 1803 else:
1804 1804 searchstart = max(0, len(buffer)-searchwindowsize)
1805 1805 for index, s in self._searches:
1806 1806 match = s.search(buffer, searchstart)
1807 1807 if match is None:
1808 1808 continue
1809 1809 n = match.start()
1810 1810 if n < first_match:
1811 1811 first_match = n
1812 1812 the_match = match
1813 1813 best_index = index
1814 1814 if first_match == absurd_match:
1815 1815 return -1
1816 1816 self.start = first_match
1817 1817 self.match = the_match
1818 1818 self.end = self.match.end()
1819 1819 return best_index
1820 1820
1821 1821 def which (filename):
1822 1822
1823 1823 """This takes a given filename; tries to find it in the environment path;
1824 1824 then checks if it is executable. This returns the full path to the filename
1825 1825 if found and executable. Otherwise this returns None."""
1826 1826
1827 1827 # Special case where filename already contains a path.
1828 1828 if os.path.dirname(filename) != '':
1829 1829 if os.access (filename, os.X_OK):
1830 1830 return filename
1831 1831
1832 1832 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1833 1833 p = os.defpath
1834 1834 else:
1835 1835 p = os.environ['PATH']
1836 1836
1837 1837 pathlist = p.split(os.pathsep)
1838 1838
1839 1839 for path in pathlist:
1840 1840 f = os.path.join(path, filename)
1841 1841 if os.access(f, os.X_OK):
1842 1842 return f
1843 1843 return None
1844 1844
1845 1845 def split_command_line(command_line):
1846 1846
1847 1847 """This splits a command line into a list of arguments. It splits arguments
1848 1848 on spaces, but handles embedded quotes, doublequotes, and escaped
1849 1849 characters. It's impossible to do this with a regular expression, so I
1850 1850 wrote a little state machine to parse the command line. """
1851 1851
1852 1852 arg_list = []
1853 1853 arg = ''
1854 1854
1855 1855 # Constants to name the states we can be in.
1856 1856 state_basic = 0
1857 1857 state_esc = 1
1858 1858 state_singlequote = 2
1859 1859 state_doublequote = 3
1860 1860 state_whitespace = 4 # The state of consuming whitespace between commands.
1861 1861 state = state_basic
1862 1862
1863 1863 for c in command_line:
1864 1864 if state == state_basic or state == state_whitespace:
1865 1865 if c == '\\': # Escape the next character
1866 1866 state = state_esc
1867 1867 elif c == r"'": # Handle single quote
1868 1868 state = state_singlequote
1869 1869 elif c == r'"': # Handle double quote
1870 1870 state = state_doublequote
1871 1871 elif c.isspace():
1872 1872 # Add arg to arg_list if we aren't in the middle of whitespace.
1873 1873 if state == state_whitespace:
1874 1874 None # Do nothing.
1875 1875 else:
1876 1876 arg_list.append(arg)
1877 1877 arg = ''
1878 1878 state = state_whitespace
1879 1879 else:
1880 1880 arg = arg + c
1881 1881 state = state_basic
1882 1882 elif state == state_esc:
1883 1883 arg = arg + c
1884 1884 state = state_basic
1885 1885 elif state == state_singlequote:
1886 1886 if c == r"'":
1887 1887 state = state_basic
1888 1888 else:
1889 1889 arg = arg + c
1890 1890 elif state == state_doublequote:
1891 1891 if c == r'"':
1892 1892 state = state_basic
1893 1893 else:
1894 1894 arg = arg + c
1895 1895
1896 1896 if arg != '':
1897 1897 arg_list.append(arg)
1898 1898 return arg_list
1899 1899
1900 1900 # vi:set sr et ts=4 sw=4 ft=python :
@@ -1,727 +1,728 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Subclass of InteractiveShell for terminal based frontends."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 17
17 18 import bdb
18 19 import os
19 20 import re
20 21 import sys
21 22 import textwrap
22 23
23 24 # We need to use nested to support python 2.6, once we move to >=2.7, we can
24 25 # use the with keyword's new builtin support for nested managers
25 26 try:
26 27 from contextlib import nested
27 28 except:
28 29 from IPython.utils.nested_context import nested
29 30
30 31 from IPython.core.error import TryNext, UsageError
31 32 from IPython.core.usage import interactive_usage, default_banner
32 33 from IPython.core.inputsplitter import IPythonInputSplitter
33 34 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
34 35 from IPython.core.magic import Magics, magics_class, line_magic
35 36 from IPython.testing.skipdoctest import skip_doctest
36 37 from IPython.utils.encoding import get_stream_enc
37 38 from IPython.utils import py3compat
38 39 from IPython.utils.terminal import toggle_set_term_title, set_term_title
39 40 from IPython.utils.process import abbrev_cwd
40 41 from IPython.utils.warn import warn, error
41 42 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
42 43 from IPython.utils.traitlets import Integer, CBool, Unicode
43 44
44 45 #-----------------------------------------------------------------------------
45 46 # Utilities
46 47 #-----------------------------------------------------------------------------
47 48
48 49 def get_default_editor():
49 50 try:
50 51 ed = os.environ['EDITOR']
51 52 except KeyError:
52 53 if os.name == 'posix':
53 54 ed = 'vi' # the only one guaranteed to be there!
54 55 else:
55 56 ed = 'notepad' # same in Windows!
56 57 return ed
57 58
58 59
59 60 def get_pasted_lines(sentinel, l_input=py3compat.input):
60 61 """ Yield pasted lines until the user enters the given sentinel value.
61 62 """
62 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
63 % sentinel
63 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
64 % sentinel)
64 65 while True:
65 66 try:
66 67 l = l_input(':')
67 68 if l == sentinel:
68 69 return
69 70 else:
70 71 yield l
71 72 except EOFError:
72 print '<EOF>'
73 print('<EOF>')
73 74 return
74 75
75 76
76 77 #------------------------------------------------------------------------
77 78 # Terminal-specific magics
78 79 #------------------------------------------------------------------------
79 80
80 81 @magics_class
81 82 class TerminalMagics(Magics):
82 83 def __init__(self, shell):
83 84 super(TerminalMagics, self).__init__(shell)
84 85 self.input_splitter = IPythonInputSplitter(input_mode='line')
85 86
86 87 def cleanup_input(self, block):
87 88 """Apply all possible IPython cleanups to an input block.
88 89
89 90 This means:
90 91
91 92 - remove any global leading whitespace (dedent)
92 93 - remove any email quotes ('>') if they are present in *all* lines
93 94 - apply all static inputsplitter transforms and break into sub-blocks
94 95 - apply prefilter() to each sub-block that is a single line.
95 96
96 97 Parameters
97 98 ----------
98 99 block : str
99 100 A possibly multiline input string of code.
100 101
101 102 Returns
102 103 -------
103 104 transformed block : str
104 105 The input, with all transformations above applied.
105 106 """
106 107 # We have to effectively implement client-side the loop that is done by
107 108 # the terminal frontend, and furthermore do it on a block that can
108 109 # possibly contain multiple statments pasted in one go.
109 110
110 111 # First, run the input through the block splitting code. We should
111 112 # eventually make this a self-contained method in the inputsplitter.
112 113 isp = self.input_splitter
113 114 isp.reset()
114 115 b = textwrap.dedent(block)
115 116
116 117 # Remove email quotes first. These must be consistently applied to
117 118 # *all* lines to be removed
118 119 b = strip_email_quotes(b)
119 120
120 121 # Split the input into independent sub-blocks so we can later do
121 122 # prefiltering (which must be done *only* to single-line inputs)
122 123 blocks = []
123 124 last_block = []
124 125 for line in b.splitlines():
125 126 isp.push(line)
126 127 last_block.append(line)
127 128 if not isp.push_accepts_more():
128 129 blocks.append(isp.source_reset())
129 130 last_block = []
130 131 if last_block:
131 132 blocks.append('\n'.join(last_block))
132 133
133 134 # Now, apply prefiltering to any one-line block to match the behavior
134 135 # of the interactive terminal
135 136 final_blocks = []
136 137 for block in blocks:
137 138 lines = block.splitlines()
138 139 if len(lines) == 1:
139 140 final_blocks.append(self.shell.prefilter(lines[0]))
140 141 else:
141 142 final_blocks.append(block)
142 143
143 144 # We now have the final version of the input code as a list of blocks,
144 145 # with all inputsplitter transformations applied and single-line blocks
145 146 # run through prefilter. For further processing, turn into a single
146 147 # string as the rest of our apis use string inputs.
147 148 return '\n'.join(final_blocks)
148 149
149 150 def store_or_execute(self, block, name):
150 151 """ Execute a block, or store it in a variable, per the user's request.
151 152 """
152 153 b = self.cleanup_input(block)
153 154 if name:
154 155 # If storing it for further editing
155 156 self.shell.user_ns[name] = SList(b.splitlines())
156 print "Block assigned to '%s'" % name
157 print("Block assigned to '%s'" % name)
157 158 else:
158 159 self.shell.user_ns['pasted_block'] = b
159 160 self.shell.run_cell(b)
160 161
161 162 def rerun_pasted(self, name='pasted_block'):
162 163 """ Rerun a previously pasted command.
163 164 """
164 165 b = self.shell.user_ns.get(name)
165 166
166 167 # Sanity checks
167 168 if b is None:
168 169 raise UsageError('No previous pasted block available')
169 170 if not isinstance(b, basestring):
170 171 raise UsageError(
171 172 "Variable 'pasted_block' is not a string, can't execute")
172 173
173 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
174 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
174 175 self.shell.run_cell(b)
175 176
176 177 @line_magic
177 178 def autoindent(self, parameter_s = ''):
178 179 """Toggle autoindent on/off (if available)."""
179 180
180 181 self.shell.set_autoindent()
181 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
182 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
182 183
183 184 @skip_doctest
184 185 @line_magic
185 186 def cpaste(self, parameter_s=''):
186 187 """Paste & execute a pre-formatted code block from clipboard.
187 188
188 189 You must terminate the block with '--' (two minus-signs) or Ctrl-D
189 190 alone on the line. You can also provide your own sentinel with '%paste
190 191 -s %%' ('%%' is the new sentinel for this operation)
191 192
192 193 The block is dedented prior to execution to enable execution of method
193 194 definitions. '>' and '+' characters at the beginning of a line are
194 195 ignored, to allow pasting directly from e-mails, diff files and
195 196 doctests (the '...' continuation prompt is also stripped). The
196 197 executed block is also assigned to variable named 'pasted_block' for
197 198 later editing with '%edit pasted_block'.
198 199
199 200 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
200 201 This assigns the pasted block to variable 'foo' as string, without
201 202 dedenting or executing it (preceding >>> and + is still stripped)
202 203
203 204 '%cpaste -r' re-executes the block previously entered by cpaste.
204 205
205 206 Do not be alarmed by garbled output on Windows (it's a readline bug).
206 207 Just press enter and type -- (and press enter again) and the block
207 208 will be what was just pasted.
208 209
209 210 IPython statements (magics, shell escapes) are not supported (yet).
210 211
211 212 See also
212 213 --------
213 214 paste: automatically pull code from clipboard.
214 215
215 216 Examples
216 217 --------
217 218 ::
218 219
219 220 In [8]: %cpaste
220 221 Pasting code; enter '--' alone on the line to stop.
221 222 :>>> a = ["world!", "Hello"]
222 223 :>>> print " ".join(sorted(a))
223 224 :--
224 225 Hello world!
225 226 """
226 227 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
227 228 if 'r' in opts:
228 229 self.rerun_pasted()
229 230 return
230 231
231 232 sentinel = opts.get('s', '--')
232 233 block = '\n'.join(get_pasted_lines(sentinel))
233 234 self.store_or_execute(block, name)
234 235
235 236 @line_magic
236 237 def paste(self, parameter_s=''):
237 238 """Paste & execute a pre-formatted code block from clipboard.
238 239
239 240 The text is pulled directly from the clipboard without user
240 241 intervention and printed back on the screen before execution (unless
241 242 the -q flag is given to force quiet mode).
242 243
243 244 The block is dedented prior to execution to enable execution of method
244 245 definitions. '>' and '+' characters at the beginning of a line are
245 246 ignored, to allow pasting directly from e-mails, diff files and
246 247 doctests (the '...' continuation prompt is also stripped). The
247 248 executed block is also assigned to variable named 'pasted_block' for
248 249 later editing with '%edit pasted_block'.
249 250
250 251 You can also pass a variable name as an argument, e.g. '%paste foo'.
251 252 This assigns the pasted block to variable 'foo' as string, without
252 253 executing it (preceding >>> and + is still stripped).
253 254
254 255 Options
255 256 -------
256 257
257 258 -r: re-executes the block previously entered by cpaste.
258 259
259 260 -q: quiet mode: do not echo the pasted text back to the terminal.
260 261
261 262 IPython statements (magics, shell escapes) are not supported (yet).
262 263
263 264 See also
264 265 --------
265 266 cpaste: manually paste code into terminal until you mark its end.
266 267 """
267 268 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
268 269 if 'r' in opts:
269 270 self.rerun_pasted()
270 271 return
271 272 try:
272 273 block = self.shell.hooks.clipboard_get()
273 274 except TryNext as clipboard_exc:
274 275 message = getattr(clipboard_exc, 'args')
275 276 if message:
276 277 error(message[0])
277 278 else:
278 279 error('Could not get text from the clipboard.')
279 280 return
280 281
281 282 # By default, echo back to terminal unless quiet mode is requested
282 283 if 'q' not in opts:
283 284 write = self.shell.write
284 285 write(self.shell.pycolorize(block))
285 286 if not block.endswith('\n'):
286 287 write('\n')
287 288 write("## -- End pasted text --\n")
288 289
289 290 self.store_or_execute(block, name)
290 291
291 292 # Class-level: add a '%cls' magic only on Windows
292 293 if sys.platform == 'win32':
293 294 @line_magic
294 295 def cls(self, s):
295 296 """Clear screen.
296 297 """
297 298 os.system("cls")
298 299
299 300 #-----------------------------------------------------------------------------
300 301 # Main class
301 302 #-----------------------------------------------------------------------------
302 303
303 304 class TerminalInteractiveShell(InteractiveShell):
304 305
305 306 autoedit_syntax = CBool(False, config=True,
306 307 help="auto editing of files with syntax errors.")
307 308 banner = Unicode('')
308 309 banner1 = Unicode(default_banner, config=True,
309 310 help="""The part of the banner to be printed before the profile"""
310 311 )
311 312 banner2 = Unicode('', config=True,
312 313 help="""The part of the banner to be printed after the profile"""
313 314 )
314 315 confirm_exit = CBool(True, config=True,
315 316 help="""
316 317 Set to confirm when you try to exit IPython with an EOF (Control-D
317 318 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
318 319 you can force a direct exit without any confirmation.""",
319 320 )
320 321 # This display_banner only controls whether or not self.show_banner()
321 322 # is called when mainloop/interact are called. The default is False
322 323 # because for the terminal based application, the banner behavior
323 324 # is controlled by Global.display_banner, which IPythonApp looks at
324 325 # to determine if *it* should call show_banner() by hand or not.
325 326 display_banner = CBool(False) # This isn't configurable!
326 327 embedded = CBool(False)
327 328 embedded_active = CBool(False)
328 329 editor = Unicode(get_default_editor(), config=True,
329 330 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
330 331 )
331 332 pager = Unicode('less', config=True,
332 333 help="The shell program to be used for paging.")
333 334
334 335 screen_length = Integer(0, config=True,
335 336 help=
336 337 """Number of lines of your screen, used to control printing of very
337 338 long strings. Strings longer than this number of lines will be sent
338 339 through a pager instead of directly printed. The default value for
339 340 this is 0, which means IPython will auto-detect your screen size every
340 341 time it needs to print certain potentially long strings (this doesn't
341 342 change the behavior of the 'print' keyword, it's only triggered
342 343 internally). If for some reason this isn't working well (it needs
343 344 curses support), specify it yourself. Otherwise don't change the
344 345 default.""",
345 346 )
346 347 term_title = CBool(False, config=True,
347 348 help="Enable auto setting the terminal title."
348 349 )
349 350
350 351 # In the terminal, GUI control is done via PyOS_InputHook
351 352 from IPython.lib.inputhook import enable_gui
352 353 enable_gui = staticmethod(enable_gui)
353 354
354 355 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
355 356 user_ns=None, user_module=None, custom_exceptions=((),None),
356 357 usage=None, banner1=None, banner2=None, display_banner=None):
357 358
358 359 super(TerminalInteractiveShell, self).__init__(
359 360 config=config, profile_dir=profile_dir, user_ns=user_ns,
360 361 user_module=user_module, custom_exceptions=custom_exceptions
361 362 )
362 363 # use os.system instead of utils.process.system by default,
363 364 # because piped system doesn't make sense in the Terminal:
364 365 self.system = self.system_raw
365 366
366 367 self.init_term_title()
367 368 self.init_usage(usage)
368 369 self.init_banner(banner1, banner2, display_banner)
369 370
370 371 #-------------------------------------------------------------------------
371 372 # Things related to the terminal
372 373 #-------------------------------------------------------------------------
373 374
374 375 @property
375 376 def usable_screen_length(self):
376 377 if self.screen_length == 0:
377 378 return 0
378 379 else:
379 380 num_lines_bot = self.separate_in.count('\n')+1
380 381 return self.screen_length - num_lines_bot
381 382
382 383 def init_term_title(self):
383 384 # Enable or disable the terminal title.
384 385 if self.term_title:
385 386 toggle_set_term_title(True)
386 387 set_term_title('IPython: ' + abbrev_cwd())
387 388 else:
388 389 toggle_set_term_title(False)
389 390
390 391 #-------------------------------------------------------------------------
391 392 # Things related to aliases
392 393 #-------------------------------------------------------------------------
393 394
394 395 def init_alias(self):
395 396 # The parent class defines aliases that can be safely used with any
396 397 # frontend.
397 398 super(TerminalInteractiveShell, self).init_alias()
398 399
399 400 # Now define aliases that only make sense on the terminal, because they
400 401 # need direct access to the console in a way that we can't emulate in
401 402 # GUI or web frontend
402 403 if os.name == 'posix':
403 404 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
404 405 ('man', 'man')]
405 406 elif os.name == 'nt':
406 407 aliases = [('cls', 'cls')]
407 408
408 409
409 410 for name, cmd in aliases:
410 411 self.alias_manager.define_alias(name, cmd)
411 412
412 413 #-------------------------------------------------------------------------
413 414 # Things related to the banner and usage
414 415 #-------------------------------------------------------------------------
415 416
416 417 def _banner1_changed(self):
417 418 self.compute_banner()
418 419
419 420 def _banner2_changed(self):
420 421 self.compute_banner()
421 422
422 423 def _term_title_changed(self, name, new_value):
423 424 self.init_term_title()
424 425
425 426 def init_banner(self, banner1, banner2, display_banner):
426 427 if banner1 is not None:
427 428 self.banner1 = banner1
428 429 if banner2 is not None:
429 430 self.banner2 = banner2
430 431 if display_banner is not None:
431 432 self.display_banner = display_banner
432 433 self.compute_banner()
433 434
434 435 def show_banner(self, banner=None):
435 436 if banner is None:
436 437 banner = self.banner
437 438 self.write(banner)
438 439
439 440 def compute_banner(self):
440 441 self.banner = self.banner1
441 442 if self.profile and self.profile != 'default':
442 443 self.banner += '\nIPython profile: %s\n' % self.profile
443 444 if self.banner2:
444 445 self.banner += '\n' + self.banner2
445 446
446 447 def init_usage(self, usage=None):
447 448 if usage is None:
448 449 self.usage = interactive_usage
449 450 else:
450 451 self.usage = usage
451 452
452 453 #-------------------------------------------------------------------------
453 454 # Mainloop and code execution logic
454 455 #-------------------------------------------------------------------------
455 456
456 457 def mainloop(self, display_banner=None):
457 458 """Start the mainloop.
458 459
459 460 If an optional banner argument is given, it will override the
460 461 internally created default banner.
461 462 """
462 463
463 464 with nested(self.builtin_trap, self.display_trap):
464 465
465 466 while 1:
466 467 try:
467 468 self.interact(display_banner=display_banner)
468 469 #self.interact_with_readline()
469 470 # XXX for testing of a readline-decoupled repl loop, call
470 471 # interact_with_readline above
471 472 break
472 473 except KeyboardInterrupt:
473 474 # this should not be necessary, but KeyboardInterrupt
474 475 # handling seems rather unpredictable...
475 476 self.write("\nKeyboardInterrupt in interact()\n")
476 477
477 478 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
478 479 """Store multiple lines as a single entry in history"""
479 480
480 481 # do nothing without readline or disabled multiline
481 482 if not self.has_readline or not self.multiline_history:
482 483 return hlen_before_cell
483 484
484 485 # windows rl has no remove_history_item
485 486 if not hasattr(self.readline, "remove_history_item"):
486 487 return hlen_before_cell
487 488
488 489 # skip empty cells
489 490 if not source_raw.rstrip():
490 491 return hlen_before_cell
491 492
492 493 # nothing changed do nothing, e.g. when rl removes consecutive dups
493 494 hlen = self.readline.get_current_history_length()
494 495 if hlen == hlen_before_cell:
495 496 return hlen_before_cell
496 497
497 498 for i in range(hlen - hlen_before_cell):
498 499 self.readline.remove_history_item(hlen - i - 1)
499 500 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
500 501 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
501 502 stdin_encoding))
502 503 return self.readline.get_current_history_length()
503 504
504 505 def interact(self, display_banner=None):
505 506 """Closely emulate the interactive Python console."""
506 507
507 508 # batch run -> do not interact
508 509 if self.exit_now:
509 510 return
510 511
511 512 if display_banner is None:
512 513 display_banner = self.display_banner
513 514
514 515 if isinstance(display_banner, basestring):
515 516 self.show_banner(display_banner)
516 517 elif display_banner:
517 518 self.show_banner()
518 519
519 520 more = False
520 521
521 522 if self.has_readline:
522 523 self.readline_startup_hook(self.pre_readline)
523 524 hlen_b4_cell = self.readline.get_current_history_length()
524 525 else:
525 526 hlen_b4_cell = 0
526 527 # exit_now is set by a call to %Exit or %Quit, through the
527 528 # ask_exit callback.
528 529
529 530 while not self.exit_now:
530 531 self.hooks.pre_prompt_hook()
531 532 if more:
532 533 try:
533 534 prompt = self.prompt_manager.render('in2')
534 535 except:
535 536 self.showtraceback()
536 537 if self.autoindent:
537 538 self.rl_do_indent = True
538 539
539 540 else:
540 541 try:
541 542 prompt = self.separate_in + self.prompt_manager.render('in')
542 543 except:
543 544 self.showtraceback()
544 545 try:
545 546 line = self.raw_input(prompt)
546 547 if self.exit_now:
547 548 # quick exit on sys.std[in|out] close
548 549 break
549 550 if self.autoindent:
550 551 self.rl_do_indent = False
551 552
552 553 except KeyboardInterrupt:
553 554 #double-guard against keyboardinterrupts during kbdint handling
554 555 try:
555 556 self.write('\nKeyboardInterrupt\n')
556 557 source_raw = self.input_splitter.source_raw_reset()[1]
557 558 hlen_b4_cell = \
558 559 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
559 560 more = False
560 561 except KeyboardInterrupt:
561 562 pass
562 563 except EOFError:
563 564 if self.autoindent:
564 565 self.rl_do_indent = False
565 566 if self.has_readline:
566 567 self.readline_startup_hook(None)
567 568 self.write('\n')
568 569 self.exit()
569 570 except bdb.BdbQuit:
570 571 warn('The Python debugger has exited with a BdbQuit exception.\n'
571 572 'Because of how pdb handles the stack, it is impossible\n'
572 573 'for IPython to properly format this particular exception.\n'
573 574 'IPython will resume normal operation.')
574 575 except:
575 576 # exceptions here are VERY RARE, but they can be triggered
576 577 # asynchronously by signal handlers, for example.
577 578 self.showtraceback()
578 579 else:
579 580 self.input_splitter.push(line)
580 581 more = self.input_splitter.push_accepts_more()
581 582 if (self.SyntaxTB.last_syntax_error and
582 583 self.autoedit_syntax):
583 584 self.edit_syntax_error()
584 585 if not more:
585 586 source_raw = self.input_splitter.source_raw_reset()[1]
586 587 self.run_cell(source_raw, store_history=True)
587 588 hlen_b4_cell = \
588 589 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
589 590
590 591 # Turn off the exit flag, so the mainloop can be restarted if desired
591 592 self.exit_now = False
592 593
593 594 def raw_input(self, prompt=''):
594 595 """Write a prompt and read a line.
595 596
596 597 The returned line does not include the trailing newline.
597 598 When the user enters the EOF key sequence, EOFError is raised.
598 599
599 600 Optional inputs:
600 601
601 602 - prompt(''): a string to be printed to prompt the user.
602 603
603 604 - continue_prompt(False): whether this line is the first one or a
604 605 continuation in a sequence of inputs.
605 606 """
606 607 # Code run by the user may have modified the readline completer state.
607 608 # We must ensure that our completer is back in place.
608 609
609 610 if self.has_readline:
610 611 self.set_readline_completer()
611 612
612 613 # raw_input expects str, but we pass it unicode sometimes
613 614 prompt = py3compat.cast_bytes_py2(prompt)
614 615
615 616 try:
616 617 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
617 618 except ValueError:
618 619 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
619 620 " or sys.stdout.close()!\nExiting IPython!\n")
620 621 self.ask_exit()
621 622 return ""
622 623
623 624 # Try to be reasonably smart about not re-indenting pasted input more
624 625 # than necessary. We do this by trimming out the auto-indent initial
625 626 # spaces, if the user's actual input started itself with whitespace.
626 627 if self.autoindent:
627 628 if num_ini_spaces(line) > self.indent_current_nsp:
628 629 line = line[self.indent_current_nsp:]
629 630 self.indent_current_nsp = 0
630 631
631 632 return line
632 633
633 634 #-------------------------------------------------------------------------
634 635 # Methods to support auto-editing of SyntaxErrors.
635 636 #-------------------------------------------------------------------------
636 637
637 638 def edit_syntax_error(self):
638 639 """The bottom half of the syntax error handler called in the main loop.
639 640
640 641 Loop until syntax error is fixed or user cancels.
641 642 """
642 643
643 644 while self.SyntaxTB.last_syntax_error:
644 645 # copy and clear last_syntax_error
645 646 err = self.SyntaxTB.clear_err_state()
646 647 if not self._should_recompile(err):
647 648 return
648 649 try:
649 650 # may set last_syntax_error again if a SyntaxError is raised
650 651 self.safe_execfile(err.filename,self.user_ns)
651 652 except:
652 653 self.showtraceback()
653 654 else:
654 655 try:
655 656 f = open(err.filename)
656 657 try:
657 658 # This should be inside a display_trap block and I
658 659 # think it is.
659 660 sys.displayhook(f.read())
660 661 finally:
661 662 f.close()
662 663 except:
663 664 self.showtraceback()
664 665
665 666 def _should_recompile(self,e):
666 667 """Utility routine for edit_syntax_error"""
667 668
668 669 if e.filename in ('<ipython console>','<input>','<string>',
669 670 '<console>','<BackgroundJob compilation>',
670 671 None):
671 672
672 673 return False
673 674 try:
674 675 if (self.autoedit_syntax and
675 676 not self.ask_yes_no('Return to editor to correct syntax error? '
676 677 '[Y/n] ','y')):
677 678 return False
678 679 except EOFError:
679 680 return False
680 681
681 682 def int0(x):
682 683 try:
683 684 return int(x)
684 685 except TypeError:
685 686 return 0
686 687 # always pass integer line and offset values to editor hook
687 688 try:
688 689 self.hooks.fix_error_editor(e.filename,
689 690 int0(e.lineno),int0(e.offset),e.msg)
690 691 except TryNext:
691 692 warn('Could not open editor')
692 693 return False
693 694 return True
694 695
695 696 #-------------------------------------------------------------------------
696 697 # Things related to exiting
697 698 #-------------------------------------------------------------------------
698 699
699 700 def ask_exit(self):
700 701 """ Ask the shell to exit. Can be overiden and used as a callback. """
701 702 self.exit_now = True
702 703
703 704 def exit(self):
704 705 """Handle interactive exit.
705 706
706 707 This method calls the ask_exit callback."""
707 708 if self.confirm_exit:
708 709 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
709 710 self.ask_exit()
710 711 else:
711 712 self.ask_exit()
712 713
713 714 #-------------------------------------------------------------------------
714 715 # Things related to magics
715 716 #-------------------------------------------------------------------------
716 717
717 718 def init_magics(self):
718 719 super(TerminalInteractiveShell, self).init_magics()
719 720 self.register_magics(TerminalMagics)
720 721
721 722 def showindentationerror(self):
722 723 super(TerminalInteractiveShell, self).showindentationerror()
723 724 print("If you want to paste code into IPython, try the "
724 725 "%paste and %cpaste magic functions.")
725 726
726 727
727 728 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,484 +1,483 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Manage background (threaded) jobs conveniently from an interactive shell.
3 3
4 4 This module provides a BackgroundJobManager class. This is the main class
5 5 meant for public usage, it implements an object which can create and manage
6 6 new background jobs.
7 7
8 8 It also provides the actual job classes managed by these BackgroundJobManager
9 9 objects, see their docstrings below.
10 10
11 11
12 12 This system was inspired by discussions with B. Granger and the
13 13 BackgroundCommand class described in the book Python Scripting for
14 14 Computational Science, by H. P. Langtangen:
15 15
16 16 http://folk.uio.no/hpl/scripting
17 17
18 18 (although ultimately no code from this text was used, as IPython's system is a
19 19 separate implementation).
20 20
21 21 An example notebook is provided in our documentation illustrating interactive
22 22 use of the system.
23 23 """
24 24
25 25 #*****************************************************************************
26 26 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
27 27 #
28 28 # Distributed under the terms of the BSD License. The full license is in
29 29 # the file COPYING, distributed as part of this software.
30 30 #*****************************************************************************
31 31
32 32 # Code begins
33 33 import sys
34 34 import threading
35 35
36 36 from IPython.core.ultratb import AutoFormattedTB
37 37 from IPython.utils.warn import warn, error
38 38
39 39
40 40 class BackgroundJobManager(object):
41 41 """Class to manage a pool of backgrounded threaded jobs.
42 42
43 43 Below, we assume that 'jobs' is a BackgroundJobManager instance.
44 44
45 45 Usage summary (see the method docstrings for details):
46 46
47 47 jobs.new(...) -> start a new job
48 48
49 49 jobs() or jobs.status() -> print status summary of all jobs
50 50
51 51 jobs[N] -> returns job number N.
52 52
53 53 foo = jobs[N].result -> assign to variable foo the result of job N
54 54
55 55 jobs[N].traceback() -> print the traceback of dead job N
56 56
57 57 jobs.remove(N) -> remove (finished) job N
58 58
59 59 jobs.flush() -> remove all finished jobs
60 60
61 61 As a convenience feature, BackgroundJobManager instances provide the
62 62 utility result and traceback methods which retrieve the corresponding
63 63 information from the jobs list:
64 64
65 65 jobs.result(N) <--> jobs[N].result
66 66 jobs.traceback(N) <--> jobs[N].traceback()
67 67
68 68 While this appears minor, it allows you to use tab completion
69 69 interactively on the job manager instance.
70 70 """
71 71
72 72 def __init__(self):
73 73 # Lists for job management, accessed via a property to ensure they're
74 74 # up to date.x
75 75 self._running = []
76 76 self._completed = []
77 77 self._dead = []
78 78 # A dict of all jobs, so users can easily access any of them
79 79 self.all = {}
80 80 # For reporting
81 81 self._comp_report = []
82 82 self._dead_report = []
83 83 # Store status codes locally for fast lookups
84 84 self._s_created = BackgroundJobBase.stat_created_c
85 85 self._s_running = BackgroundJobBase.stat_running_c
86 86 self._s_completed = BackgroundJobBase.stat_completed_c
87 87 self._s_dead = BackgroundJobBase.stat_dead_c
88 88
89 89 @property
90 90 def running(self):
91 91 self._update_status()
92 92 return self._running
93 93
94 94 @property
95 95 def dead(self):
96 96 self._update_status()
97 97 return self._dead
98 98
99 99 @property
100 100 def completed(self):
101 101 self._update_status()
102 102 return self._completed
103 103
104 104 def new(self, func_or_exp, *args, **kwargs):
105 105 """Add a new background job and start it in a separate thread.
106 106
107 107 There are two types of jobs which can be created:
108 108
109 109 1. Jobs based on expressions which can be passed to an eval() call.
110 110 The expression must be given as a string. For example:
111 111
112 112 job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
113 113
114 114 The given expression is passed to eval(), along with the optional
115 115 global/local dicts provided. If no dicts are given, they are
116 116 extracted automatically from the caller's frame.
117 117
118 118 A Python statement is NOT a valid eval() expression. Basically, you
119 119 can only use as an eval() argument something which can go on the right
120 120 of an '=' sign and be assigned to a variable.
121 121
122 122 For example,"print 'hello'" is not valid, but '2+3' is.
123 123
124 124 2. Jobs given a function object, optionally passing additional
125 125 positional arguments:
126 126
127 127 job_manager.new(myfunc, x, y)
128 128
129 129 The function is called with the given arguments.
130 130
131 131 If you need to pass keyword arguments to your function, you must
132 132 supply them as a dict named kw:
133 133
134 134 job_manager.new(myfunc, x, y, kw=dict(z=1))
135 135
136 136 The reason for this assymmetry is that the new() method needs to
137 137 maintain access to its own keywords, and this prevents name collisions
138 138 between arguments to new() and arguments to your own functions.
139 139
140 140 In both cases, the result is stored in the job.result field of the
141 141 background job object.
142 142
143 143 You can set `daemon` attribute of the thread by giving the keyword
144 144 argument `daemon`.
145 145
146 146 Notes and caveats:
147 147
148 148 1. All threads running share the same standard output. Thus, if your
149 149 background jobs generate output, it will come out on top of whatever
150 150 you are currently writing. For this reason, background jobs are best
151 151 used with silent functions which simply return their output.
152 152
153 153 2. Threads also all work within the same global namespace, and this
154 154 system does not lock interactive variables. So if you send job to the
155 155 background which operates on a mutable object for a long time, and
156 156 start modifying that same mutable object interactively (or in another
157 157 backgrounded job), all sorts of bizarre behaviour will occur.
158 158
159 159 3. If a background job is spending a lot of time inside a C extension
160 160 module which does not release the Python Global Interpreter Lock
161 161 (GIL), this will block the IPython prompt. This is simply because the
162 162 Python interpreter can only switch between threads at Python
163 163 bytecodes. While the execution is inside C code, the interpreter must
164 164 simply wait unless the extension module releases the GIL.
165 165
166 166 4. There is no way, due to limitations in the Python threads library,
167 167 to kill a thread once it has started."""
168 168
169 169 if callable(func_or_exp):
170 170 kw = kwargs.get('kw',{})
171 171 job = BackgroundJobFunc(func_or_exp,*args,**kw)
172 172 elif isinstance(func_or_exp, basestring):
173 173 if not args:
174 174 frame = sys._getframe(1)
175 175 glob, loc = frame.f_globals, frame.f_locals
176 176 elif len(args)==1:
177 177 glob = loc = args[0]
178 178 elif len(args)==2:
179 179 glob,loc = args
180 180 else:
181 181 raise ValueError(
182 182 'Expression jobs take at most 2 args (globals,locals)')
183 183 job = BackgroundJobExpr(func_or_exp, glob, loc)
184 184 else:
185 185 raise TypeError('invalid args for new job')
186 186
187 187 if kwargs.get('daemon', False):
188 188 job.daemon = True
189 189 job.num = len(self.all)+1 if self.all else 0
190 190 self.running.append(job)
191 191 self.all[job.num] = job
192 192 print 'Starting job # %s in a separate thread.' % job.num
193 193 job.start()
194 194 return job
195 195
196 196 def __getitem__(self, job_key):
197 197 num = job_key if isinstance(job_key, int) else job_key.num
198 198 return self.all[num]
199 199
200 200 def __call__(self):
201 201 """An alias to self.status(),
202 202
203 203 This allows you to simply call a job manager instance much like the
204 204 Unix `jobs` shell command."""
205 205
206 206 return self.status()
207 207
208 208 def _update_status(self):
209 209 """Update the status of the job lists.
210 210
211 211 This method moves finished jobs to one of two lists:
212 212 - self.completed: jobs which completed successfully
213 213 - self.dead: jobs which finished but died.
214 214
215 215 It also copies those jobs to corresponding _report lists. These lists
216 216 are used to report jobs completed/dead since the last update, and are
217 217 then cleared by the reporting function after each call."""
218 218
219 219 # Status codes
220 220 srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
221 221 # State lists, use the actual lists b/c the public names are properties
222 222 # that call this very function on access
223 223 running, completed, dead = self._running, self._completed, self._dead
224 224
225 225 # Now, update all state lists
226 226 for num, job in enumerate(running):
227 227 stat = job.stat_code
228 228 if stat == srun:
229 229 continue
230 230 elif stat == scomp:
231 231 completed.append(job)
232 232 self._comp_report.append(job)
233 233 running[num] = False
234 234 elif stat == sdead:
235 235 dead.append(job)
236 236 self._dead_report.append(job)
237 237 running[num] = False
238 238 # Remove dead/completed jobs from running list
239 239 running[:] = filter(None, running)
240 240
241 241 def _group_report(self,group,name):
242 242 """Report summary for a given job group.
243 243
244 244 Return True if the group had any elements."""
245 245
246 246 if group:
247 247 print '%s jobs:' % name
248 248 for job in group:
249 249 print '%s : %s' % (job.num,job)
250 250 print
251 251 return True
252 252
253 253 def _group_flush(self,group,name):
254 254 """Flush a given job group
255 255
256 256 Return True if the group had any elements."""
257 257
258 258 njobs = len(group)
259 259 if njobs:
260 260 plural = {1:''}.setdefault(njobs,'s')
261 261 print 'Flushing %s %s job%s.' % (njobs,name,plural)
262 262 group[:] = []
263 263 return True
264 264
265 265 def _status_new(self):
266 266 """Print the status of newly finished jobs.
267 267
268 268 Return True if any new jobs are reported.
269 269
270 270 This call resets its own state every time, so it only reports jobs
271 271 which have finished since the last time it was called."""
272 272
273 273 self._update_status()
274 274 new_comp = self._group_report(self._comp_report, 'Completed')
275 275 new_dead = self._group_report(self._dead_report,
276 276 'Dead, call jobs.traceback() for details')
277 277 self._comp_report[:] = []
278 278 self._dead_report[:] = []
279 279 return new_comp or new_dead
280 280
281 281 def status(self,verbose=0):
282 282 """Print a status of all jobs currently being managed."""
283 283
284 284 self._update_status()
285 285 self._group_report(self.running,'Running')
286 286 self._group_report(self.completed,'Completed')
287 287 self._group_report(self.dead,'Dead')
288 288 # Also flush the report queues
289 289 self._comp_report[:] = []
290 290 self._dead_report[:] = []
291 291
292 292 def remove(self,num):
293 293 """Remove a finished (completed or dead) job."""
294 294
295 295 try:
296 296 job = self.all[num]
297 297 except KeyError:
298 298 error('Job #%s not found' % num)
299 299 else:
300 300 stat_code = job.stat_code
301 301 if stat_code == self._s_running:
302 302 error('Job #%s is still running, it can not be removed.' % num)
303 303 return
304 304 elif stat_code == self._s_completed:
305 305 self.completed.remove(job)
306 306 elif stat_code == self._s_dead:
307 307 self.dead.remove(job)
308 308
309 309 def flush(self):
310 310 """Flush all finished jobs (completed and dead) from lists.
311 311
312 312 Running jobs are never flushed.
313 313
314 314 It first calls _status_new(), to update info. If any jobs have
315 315 completed since the last _status_new() call, the flush operation
316 316 aborts."""
317 317
318 318 # Remove the finished jobs from the master dict
319 319 alljobs = self.all
320 320 for job in self.completed+self.dead:
321 321 del(alljobs[job.num])
322 322
323 323 # Now flush these lists completely
324 324 fl_comp = self._group_flush(self.completed, 'Completed')
325 325 fl_dead = self._group_flush(self.dead, 'Dead')
326 326 if not (fl_comp or fl_dead):
327 327 print 'No jobs to flush.'
328 328
329 329 def result(self,num):
330 330 """result(N) -> return the result of job N."""
331 331 try:
332 332 return self.all[num].result
333 333 except KeyError:
334 334 error('Job #%s not found' % num)
335 335
336 336 def _traceback(self, job):
337 337 num = job if isinstance(job, int) else job.num
338 338 try:
339 339 self.all[num].traceback()
340 340 except KeyError:
341 341 error('Job #%s not found' % num)
342 342
343 343 def traceback(self, job=None):
344 344 if job is None:
345 345 self._update_status()
346 346 for deadjob in self.dead:
347 347 print "Traceback for: %r" % deadjob
348 348 self._traceback(deadjob)
349 349 print
350 350 else:
351 351 self._traceback(job)
352 352
353 353
354 354 class BackgroundJobBase(threading.Thread):
355 355 """Base class to build BackgroundJob classes.
356 356
357 357 The derived classes must implement:
358 358
359 359 - Their own __init__, since the one here raises NotImplementedError. The
360 360 derived constructor must call self._init() at the end, to provide common
361 361 initialization.
362 362
363 363 - A strform attribute used in calls to __str__.
364 364
365 365 - A call() method, which will make the actual execution call and must
366 366 return a value to be held in the 'result' field of the job object."""
367 367
368 368 # Class constants for status, in string and as numerical codes (when
369 369 # updating jobs lists, we don't want to do string comparisons). This will
370 370 # be done at every user prompt, so it has to be as fast as possible
371 371 stat_created = 'Created'; stat_created_c = 0
372 372 stat_running = 'Running'; stat_running_c = 1
373 373 stat_completed = 'Completed'; stat_completed_c = 2
374 374 stat_dead = 'Dead (Exception), call jobs.traceback() for details'
375 375 stat_dead_c = -1
376 376
377 377 def __init__(self):
378 raise NotImplementedError, \
379 "This class can not be instantiated directly."
378 raise NotImplementedError("This class can not be instantiated directly.")
380 379
381 380 def _init(self):
382 381 """Common initialization for all BackgroundJob objects"""
383 382
384 383 for attr in ['call','strform']:
385 384 assert hasattr(self,attr), "Missing attribute <%s>" % attr
386 385
387 386 # The num tag can be set by an external job manager
388 387 self.num = None
389 388
390 389 self.status = BackgroundJobBase.stat_created
391 390 self.stat_code = BackgroundJobBase.stat_created_c
392 391 self.finished = False
393 392 self.result = '<BackgroundJob has not completed>'
394 393
395 394 # reuse the ipython traceback handler if we can get to it, otherwise
396 395 # make a new one
397 396 try:
398 397 make_tb = get_ipython().InteractiveTB.text
399 398 except:
400 399 make_tb = AutoFormattedTB(mode = 'Context',
401 400 color_scheme='NoColor',
402 401 tb_offset = 1).text
403 402 # Note that the actual API for text() requires the three args to be
404 403 # passed in, so we wrap it in a simple lambda.
405 404 self._make_tb = lambda : make_tb(None, None, None)
406 405
407 406 # Hold a formatted traceback if one is generated.
408 407 self._tb = None
409 408
410 409 threading.Thread.__init__(self)
411 410
412 411 def __str__(self):
413 412 return self.strform
414 413
415 414 def __repr__(self):
416 415 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
417 416
418 417 def traceback(self):
419 418 print self._tb
420 419
421 420 def run(self):
422 421 try:
423 422 self.status = BackgroundJobBase.stat_running
424 423 self.stat_code = BackgroundJobBase.stat_running_c
425 424 self.result = self.call()
426 425 except:
427 426 self.status = BackgroundJobBase.stat_dead
428 427 self.stat_code = BackgroundJobBase.stat_dead_c
429 428 self.finished = None
430 429 self.result = ('<BackgroundJob died, call jobs.traceback() for details>')
431 430 self._tb = self._make_tb()
432 431 else:
433 432 self.status = BackgroundJobBase.stat_completed
434 433 self.stat_code = BackgroundJobBase.stat_completed_c
435 434 self.finished = True
436 435
437 436
438 437 class BackgroundJobExpr(BackgroundJobBase):
439 438 """Evaluate an expression as a background job (uses a separate thread)."""
440 439
441 440 def __init__(self, expression, glob=None, loc=None):
442 441 """Create a new job from a string which can be fed to eval().
443 442
444 443 global/locals dicts can be provided, which will be passed to the eval
445 444 call."""
446 445
447 446 # fail immediately if the given expression can't be compiled
448 447 self.code = compile(expression,'<BackgroundJob compilation>','eval')
449 448
450 449 glob = {} if glob is None else glob
451 450 loc = {} if loc is None else loc
452 451 self.expression = self.strform = expression
453 452 self.glob = glob
454 453 self.loc = loc
455 454 self._init()
456 455
457 456 def call(self):
458 457 return eval(self.code,self.glob,self.loc)
459 458
460 459
461 460 class BackgroundJobFunc(BackgroundJobBase):
462 461 """Run a function call as a background job (uses a separate thread)."""
463 462
464 463 def __init__(self, func, *args, **kwargs):
465 464 """Create a new job from a callable object.
466 465
467 466 Any positional arguments and keyword args given to this constructor
468 467 after the initial callable are passed directly to it."""
469 468
470 469 if not callable(func):
471 470 raise TypeError(
472 471 'first argument to BackgroundJobFunc must be callable')
473 472
474 473 self.func = func
475 474 self.args = args
476 475 self.kwargs = kwargs
477 476 # The string form will only include the function passed, because
478 477 # generating string representations of the arguments is a potentially
479 478 # _very_ expensive operation (e.g. with large arrays).
480 479 self.strform = str(func)
481 480 self._init()
482 481
483 482 def call(self):
484 483 return self.func(*self.args, **self.kwargs)
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now