##// 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 # encoding: utf-8
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian E. Granger
7 * Brian E. Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2008-2011 The IPython Development Team
12 # Copyright (C) 2008-2011 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 from __future__ import print_function
21
22
22 import os
23 import os
23 import sys
24 import sys
24 import traceback
25 import traceback
25 from pprint import pformat
26 from pprint import pformat
26
27
27 from IPython.core import ultratb
28 from IPython.core import ultratb
28 from IPython.core.release import author_email
29 from IPython.core.release import author_email
29 from IPython.utils.sysinfo import sys_info
30 from IPython.utils.sysinfo import sys_info
30
31
31 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
32 # Code
33 # Code
33 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
34
35
35 # Template for the user message.
36 # Template for the user message.
36 _default_message_template = """\
37 _default_message_template = """\
37 Oops, {app_name} crashed. We do our best to make it stable, but...
38 Oops, {app_name} crashed. We do our best to make it stable, but...
38
39
39 A crash report was automatically generated with the following information:
40 A crash report was automatically generated with the following information:
40 - A verbatim copy of the crash traceback.
41 - A verbatim copy of the crash traceback.
41 - A copy of your input history during this session.
42 - A copy of your input history during this session.
42 - Data on your current {app_name} configuration.
43 - Data on your current {app_name} configuration.
43
44
44 It was left in the file named:
45 It was left in the file named:
45 \t'{crash_report_fname}'
46 \t'{crash_report_fname}'
46 If you can email this file to the developers, the information in it will help
47 If you can email this file to the developers, the information in it will help
47 them in understanding and correcting the problem.
48 them in understanding and correcting the problem.
48
49
49 You can mail it to: {contact_name} at {contact_email}
50 You can mail it to: {contact_name} at {contact_email}
50 with the subject '{app_name} Crash Report'.
51 with the subject '{app_name} Crash Report'.
51
52
52 If you want to do it now, the following command will work (under Unix):
53 If you want to do it now, the following command will work (under Unix):
53 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
54 mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
54
55
55 To ensure accurate tracking of this issue, please file a report about it at:
56 To ensure accurate tracking of this issue, please file a report about it at:
56 {bug_tracker}
57 {bug_tracker}
57 """
58 """
58
59
59 _lite_message_template = """
60 _lite_message_template = """
60 If you suspect this is an IPython bug, please report it at:
61 If you suspect this is an IPython bug, please report it at:
61 https://github.com/ipython/ipython/issues
62 https://github.com/ipython/ipython/issues
62 or send an email to the mailing list at {email}
63 or send an email to the mailing list at {email}
63
64
64 You can print a more detailed traceback right now with "%tb", or use "%debug"
65 You can print a more detailed traceback right now with "%tb", or use "%debug"
65 to interactively debug it.
66 to interactively debug it.
66
67
67 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
68 Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
68 {config}Application.verbose_crash=True
69 {config}Application.verbose_crash=True
69 """
70 """
70
71
71
72
72 class CrashHandler(object):
73 class CrashHandler(object):
73 """Customizable crash handlers for IPython applications.
74 """Customizable crash handlers for IPython applications.
74
75
75 Instances of this class provide a :meth:`__call__` method which can be
76 Instances of this class provide a :meth:`__call__` method which can be
76 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
77 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
77
78
78 def __call__(self, etype, evalue, etb)
79 def __call__(self, etype, evalue, etb)
79 """
80 """
80
81
81 message_template = _default_message_template
82 message_template = _default_message_template
82 section_sep = '\n\n'+'*'*75+'\n\n'
83 section_sep = '\n\n'+'*'*75+'\n\n'
83
84
84 def __init__(self, app, contact_name=None, contact_email=None,
85 def __init__(self, app, contact_name=None, contact_email=None,
85 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
86 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
86 """Create a new crash handler
87 """Create a new crash handler
87
88
88 Parameters
89 Parameters
89 ----------
90 ----------
90 app : Application
91 app : Application
91 A running :class:`Application` instance, which will be queried at
92 A running :class:`Application` instance, which will be queried at
92 crash time for internal information.
93 crash time for internal information.
93
94
94 contact_name : str
95 contact_name : str
95 A string with the name of the person to contact.
96 A string with the name of the person to contact.
96
97
97 contact_email : str
98 contact_email : str
98 A string with the email address of the contact.
99 A string with the email address of the contact.
99
100
100 bug_tracker : str
101 bug_tracker : str
101 A string with the URL for your project's bug tracker.
102 A string with the URL for your project's bug tracker.
102
103
103 show_crash_traceback : bool
104 show_crash_traceback : bool
104 If false, don't print the crash traceback on stderr, only generate
105 If false, don't print the crash traceback on stderr, only generate
105 the on-disk report
106 the on-disk report
106
107
107 Non-argument instance attributes:
108 Non-argument instance attributes:
108
109
109 These instances contain some non-argument attributes which allow for
110 These instances contain some non-argument attributes which allow for
110 further customization of the crash handler's behavior. Please see the
111 further customization of the crash handler's behavior. Please see the
111 source for further details.
112 source for further details.
112 """
113 """
113 self.crash_report_fname = "Crash_report_%s.txt" % app.name
114 self.crash_report_fname = "Crash_report_%s.txt" % app.name
114 self.app = app
115 self.app = app
115 self.call_pdb = call_pdb
116 self.call_pdb = call_pdb
116 #self.call_pdb = True # dbg
117 #self.call_pdb = True # dbg
117 self.show_crash_traceback = show_crash_traceback
118 self.show_crash_traceback = show_crash_traceback
118 self.info = dict(app_name = app.name,
119 self.info = dict(app_name = app.name,
119 contact_name = contact_name,
120 contact_name = contact_name,
120 contact_email = contact_email,
121 contact_email = contact_email,
121 bug_tracker = bug_tracker,
122 bug_tracker = bug_tracker,
122 crash_report_fname = self.crash_report_fname)
123 crash_report_fname = self.crash_report_fname)
123
124
124
125
125 def __call__(self, etype, evalue, etb):
126 def __call__(self, etype, evalue, etb):
126 """Handle an exception, call for compatible with sys.excepthook"""
127 """Handle an exception, call for compatible with sys.excepthook"""
127
128
128 # do not allow the crash handler to be called twice without reinstalling it
129 # do not allow the crash handler to be called twice without reinstalling it
129 # this prevents unlikely errors in the crash handling from entering an
130 # this prevents unlikely errors in the crash handling from entering an
130 # infinite loop.
131 # infinite loop.
131 sys.excepthook = sys.__excepthook__
132 sys.excepthook = sys.__excepthook__
132
133
133 # Report tracebacks shouldn't use color in general (safer for users)
134 # Report tracebacks shouldn't use color in general (safer for users)
134 color_scheme = 'NoColor'
135 color_scheme = 'NoColor'
135
136
136 # Use this ONLY for developer debugging (keep commented out for release)
137 # Use this ONLY for developer debugging (keep commented out for release)
137 #color_scheme = 'Linux' # dbg
138 #color_scheme = 'Linux' # dbg
138 try:
139 try:
139 rptdir = self.app.ipython_dir
140 rptdir = self.app.ipython_dir
140 except:
141 except:
141 rptdir = os.getcwdu()
142 rptdir = os.getcwdu()
142 if rptdir is None or not os.path.isdir(rptdir):
143 if rptdir is None or not os.path.isdir(rptdir):
143 rptdir = os.getcwdu()
144 rptdir = os.getcwdu()
144 report_name = os.path.join(rptdir,self.crash_report_fname)
145 report_name = os.path.join(rptdir,self.crash_report_fname)
145 # write the report filename into the instance dict so it can get
146 # write the report filename into the instance dict so it can get
146 # properly expanded out in the user message template
147 # properly expanded out in the user message template
147 self.crash_report_fname = report_name
148 self.crash_report_fname = report_name
148 self.info['crash_report_fname'] = report_name
149 self.info['crash_report_fname'] = report_name
149 TBhandler = ultratb.VerboseTB(
150 TBhandler = ultratb.VerboseTB(
150 color_scheme=color_scheme,
151 color_scheme=color_scheme,
151 long_header=1,
152 long_header=1,
152 call_pdb=self.call_pdb,
153 call_pdb=self.call_pdb,
153 )
154 )
154 if self.call_pdb:
155 if self.call_pdb:
155 TBhandler(etype,evalue,etb)
156 TBhandler(etype,evalue,etb)
156 return
157 return
157 else:
158 else:
158 traceback = TBhandler.text(etype,evalue,etb,context=31)
159 traceback = TBhandler.text(etype,evalue,etb,context=31)
159
160
160 # print traceback to screen
161 # print traceback to screen
161 if self.show_crash_traceback:
162 if self.show_crash_traceback:
162 print >> sys.stderr, traceback
163 print(traceback, file=sys.stderr)
163
164
164 # and generate a complete report on disk
165 # and generate a complete report on disk
165 try:
166 try:
166 report = open(report_name,'w')
167 report = open(report_name,'w')
167 except:
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 return
170 return
170
171
171 # Inform user on stderr of what happened
172 # Inform user on stderr of what happened
172 print >> sys.stderr, '\n'+'*'*70+'\n'
173 print('\n'+'*'*70+'\n', file=sys.stderr)
173 print >> sys.stderr, self.message_template.format(**self.info)
174 print(self.message_template.format(**self.info), file=sys.stderr)
174
175
175 # Construct report on disk
176 # Construct report on disk
176 report.write(self.make_report(traceback))
177 report.write(self.make_report(traceback))
177 report.close()
178 report.close()
178 raw_input("Hit <Enter> to quit (your terminal may close):")
179 raw_input("Hit <Enter> to quit (your terminal may close):")
179
180
180 def make_report(self,traceback):
181 def make_report(self,traceback):
181 """Return a string containing a crash report."""
182 """Return a string containing a crash report."""
182
183
183 sec_sep = self.section_sep
184 sec_sep = self.section_sep
184
185
185 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
186 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
186 rpt_add = report.append
187 rpt_add = report.append
187 rpt_add(sys_info())
188 rpt_add(sys_info())
188
189
189 try:
190 try:
190 config = pformat(self.app.config)
191 config = pformat(self.app.config)
191 rpt_add(sec_sep)
192 rpt_add(sec_sep)
192 rpt_add('Application name: %s\n\n' % self.app_name)
193 rpt_add('Application name: %s\n\n' % self.app_name)
193 rpt_add('Current user configuration structure:\n\n')
194 rpt_add('Current user configuration structure:\n\n')
194 rpt_add(config)
195 rpt_add(config)
195 except:
196 except:
196 pass
197 pass
197 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
198 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
198
199
199 return ''.join(report)
200 return ''.join(report)
200
201
201
202
202 def crash_handler_lite(etype, evalue, tb):
203 def crash_handler_lite(etype, evalue, tb):
203 """a light excepthook, adding a small message to the usual traceback"""
204 """a light excepthook, adding a small message to the usual traceback"""
204 traceback.print_exception(etype, evalue, tb)
205 traceback.print_exception(etype, evalue, tb)
205
206
206 from IPython.core.interactiveshell import InteractiveShell
207 from IPython.core.interactiveshell import InteractiveShell
207 if InteractiveShell.initialized():
208 if InteractiveShell.initialized():
208 # we are in a Shell environment, give %magic example
209 # we are in a Shell environment, give %magic example
209 config = "%config "
210 config = "%config "
210 else:
211 else:
211 # we are not in a shell, show generic config
212 # we are not in a shell, show generic config
212 config = "c."
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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
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 import bdb
29 import bdb
29 import linecache
30 import linecache
30 import sys
31 import sys
31
32
32 from IPython.utils import PyColorize
33 from IPython.utils import PyColorize
33 from IPython.core import ipapi
34 from IPython.core import ipapi
34 from IPython.utils import coloransi, io
35 from IPython.utils import coloransi, io
35 from IPython.core.excolors import exception_colors
36 from IPython.core.excolors import exception_colors
36
37
37 # See if we can use pydb.
38 # See if we can use pydb.
38 has_pydb = False
39 has_pydb = False
39 prompt = 'ipdb> '
40 prompt = 'ipdb> '
40 #We have to check this directly from sys.argv, config struct not yet available
41 #We have to check this directly from sys.argv, config struct not yet available
41 if '--pydb' in sys.argv:
42 if '--pydb' in sys.argv:
42 try:
43 try:
43 import pydb
44 import pydb
44 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
45 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
46 # better protect against it.
47 # better protect against it.
47 has_pydb = True
48 has_pydb = True
48 except ImportError:
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 if has_pydb:
52 if has_pydb:
52 from pydb import Pdb as OldPdb
53 from pydb import Pdb as OldPdb
53 #print "Using pydb for %run -d and post-mortem" #dbg
54 #print "Using pydb for %run -d and post-mortem" #dbg
54 prompt = 'ipydb> '
55 prompt = 'ipydb> '
55 else:
56 else:
56 from pdb import Pdb as OldPdb
57 from pdb import Pdb as OldPdb
57
58
58 # Allow the set_trace code to operate outside of an ipython instance, even if
59 # Allow the set_trace code to operate outside of an ipython instance, even if
59 # it does so with some limitations. The rest of this support is implemented in
60 # it does so with some limitations. The rest of this support is implemented in
60 # the Tracer constructor.
61 # the Tracer constructor.
61 def BdbQuit_excepthook(et,ev,tb):
62 def BdbQuit_excepthook(et,ev,tb):
62 if et==bdb.BdbQuit:
63 if et==bdb.BdbQuit:
63 print 'Exiting Debugger.'
64 print('Exiting Debugger.')
64 else:
65 else:
65 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66
67
67 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
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 class Tracer(object):
72 class Tracer(object):
72 """Class for local debugging, similar to pdb.set_trace.
73 """Class for local debugging, similar to pdb.set_trace.
73
74
74 Instances of this class, when called, behave like pdb.set_trace, but
75 Instances of this class, when called, behave like pdb.set_trace, but
75 providing IPython's enhanced capabilities.
76 providing IPython's enhanced capabilities.
76
77
77 This is implemented as a class which must be initialized in your own code
78 This is implemented as a class which must be initialized in your own code
78 and not as a standalone function because we need to detect at runtime
79 and not as a standalone function because we need to detect at runtime
79 whether IPython is already active or not. That detection is done in the
80 whether IPython is already active or not. That detection is done in the
80 constructor, ensuring that this code plays nicely with a running IPython,
81 constructor, ensuring that this code plays nicely with a running IPython,
81 while functioning acceptably (though with limitations) if outside of it.
82 while functioning acceptably (though with limitations) if outside of it.
82 """
83 """
83
84
84 def __init__(self,colors=None):
85 def __init__(self,colors=None):
85 """Create a local debugger instance.
86 """Create a local debugger instance.
86
87
87 :Parameters:
88 :Parameters:
88
89
89 - `colors` (None): a string containing the name of the color scheme to
90 - `colors` (None): a string containing the name of the color scheme to
90 use, it must be one of IPython's valid color schemes. If not given, the
91 use, it must be one of IPython's valid color schemes. If not given, the
91 function will default to the current IPython scheme when running inside
92 function will default to the current IPython scheme when running inside
92 IPython, and to 'NoColor' otherwise.
93 IPython, and to 'NoColor' otherwise.
93
94
94 Usage example:
95 Usage example:
95
96
96 from IPython.core.debugger import Tracer; debug_here = Tracer()
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
97
98
98 ... later in your code
99 ... later in your code
99 debug_here() # -> will open up the debugger at that point.
100 debug_here() # -> will open up the debugger at that point.
100
101
101 Once the debugger activates, you can use all of its regular commands to
102 Once the debugger activates, you can use all of its regular commands to
102 step through code, set breakpoints, etc. See the pdb documentation
103 step through code, set breakpoints, etc. See the pdb documentation
103 from the Python standard library for usage details.
104 from the Python standard library for usage details.
104 """
105 """
105
106
106 try:
107 try:
107 ip = get_ipython()
108 ip = get_ipython()
108 except NameError:
109 except NameError:
109 # Outside of ipython, we set our own exception hook manually
110 # Outside of ipython, we set our own exception hook manually
110 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 sys.excepthook = BdbQuit_excepthook
112 sys.excepthook = BdbQuit_excepthook
112 def_colors = 'NoColor'
113 def_colors = 'NoColor'
113 try:
114 try:
114 # Limited tab completion support
115 # Limited tab completion support
115 import readline
116 import readline
116 readline.parse_and_bind('tab: complete')
117 readline.parse_and_bind('tab: complete')
117 except ImportError:
118 except ImportError:
118 pass
119 pass
119 else:
120 else:
120 # In ipython, we use its custom exception handler mechanism
121 # In ipython, we use its custom exception handler mechanism
121 def_colors = ip.colors
122 def_colors = ip.colors
122 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
123
124
124 if colors is None:
125 if colors is None:
125 colors = def_colors
126 colors = def_colors
126
127
127 # The stdlib debugger internally uses a modified repr from the `repr`
128 # The stdlib debugger internally uses a modified repr from the `repr`
128 # module, that limits the length of printed strings to a hardcoded
129 # module, that limits the length of printed strings to a hardcoded
129 # limit of 30 characters. That much trimming is too aggressive, let's
130 # limit of 30 characters. That much trimming is too aggressive, let's
130 # at least raise that limit to 80 chars, which should be enough for
131 # at least raise that limit to 80 chars, which should be enough for
131 # most interactive uses.
132 # most interactive uses.
132 try:
133 try:
133 from repr import aRepr
134 from repr import aRepr
134 aRepr.maxstring = 80
135 aRepr.maxstring = 80
135 except:
136 except:
136 # This is only a user-facing convenience, so any error we encounter
137 # This is only a user-facing convenience, so any error we encounter
137 # here can be warned about but can be otherwise ignored. These
138 # here can be warned about but can be otherwise ignored. These
138 # printouts will tell us about problems if this API changes
139 # printouts will tell us about problems if this API changes
139 import traceback
140 import traceback
140 traceback.print_exc()
141 traceback.print_exc()
141
142
142 self.debugger = Pdb(colors)
143 self.debugger = Pdb(colors)
143
144
144 def __call__(self):
145 def __call__(self):
145 """Starts an interactive debugger at the point where called.
146 """Starts an interactive debugger at the point where called.
146
147
147 This is similar to the pdb.set_trace() function from the std lib, but
148 This is similar to the pdb.set_trace() function from the std lib, but
148 using IPython's enhanced debugger."""
149 using IPython's enhanced debugger."""
149
150
150 self.debugger.set_trace(sys._getframe().f_back)
151 self.debugger.set_trace(sys._getframe().f_back)
151
152
152
153
153 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
154 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
154 """Make new_fn have old_fn's doc string. This is particularly useful
155 """Make new_fn have old_fn's doc string. This is particularly useful
155 for the do_... commands that hook into the help system.
156 for the do_... commands that hook into the help system.
156 Adapted from from a comp.lang.python posting
157 Adapted from from a comp.lang.python posting
157 by Duncan Booth."""
158 by Duncan Booth."""
158 def wrapper(*args, **kw):
159 def wrapper(*args, **kw):
159 return new_fn(*args, **kw)
160 return new_fn(*args, **kw)
160 if old_fn.__doc__:
161 if old_fn.__doc__:
161 wrapper.__doc__ = old_fn.__doc__ + additional_text
162 wrapper.__doc__ = old_fn.__doc__ + additional_text
162 return wrapper
163 return wrapper
163
164
164
165
165 def _file_lines(fname):
166 def _file_lines(fname):
166 """Return the contents of a named file as a list of lines.
167 """Return the contents of a named file as a list of lines.
167
168
168 This function never raises an IOError exception: if the file can't be
169 This function never raises an IOError exception: if the file can't be
169 read, it simply returns an empty list."""
170 read, it simply returns an empty list."""
170
171
171 try:
172 try:
172 outfile = open(fname)
173 outfile = open(fname)
173 except IOError:
174 except IOError:
174 return []
175 return []
175 else:
176 else:
176 out = outfile.readlines()
177 out = outfile.readlines()
177 outfile.close()
178 outfile.close()
178 return out
179 return out
179
180
180
181
181 class Pdb(OldPdb):
182 class Pdb(OldPdb):
182 """Modified Pdb class, does not load readline."""
183 """Modified Pdb class, does not load readline."""
183
184
184 def __init__(self,color_scheme='NoColor',completekey=None,
185 def __init__(self,color_scheme='NoColor',completekey=None,
185 stdin=None, stdout=None):
186 stdin=None, stdout=None):
186
187
187 # Parent constructor:
188 # Parent constructor:
188 if has_pydb and completekey is None:
189 if has_pydb and completekey is None:
189 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
190 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
190 else:
191 else:
191 OldPdb.__init__(self,completekey,stdin,stdout)
192 OldPdb.__init__(self,completekey,stdin,stdout)
192
193
193 self.prompt = prompt # The default prompt is '(Pdb)'
194 self.prompt = prompt # The default prompt is '(Pdb)'
194
195
195 # IPython changes...
196 # IPython changes...
196 self.is_pydb = has_pydb
197 self.is_pydb = has_pydb
197
198
198 self.shell = ipapi.get()
199 self.shell = ipapi.get()
199
200
200 if self.is_pydb:
201 if self.is_pydb:
201
202
202 # interactiveshell.py's ipalias seems to want pdb's checkline
203 # interactiveshell.py's ipalias seems to want pdb's checkline
203 # which located in pydb.fn
204 # which located in pydb.fn
204 import pydb.fns
205 import pydb.fns
205 self.checkline = lambda filename, lineno: \
206 self.checkline = lambda filename, lineno: \
206 pydb.fns.checkline(self, filename, lineno)
207 pydb.fns.checkline(self, filename, lineno)
207
208
208 self.curframe = None
209 self.curframe = None
209 self.do_restart = self.new_do_restart
210 self.do_restart = self.new_do_restart
210
211
211 self.old_all_completions = self.shell.Completer.all_completions
212 self.old_all_completions = self.shell.Completer.all_completions
212 self.shell.Completer.all_completions=self.all_completions
213 self.shell.Completer.all_completions=self.all_completions
213
214
214 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
215 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
215 OldPdb.do_list)
216 OldPdb.do_list)
216 self.do_l = self.do_list
217 self.do_l = self.do_list
217 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
218 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
218 OldPdb.do_frame)
219 OldPdb.do_frame)
219
220
220 self.aliases = {}
221 self.aliases = {}
221
222
222 # Create color table: we copy the default one from the traceback
223 # Create color table: we copy the default one from the traceback
223 # module and add a few attributes needed for debugging
224 # module and add a few attributes needed for debugging
224 self.color_scheme_table = exception_colors()
225 self.color_scheme_table = exception_colors()
225
226
226 # shorthands
227 # shorthands
227 C = coloransi.TermColors
228 C = coloransi.TermColors
228 cst = self.color_scheme_table
229 cst = self.color_scheme_table
229
230
230 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
231 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
231 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
232 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
232
233
233 cst['Linux'].colors.breakpoint_enabled = C.LightRed
234 cst['Linux'].colors.breakpoint_enabled = C.LightRed
234 cst['Linux'].colors.breakpoint_disabled = C.Red
235 cst['Linux'].colors.breakpoint_disabled = C.Red
235
236
236 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
237 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
237 cst['LightBG'].colors.breakpoint_disabled = C.Red
238 cst['LightBG'].colors.breakpoint_disabled = C.Red
238
239
239 self.set_colors(color_scheme)
240 self.set_colors(color_scheme)
240
241
241 # Add a python parser so we can syntax highlight source while
242 # Add a python parser so we can syntax highlight source while
242 # debugging.
243 # debugging.
243 self.parser = PyColorize.Parser()
244 self.parser = PyColorize.Parser()
244
245
245 def set_colors(self, scheme):
246 def set_colors(self, scheme):
246 """Shorthand access to the color table scheme selector method."""
247 """Shorthand access to the color table scheme selector method."""
247 self.color_scheme_table.set_active_scheme(scheme)
248 self.color_scheme_table.set_active_scheme(scheme)
248
249
249 def interaction(self, frame, traceback):
250 def interaction(self, frame, traceback):
250 self.shell.set_completer_frame(frame)
251 self.shell.set_completer_frame(frame)
251 OldPdb.interaction(self, frame, traceback)
252 OldPdb.interaction(self, frame, traceback)
252
253
253 def new_do_up(self, arg):
254 def new_do_up(self, arg):
254 OldPdb.do_up(self, arg)
255 OldPdb.do_up(self, arg)
255 self.shell.set_completer_frame(self.curframe)
256 self.shell.set_completer_frame(self.curframe)
256 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
257 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
257
258
258 def new_do_down(self, arg):
259 def new_do_down(self, arg):
259 OldPdb.do_down(self, arg)
260 OldPdb.do_down(self, arg)
260 self.shell.set_completer_frame(self.curframe)
261 self.shell.set_completer_frame(self.curframe)
261
262
262 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
263 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
263
264
264 def new_do_frame(self, arg):
265 def new_do_frame(self, arg):
265 OldPdb.do_frame(self, arg)
266 OldPdb.do_frame(self, arg)
266 self.shell.set_completer_frame(self.curframe)
267 self.shell.set_completer_frame(self.curframe)
267
268
268 def new_do_quit(self, arg):
269 def new_do_quit(self, arg):
269
270
270 if hasattr(self, 'old_all_completions'):
271 if hasattr(self, 'old_all_completions'):
271 self.shell.Completer.all_completions=self.old_all_completions
272 self.shell.Completer.all_completions=self.old_all_completions
272
273
273
274
274 return OldPdb.do_quit(self, arg)
275 return OldPdb.do_quit(self, arg)
275
276
276 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
277 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
277
278
278 def new_do_restart(self, arg):
279 def new_do_restart(self, arg):
279 """Restart command. In the context of ipython this is exactly the same
280 """Restart command. In the context of ipython this is exactly the same
280 thing as 'quit'."""
281 thing as 'quit'."""
281 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
282 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
282 return self.do_quit(arg)
283 return self.do_quit(arg)
283
284
284 def postloop(self):
285 def postloop(self):
285 self.shell.set_completer_frame(None)
286 self.shell.set_completer_frame(None)
286
287
287 def print_stack_trace(self):
288 def print_stack_trace(self):
288 try:
289 try:
289 for frame_lineno in self.stack:
290 for frame_lineno in self.stack:
290 self.print_stack_entry(frame_lineno, context = 5)
291 self.print_stack_entry(frame_lineno, context = 5)
291 except KeyboardInterrupt:
292 except KeyboardInterrupt:
292 pass
293 pass
293
294
294 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
295 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
295 context = 3):
296 context = 3):
296 #frame, lineno = frame_lineno
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 # vds: >>
300 # vds: >>
300 frame, lineno = frame_lineno
301 frame, lineno = frame_lineno
301 filename = frame.f_code.co_filename
302 filename = frame.f_code.co_filename
302 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
303 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
303 # vds: <<
304 # vds: <<
304
305
305 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
306 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
306 import linecache, repr
307 import linecache, repr
307
308
308 ret = []
309 ret = []
309
310
310 Colors = self.color_scheme_table.active_colors
311 Colors = self.color_scheme_table.active_colors
311 ColorsNormal = Colors.Normal
312 ColorsNormal = Colors.Normal
312 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
313 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
313 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
314 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
314 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
315 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
315 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
316 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
316 ColorsNormal)
317 ColorsNormal)
317
318
318 frame, lineno = frame_lineno
319 frame, lineno = frame_lineno
319
320
320 return_value = ''
321 return_value = ''
321 if '__return__' in frame.f_locals:
322 if '__return__' in frame.f_locals:
322 rv = frame.f_locals['__return__']
323 rv = frame.f_locals['__return__']
323 #return_value += '->'
324 #return_value += '->'
324 return_value += repr.repr(rv) + '\n'
325 return_value += repr.repr(rv) + '\n'
325 ret.append(return_value)
326 ret.append(return_value)
326
327
327 #s = filename + '(' + `lineno` + ')'
328 #s = filename + '(' + `lineno` + ')'
328 filename = self.canonic(frame.f_code.co_filename)
329 filename = self.canonic(frame.f_code.co_filename)
329 link = tpl_link % filename
330 link = tpl_link % filename
330
331
331 if frame.f_code.co_name:
332 if frame.f_code.co_name:
332 func = frame.f_code.co_name
333 func = frame.f_code.co_name
333 else:
334 else:
334 func = "<lambda>"
335 func = "<lambda>"
335
336
336 call = ''
337 call = ''
337 if func != '?':
338 if func != '?':
338 if '__args__' in frame.f_locals:
339 if '__args__' in frame.f_locals:
339 args = repr.repr(frame.f_locals['__args__'])
340 args = repr.repr(frame.f_locals['__args__'])
340 else:
341 else:
341 args = '()'
342 args = '()'
342 call = tpl_call % (func, args)
343 call = tpl_call % (func, args)
343
344
344 # The level info should be generated in the same format pdb uses, to
345 # The level info should be generated in the same format pdb uses, to
345 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
346 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
346 if frame is self.curframe:
347 if frame is self.curframe:
347 ret.append('> ')
348 ret.append('> ')
348 else:
349 else:
349 ret.append(' ')
350 ret.append(' ')
350 ret.append('%s(%s)%s\n' % (link,lineno,call))
351 ret.append('%s(%s)%s\n' % (link,lineno,call))
351
352
352 start = lineno - 1 - context//2
353 start = lineno - 1 - context//2
353 lines = linecache.getlines(filename)
354 lines = linecache.getlines(filename)
354 start = max(start, 0)
355 start = max(start, 0)
355 start = min(start, len(lines) - context)
356 start = min(start, len(lines) - context)
356 lines = lines[start : start + context]
357 lines = lines[start : start + context]
357
358
358 for i,line in enumerate(lines):
359 for i,line in enumerate(lines):
359 show_arrow = (start + 1 + i == lineno)
360 show_arrow = (start + 1 + i == lineno)
360 linetpl = (frame is self.curframe or show_arrow) \
361 linetpl = (frame is self.curframe or show_arrow) \
361 and tpl_line_em \
362 and tpl_line_em \
362 or tpl_line
363 or tpl_line
363 ret.append(self.__format_line(linetpl, filename,
364 ret.append(self.__format_line(linetpl, filename,
364 start + 1 + i, line,
365 start + 1 + i, line,
365 arrow = show_arrow) )
366 arrow = show_arrow) )
366
367
367 return ''.join(ret)
368 return ''.join(ret)
368
369
369 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
370 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
370 bp_mark = ""
371 bp_mark = ""
371 bp_mark_color = ""
372 bp_mark_color = ""
372
373
373 scheme = self.color_scheme_table.active_scheme_name
374 scheme = self.color_scheme_table.active_scheme_name
374 new_line, err = self.parser.format2(line, 'str', scheme)
375 new_line, err = self.parser.format2(line, 'str', scheme)
375 if not err: line = new_line
376 if not err: line = new_line
376
377
377 bp = None
378 bp = None
378 if lineno in self.get_file_breaks(filename):
379 if lineno in self.get_file_breaks(filename):
379 bps = self.get_breaks(filename, lineno)
380 bps = self.get_breaks(filename, lineno)
380 bp = bps[-1]
381 bp = bps[-1]
381
382
382 if bp:
383 if bp:
383 Colors = self.color_scheme_table.active_colors
384 Colors = self.color_scheme_table.active_colors
384 bp_mark = str(bp.number)
385 bp_mark = str(bp.number)
385 bp_mark_color = Colors.breakpoint_enabled
386 bp_mark_color = Colors.breakpoint_enabled
386 if not bp.enabled:
387 if not bp.enabled:
387 bp_mark_color = Colors.breakpoint_disabled
388 bp_mark_color = Colors.breakpoint_disabled
388
389
389 numbers_width = 7
390 numbers_width = 7
390 if arrow:
391 if arrow:
391 # This is the line with the error
392 # This is the line with the error
392 pad = numbers_width - len(str(lineno)) - len(bp_mark)
393 pad = numbers_width - len(str(lineno)) - len(bp_mark)
393 if pad >= 3:
394 if pad >= 3:
394 marker = '-'*(pad-3) + '-> '
395 marker = '-'*(pad-3) + '-> '
395 elif pad == 2:
396 elif pad == 2:
396 marker = '> '
397 marker = '> '
397 elif pad == 1:
398 elif pad == 1:
398 marker = '>'
399 marker = '>'
399 else:
400 else:
400 marker = ''
401 marker = ''
401 num = '%s%s' % (marker, str(lineno))
402 num = '%s%s' % (marker, str(lineno))
402 line = tpl_line % (bp_mark_color + bp_mark, num, line)
403 line = tpl_line % (bp_mark_color + bp_mark, num, line)
403 else:
404 else:
404 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
405 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
405 line = tpl_line % (bp_mark_color + bp_mark, num, line)
406 line = tpl_line % (bp_mark_color + bp_mark, num, line)
406
407
407 return line
408 return line
408
409
409 def list_command_pydb(self, arg):
410 def list_command_pydb(self, arg):
410 """List command to use if we have a newer pydb installed"""
411 """List command to use if we have a newer pydb installed"""
411 filename, first, last = OldPdb.parse_list_cmd(self, arg)
412 filename, first, last = OldPdb.parse_list_cmd(self, arg)
412 if filename is not None:
413 if filename is not None:
413 self.print_list_lines(filename, first, last)
414 self.print_list_lines(filename, first, last)
414
415
415 def print_list_lines(self, filename, first, last):
416 def print_list_lines(self, filename, first, last):
416 """The printing (as opposed to the parsing part of a 'list'
417 """The printing (as opposed to the parsing part of a 'list'
417 command."""
418 command."""
418 try:
419 try:
419 Colors = self.color_scheme_table.active_colors
420 Colors = self.color_scheme_table.active_colors
420 ColorsNormal = Colors.Normal
421 ColorsNormal = Colors.Normal
421 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
422 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
422 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
423 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
423 src = []
424 src = []
424 for lineno in range(first, last+1):
425 for lineno in range(first, last+1):
425 line = linecache.getline(filename, lineno)
426 line = linecache.getline(filename, lineno)
426 if not line:
427 if not line:
427 break
428 break
428
429
429 if lineno == self.curframe.f_lineno:
430 if lineno == self.curframe.f_lineno:
430 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
431 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
431 else:
432 else:
432 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
433 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
433
434
434 src.append(line)
435 src.append(line)
435 self.lineno = lineno
436 self.lineno = lineno
436
437
437 print >>io.stdout, ''.join(src)
438 print(''.join(src), file=io.stdout)
438
439
439 except KeyboardInterrupt:
440 except KeyboardInterrupt:
440 pass
441 pass
441
442
442 def do_list(self, arg):
443 def do_list(self, arg):
443 self.lastcmd = 'list'
444 self.lastcmd = 'list'
444 last = None
445 last = None
445 if arg:
446 if arg:
446 try:
447 try:
447 x = eval(arg, {}, {})
448 x = eval(arg, {}, {})
448 if type(x) == type(()):
449 if type(x) == type(()):
449 first, last = x
450 first, last = x
450 first = int(first)
451 first = int(first)
451 last = int(last)
452 last = int(last)
452 if last < first:
453 if last < first:
453 # Assume it's a count
454 # Assume it's a count
454 last = first + last
455 last = first + last
455 else:
456 else:
456 first = max(1, int(x) - 5)
457 first = max(1, int(x) - 5)
457 except:
458 except:
458 print '*** Error in argument:', `arg`
459 print('*** Error in argument:', repr(arg))
459 return
460 return
460 elif self.lineno is None:
461 elif self.lineno is None:
461 first = max(1, self.curframe.f_lineno - 5)
462 first = max(1, self.curframe.f_lineno - 5)
462 else:
463 else:
463 first = self.lineno + 1
464 first = self.lineno + 1
464 if last is None:
465 if last is None:
465 last = first + 10
466 last = first + 10
466 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
467 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
467
468
468 # vds: >>
469 # vds: >>
469 lineno = first
470 lineno = first
470 filename = self.curframe.f_code.co_filename
471 filename = self.curframe.f_code.co_filename
471 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
472 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
472 # vds: <<
473 # vds: <<
473
474
474 do_l = do_list
475 do_l = do_list
475
476
476 def do_pdef(self, arg):
477 def do_pdef(self, arg):
477 """The debugger interface to magic_pdef"""
478 """The debugger interface to magic_pdef"""
478 namespaces = [('Locals', self.curframe.f_locals),
479 namespaces = [('Locals', self.curframe.f_locals),
479 ('Globals', self.curframe.f_globals)]
480 ('Globals', self.curframe.f_globals)]
480 self.shell.magic_pdef(arg, namespaces=namespaces)
481 self.shell.magic_pdef(arg, namespaces=namespaces)
481
482
482 def do_pdoc(self, arg):
483 def do_pdoc(self, arg):
483 """The debugger interface to magic_pdoc"""
484 """The debugger interface to magic_pdoc"""
484 namespaces = [('Locals', self.curframe.f_locals),
485 namespaces = [('Locals', self.curframe.f_locals),
485 ('Globals', self.curframe.f_globals)]
486 ('Globals', self.curframe.f_globals)]
486 self.shell.magic_pdoc(arg, namespaces=namespaces)
487 self.shell.magic_pdoc(arg, namespaces=namespaces)
487
488
488 def do_pinfo(self, arg):
489 def do_pinfo(self, arg):
489 """The debugger equivalant of ?obj"""
490 """The debugger equivalant of ?obj"""
490 namespaces = [('Locals', self.curframe.f_locals),
491 namespaces = [('Locals', self.curframe.f_locals),
491 ('Globals', self.curframe.f_globals)]
492 ('Globals', self.curframe.f_globals)]
492 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
493 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
493
494
494 def checkline(self, filename, lineno):
495 def checkline(self, filename, lineno):
495 """Check whether specified line seems to be executable.
496 """Check whether specified line seems to be executable.
496
497
497 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
498 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
498 line or EOF). Warning: testing is not comprehensive.
499 line or EOF). Warning: testing is not comprehensive.
499 """
500 """
500 #######################################################################
501 #######################################################################
501 # XXX Hack! Use python-2.5 compatible code for this call, because with
502 # XXX Hack! Use python-2.5 compatible code for this call, because with
502 # all of our changes, we've drifted from the pdb api in 2.6. For now,
503 # all of our changes, we've drifted from the pdb api in 2.6. For now,
503 # changing:
504 # changing:
504 #
505 #
505 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
506 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
506 # to:
507 # to:
507 #
508 #
508 line = linecache.getline(filename, lineno)
509 line = linecache.getline(filename, lineno)
509 #
510 #
510 # does the trick. But in reality, we need to fix this by reconciling
511 # does the trick. But in reality, we need to fix this by reconciling
511 # our updates with the new Pdb APIs in Python 2.6.
512 # our updates with the new Pdb APIs in Python 2.6.
512 #
513 #
513 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
514 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
514 #######################################################################
515 #######################################################################
515
516
516 if not line:
517 if not line:
517 print >>self.stdout, 'End of file'
518 print('End of file', file=self.stdout)
518 return 0
519 return 0
519 line = line.strip()
520 line = line.strip()
520 # Don't allow setting breakpoint at a blank line
521 # Don't allow setting breakpoint at a blank line
521 if (not line or (line[0] == '#') or
522 if (not line or (line[0] == '#') or
522 (line[:3] == '"""') or line[:3] == "'''"):
523 (line[:3] == '"""') or line[:3] == "'''"):
523 print >>self.stdout, '*** Blank or comment'
524 print('*** Blank or comment', file=self.stdout)
524 return 0
525 return 0
525 return lineno
526 return lineno
@@ -1,269 +1,270 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
4 This defines a callable class that IPython uses for `sys.displayhook`.
5
5
6 Authors:
6 Authors:
7
7
8 * Fernando Perez
8 * Fernando Perez
9 * Brian Granger
9 * Brian Granger
10 * Robert Kern
10 * Robert Kern
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
14 # Copyright (C) 2008-2011 The IPython Development Team
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 from __future__ import print_function
24
25
25 import __builtin__
26 import __builtin__
26
27
27 from IPython.config.configurable import Configurable
28 from IPython.config.configurable import Configurable
28 from IPython.utils import io
29 from IPython.utils import io
29 from IPython.utils.traitlets import Instance, List
30 from IPython.utils.traitlets import Instance, List
30 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Main displayhook class
34 # Main displayhook class
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35
36
36 # TODO: Move the various attributes (cache_size, [others now moved]). Some
37 # TODO: Move the various attributes (cache_size, [others now moved]). Some
37 # of these are also attributes of InteractiveShell. They should be on ONE object
38 # of these are also attributes of InteractiveShell. They should be on ONE object
38 # only and the other objects should ask that one object for their values.
39 # only and the other objects should ask that one object for their values.
39
40
40 class DisplayHook(Configurable):
41 class DisplayHook(Configurable):
41 """The custom IPython displayhook to replace sys.displayhook.
42 """The custom IPython displayhook to replace sys.displayhook.
42
43
43 This class does many things, but the basic idea is that it is a callable
44 This class does many things, but the basic idea is that it is a callable
44 that gets called anytime user code returns a value.
45 that gets called anytime user code returns a value.
45 """
46 """
46
47
47 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
48 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
48
49
49 def __init__(self, shell=None, cache_size=1000, config=None):
50 def __init__(self, shell=None, cache_size=1000, config=None):
50 super(DisplayHook, self).__init__(shell=shell, config=config)
51 super(DisplayHook, self).__init__(shell=shell, config=config)
51
52
52 cache_size_min = 3
53 cache_size_min = 3
53 if cache_size <= 0:
54 if cache_size <= 0:
54 self.do_full_cache = 0
55 self.do_full_cache = 0
55 cache_size = 0
56 cache_size = 0
56 elif cache_size < cache_size_min:
57 elif cache_size < cache_size_min:
57 self.do_full_cache = 0
58 self.do_full_cache = 0
58 cache_size = 0
59 cache_size = 0
59 warn('caching was disabled (min value for cache size is %s).' %
60 warn('caching was disabled (min value for cache size is %s).' %
60 cache_size_min,level=3)
61 cache_size_min,level=3)
61 else:
62 else:
62 self.do_full_cache = 1
63 self.do_full_cache = 1
63
64
64 self.cache_size = cache_size
65 self.cache_size = cache_size
65
66
66 # we need a reference to the user-level namespace
67 # we need a reference to the user-level namespace
67 self.shell = shell
68 self.shell = shell
68
69
69 self._,self.__,self.___ = '','',''
70 self._,self.__,self.___ = '','',''
70
71
71 # these are deliberately global:
72 # these are deliberately global:
72 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
73 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
73 self.shell.user_ns.update(to_user_ns)
74 self.shell.user_ns.update(to_user_ns)
74
75
75 @property
76 @property
76 def prompt_count(self):
77 def prompt_count(self):
77 return self.shell.execution_count
78 return self.shell.execution_count
78
79
79 #-------------------------------------------------------------------------
80 #-------------------------------------------------------------------------
80 # Methods used in __call__. Override these methods to modify the behavior
81 # Methods used in __call__. Override these methods to modify the behavior
81 # of the displayhook.
82 # of the displayhook.
82 #-------------------------------------------------------------------------
83 #-------------------------------------------------------------------------
83
84
84 def check_for_underscore(self):
85 def check_for_underscore(self):
85 """Check if the user has set the '_' variable by hand."""
86 """Check if the user has set the '_' variable by hand."""
86 # If something injected a '_' variable in __builtin__, delete
87 # If something injected a '_' variable in __builtin__, delete
87 # ipython's automatic one so we don't clobber that. gettext() in
88 # ipython's automatic one so we don't clobber that. gettext() in
88 # particular uses _, so we need to stay away from it.
89 # particular uses _, so we need to stay away from it.
89 if '_' in __builtin__.__dict__:
90 if '_' in __builtin__.__dict__:
90 try:
91 try:
91 del self.shell.user_ns['_']
92 del self.shell.user_ns['_']
92 except KeyError:
93 except KeyError:
93 pass
94 pass
94
95
95 def quiet(self):
96 def quiet(self):
96 """Should we silence the display hook because of ';'?"""
97 """Should we silence the display hook because of ';'?"""
97 # do not print output if input ends in ';'
98 # do not print output if input ends in ';'
98 try:
99 try:
99 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
100 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
100 if cell.rstrip().endswith(';'):
101 if cell.rstrip().endswith(';'):
101 return True
102 return True
102 except IndexError:
103 except IndexError:
103 # some uses of ipshellembed may fail here
104 # some uses of ipshellembed may fail here
104 pass
105 pass
105 return False
106 return False
106
107
107 def start_displayhook(self):
108 def start_displayhook(self):
108 """Start the displayhook, initializing resources."""
109 """Start the displayhook, initializing resources."""
109 pass
110 pass
110
111
111 def write_output_prompt(self):
112 def write_output_prompt(self):
112 """Write the output prompt.
113 """Write the output prompt.
113
114
114 The default implementation simply writes the prompt to
115 The default implementation simply writes the prompt to
115 ``io.stdout``.
116 ``io.stdout``.
116 """
117 """
117 # Use write, not print which adds an extra space.
118 # Use write, not print which adds an extra space.
118 io.stdout.write(self.shell.separate_out)
119 io.stdout.write(self.shell.separate_out)
119 outprompt = self.shell.prompt_manager.render('out')
120 outprompt = self.shell.prompt_manager.render('out')
120 if self.do_full_cache:
121 if self.do_full_cache:
121 io.stdout.write(outprompt)
122 io.stdout.write(outprompt)
122
123
123 def compute_format_data(self, result):
124 def compute_format_data(self, result):
124 """Compute format data of the object to be displayed.
125 """Compute format data of the object to be displayed.
125
126
126 The format data is a generalization of the :func:`repr` of an object.
127 The format data is a generalization of the :func:`repr` of an object.
127 In the default implementation the format data is a :class:`dict` of
128 In the default implementation the format data is a :class:`dict` of
128 key value pair where the keys are valid MIME types and the values
129 key value pair where the keys are valid MIME types and the values
129 are JSON'able data structure containing the raw data for that MIME
130 are JSON'able data structure containing the raw data for that MIME
130 type. It is up to frontends to determine pick a MIME to to use and
131 type. It is up to frontends to determine pick a MIME to to use and
131 display that data in an appropriate manner.
132 display that data in an appropriate manner.
132
133
133 This method only computes the format data for the object and should
134 This method only computes the format data for the object and should
134 NOT actually print or write that to a stream.
135 NOT actually print or write that to a stream.
135
136
136 Parameters
137 Parameters
137 ----------
138 ----------
138 result : object
139 result : object
139 The Python object passed to the display hook, whose format will be
140 The Python object passed to the display hook, whose format will be
140 computed.
141 computed.
141
142
142 Returns
143 Returns
143 -------
144 -------
144 format_data : dict
145 format_data : dict
145 A :class:`dict` whose keys are valid MIME types and values are
146 A :class:`dict` whose keys are valid MIME types and values are
146 JSON'able raw data for that MIME type. It is recommended that
147 JSON'able raw data for that MIME type. It is recommended that
147 all return values of this should always include the "text/plain"
148 all return values of this should always include the "text/plain"
148 MIME type representation of the object.
149 MIME type representation of the object.
149 """
150 """
150 return self.shell.display_formatter.format(result)
151 return self.shell.display_formatter.format(result)
151
152
152 def write_format_data(self, format_dict):
153 def write_format_data(self, format_dict):
153 """Write the format data dict to the frontend.
154 """Write the format data dict to the frontend.
154
155
155 This default version of this method simply writes the plain text
156 This default version of this method simply writes the plain text
156 representation of the object to ``io.stdout``. Subclasses should
157 representation of the object to ``io.stdout``. Subclasses should
157 override this method to send the entire `format_dict` to the
158 override this method to send the entire `format_dict` to the
158 frontends.
159 frontends.
159
160
160 Parameters
161 Parameters
161 ----------
162 ----------
162 format_dict : dict
163 format_dict : dict
163 The format dict for the object passed to `sys.displayhook`.
164 The format dict for the object passed to `sys.displayhook`.
164 """
165 """
165 # We want to print because we want to always make sure we have a
166 # We want to print because we want to always make sure we have a
166 # newline, even if all the prompt separators are ''. This is the
167 # newline, even if all the prompt separators are ''. This is the
167 # standard IPython behavior.
168 # standard IPython behavior.
168 result_repr = format_dict['text/plain']
169 result_repr = format_dict['text/plain']
169 if '\n' in result_repr:
170 if '\n' in result_repr:
170 # So that multi-line strings line up with the left column of
171 # So that multi-line strings line up with the left column of
171 # the screen, instead of having the output prompt mess up
172 # the screen, instead of having the output prompt mess up
172 # their first line.
173 # their first line.
173 # We use the prompt template instead of the expanded prompt
174 # We use the prompt template instead of the expanded prompt
174 # because the expansion may add ANSI escapes that will interfere
175 # because the expansion may add ANSI escapes that will interfere
175 # with our ability to determine whether or not we should add
176 # with our ability to determine whether or not we should add
176 # a newline.
177 # a newline.
177 prompt_template = self.shell.prompt_manager.out_template
178 prompt_template = self.shell.prompt_manager.out_template
178 if prompt_template and not prompt_template.endswith('\n'):
179 if prompt_template and not prompt_template.endswith('\n'):
179 # But avoid extraneous empty lines.
180 # But avoid extraneous empty lines.
180 result_repr = '\n' + result_repr
181 result_repr = '\n' + result_repr
181
182
182 print >>io.stdout, result_repr
183 print(result_repr, file=io.stdout)
183
184
184 def update_user_ns(self, result):
185 def update_user_ns(self, result):
185 """Update user_ns with various things like _, __, _1, etc."""
186 """Update user_ns with various things like _, __, _1, etc."""
186
187
187 # Avoid recursive reference when displaying _oh/Out
188 # Avoid recursive reference when displaying _oh/Out
188 if result is not self.shell.user_ns['_oh']:
189 if result is not self.shell.user_ns['_oh']:
189 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
190 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
190 warn('Output cache limit (currently '+
191 warn('Output cache limit (currently '+
191 `self.cache_size`+' entries) hit.\n'
192 repr(self.cache_size)+' entries) hit.\n'
192 'Flushing cache and resetting history counter...\n'
193 'Flushing cache and resetting history counter...\n'
193 'The only history variables available will be _,__,___ and _1\n'
194 'The only history variables available will be _,__,___ and _1\n'
194 'with the current result.')
195 'with the current result.')
195
196
196 self.flush()
197 self.flush()
197 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
198 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
198 # we cause buggy behavior for things like gettext).
199 # we cause buggy behavior for things like gettext).
199
200
200 if '_' not in __builtin__.__dict__:
201 if '_' not in __builtin__.__dict__:
201 self.___ = self.__
202 self.___ = self.__
202 self.__ = self._
203 self.__ = self._
203 self._ = result
204 self._ = result
204 self.shell.push({'_':self._,
205 self.shell.push({'_':self._,
205 '__':self.__,
206 '__':self.__,
206 '___':self.___}, interactive=False)
207 '___':self.___}, interactive=False)
207
208
208 # hackish access to top-level namespace to create _1,_2... dynamically
209 # hackish access to top-level namespace to create _1,_2... dynamically
209 to_main = {}
210 to_main = {}
210 if self.do_full_cache:
211 if self.do_full_cache:
211 new_result = '_'+`self.prompt_count`
212 new_result = '_'+repr(self.prompt_count)
212 to_main[new_result] = result
213 to_main[new_result] = result
213 self.shell.push(to_main, interactive=False)
214 self.shell.push(to_main, interactive=False)
214 self.shell.user_ns['_oh'][self.prompt_count] = result
215 self.shell.user_ns['_oh'][self.prompt_count] = result
215
216
216 def log_output(self, format_dict):
217 def log_output(self, format_dict):
217 """Log the output."""
218 """Log the output."""
218 if self.shell.logger.log_output:
219 if self.shell.logger.log_output:
219 self.shell.logger.log_write(format_dict['text/plain'], 'output')
220 self.shell.logger.log_write(format_dict['text/plain'], 'output')
220 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
221 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
221 format_dict['text/plain']
222 format_dict['text/plain']
222
223
223 def finish_displayhook(self):
224 def finish_displayhook(self):
224 """Finish up all displayhook activities."""
225 """Finish up all displayhook activities."""
225 io.stdout.write(self.shell.separate_out2)
226 io.stdout.write(self.shell.separate_out2)
226 io.stdout.flush()
227 io.stdout.flush()
227
228
228 def __call__(self, result=None):
229 def __call__(self, result=None):
229 """Printing with history cache management.
230 """Printing with history cache management.
230
231
231 This is invoked everytime the interpreter needs to print, and is
232 This is invoked everytime the interpreter needs to print, and is
232 activated by setting the variable sys.displayhook to it.
233 activated by setting the variable sys.displayhook to it.
233 """
234 """
234 self.check_for_underscore()
235 self.check_for_underscore()
235 if result is not None and not self.quiet():
236 if result is not None and not self.quiet():
236 self.start_displayhook()
237 self.start_displayhook()
237 self.write_output_prompt()
238 self.write_output_prompt()
238 format_dict = self.compute_format_data(result)
239 format_dict = self.compute_format_data(result)
239 self.write_format_data(format_dict)
240 self.write_format_data(format_dict)
240 self.update_user_ns(result)
241 self.update_user_ns(result)
241 self.log_output(format_dict)
242 self.log_output(format_dict)
242 self.finish_displayhook()
243 self.finish_displayhook()
243
244
244 def flush(self):
245 def flush(self):
245 if not self.do_full_cache:
246 if not self.do_full_cache:
246 raise ValueError,"You shouldn't have reached the cache flush "\
247 raise ValueError("You shouldn't have reached the cache flush "
247 "if full caching is not enabled!"
248 "if full caching is not enabled!")
248 # delete auto-generated vars from global namespace
249 # delete auto-generated vars from global namespace
249
250
250 for n in range(1,self.prompt_count + 1):
251 for n in range(1,self.prompt_count + 1):
251 key = '_'+`n`
252 key = '_'+repr(n)
252 try:
253 try:
253 del self.shell.user_ns[key]
254 del self.shell.user_ns[key]
254 except: pass
255 except: pass
255 # In some embedded circumstances, the user_ns doesn't have the
256 # In some embedded circumstances, the user_ns doesn't have the
256 # '_oh' key set up.
257 # '_oh' key set up.
257 oh = self.shell.user_ns.get('_oh', None)
258 oh = self.shell.user_ns.get('_oh', None)
258 if oh is not None:
259 if oh is not None:
259 oh.clear()
260 oh.clear()
260
261
261 # Release our own references to objects:
262 # Release our own references to objects:
262 self._, self.__, self.___ = '', '', ''
263 self._, self.__, self.___ = '', '', ''
263
264
264 if '_' not in __builtin__.__dict__:
265 if '_' not in __builtin__.__dict__:
265 self.shell.user_ns.update({'_':None,'__':None, '___':None})
266 self.shell.user_ns.update({'_':None,'__':None, '___':None})
266 import gc
267 import gc
267 # TODO: Is this really needed?
268 # TODO: Is this really needed?
268 gc.collect()
269 gc.collect()
269
270
@@ -1,3005 +1,3006 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19 from __future__ import print_function
19
20
20 import __builtin__ as builtin_mod
21 import __builtin__ as builtin_mod
21 import __future__
22 import __future__
22 import abc
23 import abc
23 import ast
24 import ast
24 import atexit
25 import atexit
25 import os
26 import os
26 import re
27 import re
27 import runpy
28 import runpy
28 import sys
29 import sys
29 import tempfile
30 import tempfile
30 import types
31 import types
31
32
32 # We need to use nested to support python 2.6, once we move to >=2.7, we can
33 # We need to use nested to support python 2.6, once we move to >=2.7, we can
33 # use the with keyword's new builtin support for nested managers
34 # use the with keyword's new builtin support for nested managers
34 try:
35 try:
35 from contextlib import nested
36 from contextlib import nested
36 except:
37 except:
37 from IPython.utils.nested_context import nested
38 from IPython.utils.nested_context import nested
38
39
39 from IPython.config.configurable import SingletonConfigurable
40 from IPython.config.configurable import SingletonConfigurable
40 from IPython.core import debugger, oinspect
41 from IPython.core import debugger, oinspect
41 from IPython.core import history as ipcorehist
42 from IPython.core import history as ipcorehist
42 from IPython.core import magic
43 from IPython.core import magic
43 from IPython.core import page
44 from IPython.core import page
44 from IPython.core import prefilter
45 from IPython.core import prefilter
45 from IPython.core import shadowns
46 from IPython.core import shadowns
46 from IPython.core import ultratb
47 from IPython.core import ultratb
47 from IPython.core.alias import AliasManager, AliasError
48 from IPython.core.alias import AliasManager, AliasError
48 from IPython.core.autocall import ExitAutocall
49 from IPython.core.autocall import ExitAutocall
49 from IPython.core.builtin_trap import BuiltinTrap
50 from IPython.core.builtin_trap import BuiltinTrap
50 from IPython.core.compilerop import CachingCompiler
51 from IPython.core.compilerop import CachingCompiler
51 from IPython.core.display_trap import DisplayTrap
52 from IPython.core.display_trap import DisplayTrap
52 from IPython.core.displayhook import DisplayHook
53 from IPython.core.displayhook import DisplayHook
53 from IPython.core.displaypub import DisplayPublisher
54 from IPython.core.displaypub import DisplayPublisher
54 from IPython.core.error import UsageError
55 from IPython.core.error import UsageError
55 from IPython.core.extensions import ExtensionManager
56 from IPython.core.extensions import ExtensionManager
56 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
57 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
57 from IPython.core.formatters import DisplayFormatter
58 from IPython.core.formatters import DisplayFormatter
58 from IPython.core.history import HistoryManager
59 from IPython.core.history import HistoryManager
59 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
60 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
60 from IPython.core.logger import Logger
61 from IPython.core.logger import Logger
61 from IPython.core.macro import Macro
62 from IPython.core.macro import Macro
62 from IPython.core.payload import PayloadManager
63 from IPython.core.payload import PayloadManager
63 from IPython.core.plugin import PluginManager
64 from IPython.core.plugin import PluginManager
64 from IPython.core.prefilter import PrefilterManager
65 from IPython.core.prefilter import PrefilterManager
65 from IPython.core.profiledir import ProfileDir
66 from IPython.core.profiledir import ProfileDir
66 from IPython.core.pylabtools import pylab_activate
67 from IPython.core.pylabtools import pylab_activate
67 from IPython.core.prompts import PromptManager
68 from IPython.core.prompts import PromptManager
68 from IPython.utils import PyColorize
69 from IPython.utils import PyColorize
69 from IPython.utils import io
70 from IPython.utils import io
70 from IPython.utils import py3compat
71 from IPython.utils import py3compat
71 from IPython.utils import openpy
72 from IPython.utils import openpy
72 from IPython.utils.doctestreload import doctest_reload
73 from IPython.utils.doctestreload import doctest_reload
73 from IPython.utils.io import ask_yes_no
74 from IPython.utils.io import ask_yes_no
74 from IPython.utils.ipstruct import Struct
75 from IPython.utils.ipstruct import Struct
75 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
76 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
76 from IPython.utils.pickleshare import PickleShareDB
77 from IPython.utils.pickleshare import PickleShareDB
77 from IPython.utils.process import system, getoutput
78 from IPython.utils.process import system, getoutput
78 from IPython.utils.strdispatch import StrDispatch
79 from IPython.utils.strdispatch import StrDispatch
79 from IPython.utils.syspathcontext import prepended_to_syspath
80 from IPython.utils.syspathcontext import prepended_to_syspath
80 from IPython.utils.text import (format_screen, LSString, SList,
81 from IPython.utils.text import (format_screen, LSString, SList,
81 DollarFormatter)
82 DollarFormatter)
82 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
83 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
83 List, Unicode, Instance, Type)
84 List, Unicode, Instance, Type)
84 from IPython.utils.warn import warn, error
85 from IPython.utils.warn import warn, error
85 import IPython.core.hooks
86 import IPython.core.hooks
86
87
87 # FIXME: do this in a function to avoid circular dependencies
88 # FIXME: do this in a function to avoid circular dependencies
88 # A better solution is to remove IPython.parallel.error,
89 # A better solution is to remove IPython.parallel.error,
89 # and place those classes in IPython.core.error.
90 # and place those classes in IPython.core.error.
90
91
91 class RemoteError(Exception):
92 class RemoteError(Exception):
92 pass
93 pass
93
94
94 def _import_remote_error():
95 def _import_remote_error():
95 global RemoteError
96 global RemoteError
96 try:
97 try:
97 from IPython.parallel.error import RemoteError
98 from IPython.parallel.error import RemoteError
98 except:
99 except:
99 pass
100 pass
100
101
101 _import_remote_error()
102 _import_remote_error()
102
103
103 #-----------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------
104 # Globals
105 # Globals
105 #-----------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------
106
107
107 # compiled regexps for autoindent management
108 # compiled regexps for autoindent management
108 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
109 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
109
110
110 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
111 # Utilities
112 # Utilities
112 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
113
114
114 def softspace(file, newvalue):
115 def softspace(file, newvalue):
115 """Copied from code.py, to remove the dependency"""
116 """Copied from code.py, to remove the dependency"""
116
117
117 oldvalue = 0
118 oldvalue = 0
118 try:
119 try:
119 oldvalue = file.softspace
120 oldvalue = file.softspace
120 except AttributeError:
121 except AttributeError:
121 pass
122 pass
122 try:
123 try:
123 file.softspace = newvalue
124 file.softspace = newvalue
124 except (AttributeError, TypeError):
125 except (AttributeError, TypeError):
125 # "attribute-less object" or "read-only attributes"
126 # "attribute-less object" or "read-only attributes"
126 pass
127 pass
127 return oldvalue
128 return oldvalue
128
129
129
130
130 def no_op(*a, **kw): pass
131 def no_op(*a, **kw): pass
131
132
132 class NoOpContext(object):
133 class NoOpContext(object):
133 def __enter__(self): pass
134 def __enter__(self): pass
134 def __exit__(self, type, value, traceback): pass
135 def __exit__(self, type, value, traceback): pass
135 no_op_context = NoOpContext()
136 no_op_context = NoOpContext()
136
137
137 class SpaceInInput(Exception): pass
138 class SpaceInInput(Exception): pass
138
139
139 class Bunch: pass
140 class Bunch: pass
140
141
141
142
142 def get_default_colors():
143 def get_default_colors():
143 if sys.platform=='darwin':
144 if sys.platform=='darwin':
144 return "LightBG"
145 return "LightBG"
145 elif os.name=='nt':
146 elif os.name=='nt':
146 return 'Linux'
147 return 'Linux'
147 else:
148 else:
148 return 'Linux'
149 return 'Linux'
149
150
150
151
151 class SeparateUnicode(Unicode):
152 class SeparateUnicode(Unicode):
152 """A Unicode subclass to validate separate_in, separate_out, etc.
153 """A Unicode subclass to validate separate_in, separate_out, etc.
153
154
154 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
155 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
155 """
156 """
156
157
157 def validate(self, obj, value):
158 def validate(self, obj, value):
158 if value == '0': value = ''
159 if value == '0': value = ''
159 value = value.replace('\\n','\n')
160 value = value.replace('\\n','\n')
160 return super(SeparateUnicode, self).validate(obj, value)
161 return super(SeparateUnicode, self).validate(obj, value)
161
162
162
163
163 class ReadlineNoRecord(object):
164 class ReadlineNoRecord(object):
164 """Context manager to execute some code, then reload readline history
165 """Context manager to execute some code, then reload readline history
165 so that interactive input to the code doesn't appear when pressing up."""
166 so that interactive input to the code doesn't appear when pressing up."""
166 def __init__(self, shell):
167 def __init__(self, shell):
167 self.shell = shell
168 self.shell = shell
168 self._nested_level = 0
169 self._nested_level = 0
169
170
170 def __enter__(self):
171 def __enter__(self):
171 if self._nested_level == 0:
172 if self._nested_level == 0:
172 try:
173 try:
173 self.orig_length = self.current_length()
174 self.orig_length = self.current_length()
174 self.readline_tail = self.get_readline_tail()
175 self.readline_tail = self.get_readline_tail()
175 except (AttributeError, IndexError): # Can fail with pyreadline
176 except (AttributeError, IndexError): # Can fail with pyreadline
176 self.orig_length, self.readline_tail = 999999, []
177 self.orig_length, self.readline_tail = 999999, []
177 self._nested_level += 1
178 self._nested_level += 1
178
179
179 def __exit__(self, type, value, traceback):
180 def __exit__(self, type, value, traceback):
180 self._nested_level -= 1
181 self._nested_level -= 1
181 if self._nested_level == 0:
182 if self._nested_level == 0:
182 # Try clipping the end if it's got longer
183 # Try clipping the end if it's got longer
183 try:
184 try:
184 e = self.current_length() - self.orig_length
185 e = self.current_length() - self.orig_length
185 if e > 0:
186 if e > 0:
186 for _ in range(e):
187 for _ in range(e):
187 self.shell.readline.remove_history_item(self.orig_length)
188 self.shell.readline.remove_history_item(self.orig_length)
188
189
189 # If it still doesn't match, just reload readline history.
190 # If it still doesn't match, just reload readline history.
190 if self.current_length() != self.orig_length \
191 if self.current_length() != self.orig_length \
191 or self.get_readline_tail() != self.readline_tail:
192 or self.get_readline_tail() != self.readline_tail:
192 self.shell.refill_readline_hist()
193 self.shell.refill_readline_hist()
193 except (AttributeError, IndexError):
194 except (AttributeError, IndexError):
194 pass
195 pass
195 # Returning False will cause exceptions to propagate
196 # Returning False will cause exceptions to propagate
196 return False
197 return False
197
198
198 def current_length(self):
199 def current_length(self):
199 return self.shell.readline.get_current_history_length()
200 return self.shell.readline.get_current_history_length()
200
201
201 def get_readline_tail(self, n=10):
202 def get_readline_tail(self, n=10):
202 """Get the last n items in readline history."""
203 """Get the last n items in readline history."""
203 end = self.shell.readline.get_current_history_length() + 1
204 end = self.shell.readline.get_current_history_length() + 1
204 start = max(end-n, 1)
205 start = max(end-n, 1)
205 ghi = self.shell.readline.get_history_item
206 ghi = self.shell.readline.get_history_item
206 return [ghi(x) for x in range(start, end)]
207 return [ghi(x) for x in range(start, end)]
207
208
208 #-----------------------------------------------------------------------------
209 #-----------------------------------------------------------------------------
209 # Main IPython class
210 # Main IPython class
210 #-----------------------------------------------------------------------------
211 #-----------------------------------------------------------------------------
211
212
212 class InteractiveShell(SingletonConfigurable):
213 class InteractiveShell(SingletonConfigurable):
213 """An enhanced, interactive shell for Python."""
214 """An enhanced, interactive shell for Python."""
214
215
215 _instance = None
216 _instance = None
216
217
217 autocall = Enum((0,1,2), default_value=0, config=True, help=
218 autocall = Enum((0,1,2), default_value=0, config=True, help=
218 """
219 """
219 Make IPython automatically call any callable object even if you didn't
220 Make IPython automatically call any callable object even if you didn't
220 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
221 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
221 automatically. The value can be '0' to disable the feature, '1' for
222 automatically. The value can be '0' to disable the feature, '1' for
222 'smart' autocall, where it is not applied if there are no more
223 'smart' autocall, where it is not applied if there are no more
223 arguments on the line, and '2' for 'full' autocall, where all callable
224 arguments on the line, and '2' for 'full' autocall, where all callable
224 objects are automatically called (even if no arguments are present).
225 objects are automatically called (even if no arguments are present).
225 """
226 """
226 )
227 )
227 # TODO: remove all autoindent logic and put into frontends.
228 # TODO: remove all autoindent logic and put into frontends.
228 # We can't do this yet because even runlines uses the autoindent.
229 # We can't do this yet because even runlines uses the autoindent.
229 autoindent = CBool(True, config=True, help=
230 autoindent = CBool(True, config=True, help=
230 """
231 """
231 Autoindent IPython code entered interactively.
232 Autoindent IPython code entered interactively.
232 """
233 """
233 )
234 )
234 automagic = CBool(True, config=True, help=
235 automagic = CBool(True, config=True, help=
235 """
236 """
236 Enable magic commands to be called without the leading %.
237 Enable magic commands to be called without the leading %.
237 """
238 """
238 )
239 )
239 cache_size = Integer(1000, config=True, help=
240 cache_size = Integer(1000, config=True, help=
240 """
241 """
241 Set the size of the output cache. The default is 1000, you can
242 Set the size of the output cache. The default is 1000, you can
242 change it permanently in your config file. Setting it to 0 completely
243 change it permanently in your config file. Setting it to 0 completely
243 disables the caching system, and the minimum value accepted is 20 (if
244 disables the caching system, and the minimum value accepted is 20 (if
244 you provide a value less than 20, it is reset to 0 and a warning is
245 you provide a value less than 20, it is reset to 0 and a warning is
245 issued). This limit is defined because otherwise you'll spend more
246 issued). This limit is defined because otherwise you'll spend more
246 time re-flushing a too small cache than working
247 time re-flushing a too small cache than working
247 """
248 """
248 )
249 )
249 color_info = CBool(True, config=True, help=
250 color_info = CBool(True, config=True, help=
250 """
251 """
251 Use colors for displaying information about objects. Because this
252 Use colors for displaying information about objects. Because this
252 information is passed through a pager (like 'less'), and some pagers
253 information is passed through a pager (like 'less'), and some pagers
253 get confused with color codes, this capability can be turned off.
254 get confused with color codes, this capability can be turned off.
254 """
255 """
255 )
256 )
256 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
257 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
257 default_value=get_default_colors(), config=True,
258 default_value=get_default_colors(), config=True,
258 help="Set the color scheme (NoColor, Linux, or LightBG)."
259 help="Set the color scheme (NoColor, Linux, or LightBG)."
259 )
260 )
260 colors_force = CBool(False, help=
261 colors_force = CBool(False, help=
261 """
262 """
262 Force use of ANSI color codes, regardless of OS and readline
263 Force use of ANSI color codes, regardless of OS and readline
263 availability.
264 availability.
264 """
265 """
265 # FIXME: This is essentially a hack to allow ZMQShell to show colors
266 # FIXME: This is essentially a hack to allow ZMQShell to show colors
266 # without readline on Win32. When the ZMQ formatting system is
267 # without readline on Win32. When the ZMQ formatting system is
267 # refactored, this should be removed.
268 # refactored, this should be removed.
268 )
269 )
269 debug = CBool(False, config=True)
270 debug = CBool(False, config=True)
270 deep_reload = CBool(False, config=True, help=
271 deep_reload = CBool(False, config=True, help=
271 """
272 """
272 Enable deep (recursive) reloading by default. IPython can use the
273 Enable deep (recursive) reloading by default. IPython can use the
273 deep_reload module which reloads changes in modules recursively (it
274 deep_reload module which reloads changes in modules recursively (it
274 replaces the reload() function, so you don't need to change anything to
275 replaces the reload() function, so you don't need to change anything to
275 use it). deep_reload() forces a full reload of modules whose code may
276 use it). deep_reload() forces a full reload of modules whose code may
276 have changed, which the default reload() function does not. When
277 have changed, which the default reload() function does not. When
277 deep_reload is off, IPython will use the normal reload(), but
278 deep_reload is off, IPython will use the normal reload(), but
278 deep_reload will still be available as dreload().
279 deep_reload will still be available as dreload().
279 """
280 """
280 )
281 )
281 disable_failing_post_execute = CBool(False, config=True,
282 disable_failing_post_execute = CBool(False, config=True,
282 help="Don't call post-execute functions that have failed in the past."
283 help="Don't call post-execute functions that have failed in the past."
283 )
284 )
284 display_formatter = Instance(DisplayFormatter)
285 display_formatter = Instance(DisplayFormatter)
285 displayhook_class = Type(DisplayHook)
286 displayhook_class = Type(DisplayHook)
286 display_pub_class = Type(DisplayPublisher)
287 display_pub_class = Type(DisplayPublisher)
287
288
288 exit_now = CBool(False)
289 exit_now = CBool(False)
289 exiter = Instance(ExitAutocall)
290 exiter = Instance(ExitAutocall)
290 def _exiter_default(self):
291 def _exiter_default(self):
291 return ExitAutocall(self)
292 return ExitAutocall(self)
292 # Monotonically increasing execution counter
293 # Monotonically increasing execution counter
293 execution_count = Integer(1)
294 execution_count = Integer(1)
294 filename = Unicode("<ipython console>")
295 filename = Unicode("<ipython console>")
295 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
296 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
296
297
297 # Input splitter, to split entire cells of input into either individual
298 # Input splitter, to split entire cells of input into either individual
298 # interactive statements or whole blocks.
299 # interactive statements or whole blocks.
299 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
300 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
300 (), {})
301 (), {})
301 logstart = CBool(False, config=True, help=
302 logstart = CBool(False, config=True, help=
302 """
303 """
303 Start logging to the default log file.
304 Start logging to the default log file.
304 """
305 """
305 )
306 )
306 logfile = Unicode('', config=True, help=
307 logfile = Unicode('', config=True, help=
307 """
308 """
308 The name of the logfile to use.
309 The name of the logfile to use.
309 """
310 """
310 )
311 )
311 logappend = Unicode('', config=True, help=
312 logappend = Unicode('', config=True, help=
312 """
313 """
313 Start logging to the given file in append mode.
314 Start logging to the given file in append mode.
314 """
315 """
315 )
316 )
316 object_info_string_level = Enum((0,1,2), default_value=0,
317 object_info_string_level = Enum((0,1,2), default_value=0,
317 config=True)
318 config=True)
318 pdb = CBool(False, config=True, help=
319 pdb = CBool(False, config=True, help=
319 """
320 """
320 Automatically call the pdb debugger after every exception.
321 Automatically call the pdb debugger after every exception.
321 """
322 """
322 )
323 )
323 multiline_history = CBool(sys.platform != 'win32', config=True,
324 multiline_history = CBool(sys.platform != 'win32', config=True,
324 help="Save multi-line entries as one entry in readline history"
325 help="Save multi-line entries as one entry in readline history"
325 )
326 )
326
327
327 # deprecated prompt traits:
328 # deprecated prompt traits:
328
329
329 prompt_in1 = Unicode('In [\\#]: ', config=True,
330 prompt_in1 = Unicode('In [\\#]: ', config=True,
330 help="Deprecated, use PromptManager.in_template")
331 help="Deprecated, use PromptManager.in_template")
331 prompt_in2 = Unicode(' .\\D.: ', config=True,
332 prompt_in2 = Unicode(' .\\D.: ', config=True,
332 help="Deprecated, use PromptManager.in2_template")
333 help="Deprecated, use PromptManager.in2_template")
333 prompt_out = Unicode('Out[\\#]: ', config=True,
334 prompt_out = Unicode('Out[\\#]: ', config=True,
334 help="Deprecated, use PromptManager.out_template")
335 help="Deprecated, use PromptManager.out_template")
335 prompts_pad_left = CBool(True, config=True,
336 prompts_pad_left = CBool(True, config=True,
336 help="Deprecated, use PromptManager.justify")
337 help="Deprecated, use PromptManager.justify")
337
338
338 def _prompt_trait_changed(self, name, old, new):
339 def _prompt_trait_changed(self, name, old, new):
339 table = {
340 table = {
340 'prompt_in1' : 'in_template',
341 'prompt_in1' : 'in_template',
341 'prompt_in2' : 'in2_template',
342 'prompt_in2' : 'in2_template',
342 'prompt_out' : 'out_template',
343 'prompt_out' : 'out_template',
343 'prompts_pad_left' : 'justify',
344 'prompts_pad_left' : 'justify',
344 }
345 }
345 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
346 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
346 name=name, newname=table[name])
347 name=name, newname=table[name])
347 )
348 )
348 # protect against weird cases where self.config may not exist:
349 # protect against weird cases where self.config may not exist:
349 if self.config is not None:
350 if self.config is not None:
350 # propagate to corresponding PromptManager trait
351 # propagate to corresponding PromptManager trait
351 setattr(self.config.PromptManager, table[name], new)
352 setattr(self.config.PromptManager, table[name], new)
352
353
353 _prompt_in1_changed = _prompt_trait_changed
354 _prompt_in1_changed = _prompt_trait_changed
354 _prompt_in2_changed = _prompt_trait_changed
355 _prompt_in2_changed = _prompt_trait_changed
355 _prompt_out_changed = _prompt_trait_changed
356 _prompt_out_changed = _prompt_trait_changed
356 _prompt_pad_left_changed = _prompt_trait_changed
357 _prompt_pad_left_changed = _prompt_trait_changed
357
358
358 show_rewritten_input = CBool(True, config=True,
359 show_rewritten_input = CBool(True, config=True,
359 help="Show rewritten input, e.g. for autocall."
360 help="Show rewritten input, e.g. for autocall."
360 )
361 )
361
362
362 quiet = CBool(False, config=True)
363 quiet = CBool(False, config=True)
363
364
364 history_length = Integer(10000, config=True)
365 history_length = Integer(10000, config=True)
365
366
366 # The readline stuff will eventually be moved to the terminal subclass
367 # The readline stuff will eventually be moved to the terminal subclass
367 # but for now, we can't do that as readline is welded in everywhere.
368 # but for now, we can't do that as readline is welded in everywhere.
368 readline_use = CBool(True, config=True)
369 readline_use = CBool(True, config=True)
369 readline_remove_delims = Unicode('-/~', config=True)
370 readline_remove_delims = Unicode('-/~', config=True)
370 # don't use \M- bindings by default, because they
371 # don't use \M- bindings by default, because they
371 # conflict with 8-bit encodings. See gh-58,gh-88
372 # conflict with 8-bit encodings. See gh-58,gh-88
372 readline_parse_and_bind = List([
373 readline_parse_and_bind = List([
373 'tab: complete',
374 'tab: complete',
374 '"\C-l": clear-screen',
375 '"\C-l": clear-screen',
375 'set show-all-if-ambiguous on',
376 'set show-all-if-ambiguous on',
376 '"\C-o": tab-insert',
377 '"\C-o": tab-insert',
377 '"\C-r": reverse-search-history',
378 '"\C-r": reverse-search-history',
378 '"\C-s": forward-search-history',
379 '"\C-s": forward-search-history',
379 '"\C-p": history-search-backward',
380 '"\C-p": history-search-backward',
380 '"\C-n": history-search-forward',
381 '"\C-n": history-search-forward',
381 '"\e[A": history-search-backward',
382 '"\e[A": history-search-backward',
382 '"\e[B": history-search-forward',
383 '"\e[B": history-search-forward',
383 '"\C-k": kill-line',
384 '"\C-k": kill-line',
384 '"\C-u": unix-line-discard',
385 '"\C-u": unix-line-discard',
385 ], allow_none=False, config=True)
386 ], allow_none=False, config=True)
386
387
387 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
388 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
388 default_value='last_expr', config=True,
389 default_value='last_expr', config=True,
389 help="""
390 help="""
390 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
391 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
391 run interactively (displaying output from expressions).""")
392 run interactively (displaying output from expressions).""")
392
393
393 # TODO: this part of prompt management should be moved to the frontends.
394 # TODO: this part of prompt management should be moved to the frontends.
394 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
395 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
395 separate_in = SeparateUnicode('\n', config=True)
396 separate_in = SeparateUnicode('\n', config=True)
396 separate_out = SeparateUnicode('', config=True)
397 separate_out = SeparateUnicode('', config=True)
397 separate_out2 = SeparateUnicode('', config=True)
398 separate_out2 = SeparateUnicode('', config=True)
398 wildcards_case_sensitive = CBool(True, config=True)
399 wildcards_case_sensitive = CBool(True, config=True)
399 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
400 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
400 default_value='Context', config=True)
401 default_value='Context', config=True)
401
402
402 # Subcomponents of InteractiveShell
403 # Subcomponents of InteractiveShell
403 alias_manager = Instance('IPython.core.alias.AliasManager')
404 alias_manager = Instance('IPython.core.alias.AliasManager')
404 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
405 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
405 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
406 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
406 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
407 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
407 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
408 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
408 plugin_manager = Instance('IPython.core.plugin.PluginManager')
409 plugin_manager = Instance('IPython.core.plugin.PluginManager')
409 payload_manager = Instance('IPython.core.payload.PayloadManager')
410 payload_manager = Instance('IPython.core.payload.PayloadManager')
410 history_manager = Instance('IPython.core.history.HistoryManager')
411 history_manager = Instance('IPython.core.history.HistoryManager')
411 magics_manager = Instance('IPython.core.magic.MagicsManager')
412 magics_manager = Instance('IPython.core.magic.MagicsManager')
412
413
413 profile_dir = Instance('IPython.core.application.ProfileDir')
414 profile_dir = Instance('IPython.core.application.ProfileDir')
414 @property
415 @property
415 def profile(self):
416 def profile(self):
416 if self.profile_dir is not None:
417 if self.profile_dir is not None:
417 name = os.path.basename(self.profile_dir.location)
418 name = os.path.basename(self.profile_dir.location)
418 return name.replace('profile_','')
419 return name.replace('profile_','')
419
420
420
421
421 # Private interface
422 # Private interface
422 _post_execute = Instance(dict)
423 _post_execute = Instance(dict)
423
424
424 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
425 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
425 user_module=None, user_ns=None,
426 user_module=None, user_ns=None,
426 custom_exceptions=((), None)):
427 custom_exceptions=((), None)):
427
428
428 # This is where traits with a config_key argument are updated
429 # This is where traits with a config_key argument are updated
429 # from the values on config.
430 # from the values on config.
430 super(InteractiveShell, self).__init__(config=config)
431 super(InteractiveShell, self).__init__(config=config)
431 self.configurables = [self]
432 self.configurables = [self]
432
433
433 # These are relatively independent and stateless
434 # These are relatively independent and stateless
434 self.init_ipython_dir(ipython_dir)
435 self.init_ipython_dir(ipython_dir)
435 self.init_profile_dir(profile_dir)
436 self.init_profile_dir(profile_dir)
436 self.init_instance_attrs()
437 self.init_instance_attrs()
437 self.init_environment()
438 self.init_environment()
438
439
439 # Check if we're in a virtualenv, and set up sys.path.
440 # Check if we're in a virtualenv, and set up sys.path.
440 self.init_virtualenv()
441 self.init_virtualenv()
441
442
442 # Create namespaces (user_ns, user_global_ns, etc.)
443 # Create namespaces (user_ns, user_global_ns, etc.)
443 self.init_create_namespaces(user_module, user_ns)
444 self.init_create_namespaces(user_module, user_ns)
444 # This has to be done after init_create_namespaces because it uses
445 # This has to be done after init_create_namespaces because it uses
445 # something in self.user_ns, but before init_sys_modules, which
446 # something in self.user_ns, but before init_sys_modules, which
446 # is the first thing to modify sys.
447 # is the first thing to modify sys.
447 # TODO: When we override sys.stdout and sys.stderr before this class
448 # TODO: When we override sys.stdout and sys.stderr before this class
448 # is created, we are saving the overridden ones here. Not sure if this
449 # is created, we are saving the overridden ones here. Not sure if this
449 # is what we want to do.
450 # is what we want to do.
450 self.save_sys_module_state()
451 self.save_sys_module_state()
451 self.init_sys_modules()
452 self.init_sys_modules()
452
453
453 # While we're trying to have each part of the code directly access what
454 # While we're trying to have each part of the code directly access what
454 # it needs without keeping redundant references to objects, we have too
455 # it needs without keeping redundant references to objects, we have too
455 # much legacy code that expects ip.db to exist.
456 # much legacy code that expects ip.db to exist.
456 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
457 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
457
458
458 self.init_history()
459 self.init_history()
459 self.init_encoding()
460 self.init_encoding()
460 self.init_prefilter()
461 self.init_prefilter()
461
462
462 self.init_syntax_highlighting()
463 self.init_syntax_highlighting()
463 self.init_hooks()
464 self.init_hooks()
464 self.init_pushd_popd_magic()
465 self.init_pushd_popd_magic()
465 # self.init_traceback_handlers use to be here, but we moved it below
466 # self.init_traceback_handlers use to be here, but we moved it below
466 # because it and init_io have to come after init_readline.
467 # because it and init_io have to come after init_readline.
467 self.init_user_ns()
468 self.init_user_ns()
468 self.init_logger()
469 self.init_logger()
469 self.init_alias()
470 self.init_alias()
470 self.init_builtins()
471 self.init_builtins()
471
472
472 # The following was in post_config_initialization
473 # The following was in post_config_initialization
473 self.init_inspector()
474 self.init_inspector()
474 # init_readline() must come before init_io(), because init_io uses
475 # init_readline() must come before init_io(), because init_io uses
475 # readline related things.
476 # readline related things.
476 self.init_readline()
477 self.init_readline()
477 # We save this here in case user code replaces raw_input, but it needs
478 # We save this here in case user code replaces raw_input, but it needs
478 # to be after init_readline(), because PyPy's readline works by replacing
479 # to be after init_readline(), because PyPy's readline works by replacing
479 # raw_input.
480 # raw_input.
480 if py3compat.PY3:
481 if py3compat.PY3:
481 self.raw_input_original = input
482 self.raw_input_original = input
482 else:
483 else:
483 self.raw_input_original = raw_input
484 self.raw_input_original = raw_input
484 # init_completer must come after init_readline, because it needs to
485 # init_completer must come after init_readline, because it needs to
485 # know whether readline is present or not system-wide to configure the
486 # know whether readline is present or not system-wide to configure the
486 # completers, since the completion machinery can now operate
487 # completers, since the completion machinery can now operate
487 # independently of readline (e.g. over the network)
488 # independently of readline (e.g. over the network)
488 self.init_completer()
489 self.init_completer()
489 # TODO: init_io() needs to happen before init_traceback handlers
490 # TODO: init_io() needs to happen before init_traceback handlers
490 # because the traceback handlers hardcode the stdout/stderr streams.
491 # because the traceback handlers hardcode the stdout/stderr streams.
491 # This logic in in debugger.Pdb and should eventually be changed.
492 # This logic in in debugger.Pdb and should eventually be changed.
492 self.init_io()
493 self.init_io()
493 self.init_traceback_handlers(custom_exceptions)
494 self.init_traceback_handlers(custom_exceptions)
494 self.init_prompts()
495 self.init_prompts()
495 self.init_display_formatter()
496 self.init_display_formatter()
496 self.init_display_pub()
497 self.init_display_pub()
497 self.init_displayhook()
498 self.init_displayhook()
498 self.init_reload_doctest()
499 self.init_reload_doctest()
499 self.init_magics()
500 self.init_magics()
500 self.init_logstart()
501 self.init_logstart()
501 self.init_pdb()
502 self.init_pdb()
502 self.init_extension_manager()
503 self.init_extension_manager()
503 self.init_plugin_manager()
504 self.init_plugin_manager()
504 self.init_payload()
505 self.init_payload()
505 self.hooks.late_startup_hook()
506 self.hooks.late_startup_hook()
506 atexit.register(self.atexit_operations)
507 atexit.register(self.atexit_operations)
507
508
508 def get_ipython(self):
509 def get_ipython(self):
509 """Return the currently running IPython instance."""
510 """Return the currently running IPython instance."""
510 return self
511 return self
511
512
512 #-------------------------------------------------------------------------
513 #-------------------------------------------------------------------------
513 # Trait changed handlers
514 # Trait changed handlers
514 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
515
516
516 def _ipython_dir_changed(self, name, new):
517 def _ipython_dir_changed(self, name, new):
517 if not os.path.isdir(new):
518 if not os.path.isdir(new):
518 os.makedirs(new, mode = 0777)
519 os.makedirs(new, mode = 0777)
519
520
520 def set_autoindent(self,value=None):
521 def set_autoindent(self,value=None):
521 """Set the autoindent flag, checking for readline support.
522 """Set the autoindent flag, checking for readline support.
522
523
523 If called with no arguments, it acts as a toggle."""
524 If called with no arguments, it acts as a toggle."""
524
525
525 if value != 0 and not self.has_readline:
526 if value != 0 and not self.has_readline:
526 if os.name == 'posix':
527 if os.name == 'posix':
527 warn("The auto-indent feature requires the readline library")
528 warn("The auto-indent feature requires the readline library")
528 self.autoindent = 0
529 self.autoindent = 0
529 return
530 return
530 if value is None:
531 if value is None:
531 self.autoindent = not self.autoindent
532 self.autoindent = not self.autoindent
532 else:
533 else:
533 self.autoindent = value
534 self.autoindent = value
534
535
535 #-------------------------------------------------------------------------
536 #-------------------------------------------------------------------------
536 # init_* methods called by __init__
537 # init_* methods called by __init__
537 #-------------------------------------------------------------------------
538 #-------------------------------------------------------------------------
538
539
539 def init_ipython_dir(self, ipython_dir):
540 def init_ipython_dir(self, ipython_dir):
540 if ipython_dir is not None:
541 if ipython_dir is not None:
541 self.ipython_dir = ipython_dir
542 self.ipython_dir = ipython_dir
542 return
543 return
543
544
544 self.ipython_dir = get_ipython_dir()
545 self.ipython_dir = get_ipython_dir()
545
546
546 def init_profile_dir(self, profile_dir):
547 def init_profile_dir(self, profile_dir):
547 if profile_dir is not None:
548 if profile_dir is not None:
548 self.profile_dir = profile_dir
549 self.profile_dir = profile_dir
549 return
550 return
550 self.profile_dir =\
551 self.profile_dir =\
551 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
552 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
552
553
553 def init_instance_attrs(self):
554 def init_instance_attrs(self):
554 self.more = False
555 self.more = False
555
556
556 # command compiler
557 # command compiler
557 self.compile = CachingCompiler()
558 self.compile = CachingCompiler()
558
559
559 # Make an empty namespace, which extension writers can rely on both
560 # Make an empty namespace, which extension writers can rely on both
560 # existing and NEVER being used by ipython itself. This gives them a
561 # existing and NEVER being used by ipython itself. This gives them a
561 # convenient location for storing additional information and state
562 # convenient location for storing additional information and state
562 # their extensions may require, without fear of collisions with other
563 # their extensions may require, without fear of collisions with other
563 # ipython names that may develop later.
564 # ipython names that may develop later.
564 self.meta = Struct()
565 self.meta = Struct()
565
566
566 # Temporary files used for various purposes. Deleted at exit.
567 # Temporary files used for various purposes. Deleted at exit.
567 self.tempfiles = []
568 self.tempfiles = []
568
569
569 # Keep track of readline usage (later set by init_readline)
570 # Keep track of readline usage (later set by init_readline)
570 self.has_readline = False
571 self.has_readline = False
571
572
572 # keep track of where we started running (mainly for crash post-mortem)
573 # keep track of where we started running (mainly for crash post-mortem)
573 # This is not being used anywhere currently.
574 # This is not being used anywhere currently.
574 self.starting_dir = os.getcwdu()
575 self.starting_dir = os.getcwdu()
575
576
576 # Indentation management
577 # Indentation management
577 self.indent_current_nsp = 0
578 self.indent_current_nsp = 0
578
579
579 # Dict to track post-execution functions that have been registered
580 # Dict to track post-execution functions that have been registered
580 self._post_execute = {}
581 self._post_execute = {}
581
582
582 def init_environment(self):
583 def init_environment(self):
583 """Any changes we need to make to the user's environment."""
584 """Any changes we need to make to the user's environment."""
584 pass
585 pass
585
586
586 def init_encoding(self):
587 def init_encoding(self):
587 # Get system encoding at startup time. Certain terminals (like Emacs
588 # Get system encoding at startup time. Certain terminals (like Emacs
588 # under Win32 have it set to None, and we need to have a known valid
589 # under Win32 have it set to None, and we need to have a known valid
589 # encoding to use in the raw_input() method
590 # encoding to use in the raw_input() method
590 try:
591 try:
591 self.stdin_encoding = sys.stdin.encoding or 'ascii'
592 self.stdin_encoding = sys.stdin.encoding or 'ascii'
592 except AttributeError:
593 except AttributeError:
593 self.stdin_encoding = 'ascii'
594 self.stdin_encoding = 'ascii'
594
595
595 def init_syntax_highlighting(self):
596 def init_syntax_highlighting(self):
596 # Python source parser/formatter for syntax highlighting
597 # Python source parser/formatter for syntax highlighting
597 pyformat = PyColorize.Parser().format
598 pyformat = PyColorize.Parser().format
598 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
599 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
599
600
600 def init_pushd_popd_magic(self):
601 def init_pushd_popd_magic(self):
601 # for pushd/popd management
602 # for pushd/popd management
602 self.home_dir = get_home_dir()
603 self.home_dir = get_home_dir()
603
604
604 self.dir_stack = []
605 self.dir_stack = []
605
606
606 def init_logger(self):
607 def init_logger(self):
607 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
608 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
608 logmode='rotate')
609 logmode='rotate')
609
610
610 def init_logstart(self):
611 def init_logstart(self):
611 """Initialize logging in case it was requested at the command line.
612 """Initialize logging in case it was requested at the command line.
612 """
613 """
613 if self.logappend:
614 if self.logappend:
614 self.magic('logstart %s append' % self.logappend)
615 self.magic('logstart %s append' % self.logappend)
615 elif self.logfile:
616 elif self.logfile:
616 self.magic('logstart %s' % self.logfile)
617 self.magic('logstart %s' % self.logfile)
617 elif self.logstart:
618 elif self.logstart:
618 self.magic('logstart')
619 self.magic('logstart')
619
620
620 def init_builtins(self):
621 def init_builtins(self):
621 # A single, static flag that we set to True. Its presence indicates
622 # A single, static flag that we set to True. Its presence indicates
622 # that an IPython shell has been created, and we make no attempts at
623 # that an IPython shell has been created, and we make no attempts at
623 # removing on exit or representing the existence of more than one
624 # removing on exit or representing the existence of more than one
624 # IPython at a time.
625 # IPython at a time.
625 builtin_mod.__dict__['__IPYTHON__'] = True
626 builtin_mod.__dict__['__IPYTHON__'] = True
626
627
627 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
628 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
628 # manage on enter/exit, but with all our shells it's virtually
629 # manage on enter/exit, but with all our shells it's virtually
629 # impossible to get all the cases right. We're leaving the name in for
630 # impossible to get all the cases right. We're leaving the name in for
630 # those who adapted their codes to check for this flag, but will
631 # those who adapted their codes to check for this flag, but will
631 # eventually remove it after a few more releases.
632 # eventually remove it after a few more releases.
632 builtin_mod.__dict__['__IPYTHON__active'] = \
633 builtin_mod.__dict__['__IPYTHON__active'] = \
633 'Deprecated, check for __IPYTHON__'
634 'Deprecated, check for __IPYTHON__'
634
635
635 self.builtin_trap = BuiltinTrap(shell=self)
636 self.builtin_trap = BuiltinTrap(shell=self)
636
637
637 def init_inspector(self):
638 def init_inspector(self):
638 # Object inspector
639 # Object inspector
639 self.inspector = oinspect.Inspector(oinspect.InspectColors,
640 self.inspector = oinspect.Inspector(oinspect.InspectColors,
640 PyColorize.ANSICodeColors,
641 PyColorize.ANSICodeColors,
641 'NoColor',
642 'NoColor',
642 self.object_info_string_level)
643 self.object_info_string_level)
643
644
644 def init_io(self):
645 def init_io(self):
645 # This will just use sys.stdout and sys.stderr. If you want to
646 # This will just use sys.stdout and sys.stderr. If you want to
646 # override sys.stdout and sys.stderr themselves, you need to do that
647 # override sys.stdout and sys.stderr themselves, you need to do that
647 # *before* instantiating this class, because io holds onto
648 # *before* instantiating this class, because io holds onto
648 # references to the underlying streams.
649 # references to the underlying streams.
649 if sys.platform == 'win32' and self.has_readline:
650 if sys.platform == 'win32' and self.has_readline:
650 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
651 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
651 else:
652 else:
652 io.stdout = io.IOStream(sys.stdout)
653 io.stdout = io.IOStream(sys.stdout)
653 io.stderr = io.IOStream(sys.stderr)
654 io.stderr = io.IOStream(sys.stderr)
654
655
655 def init_prompts(self):
656 def init_prompts(self):
656 self.prompt_manager = PromptManager(shell=self, config=self.config)
657 self.prompt_manager = PromptManager(shell=self, config=self.config)
657 self.configurables.append(self.prompt_manager)
658 self.configurables.append(self.prompt_manager)
658 # Set system prompts, so that scripts can decide if they are running
659 # Set system prompts, so that scripts can decide if they are running
659 # interactively.
660 # interactively.
660 sys.ps1 = 'In : '
661 sys.ps1 = 'In : '
661 sys.ps2 = '...: '
662 sys.ps2 = '...: '
662 sys.ps3 = 'Out: '
663 sys.ps3 = 'Out: '
663
664
664 def init_display_formatter(self):
665 def init_display_formatter(self):
665 self.display_formatter = DisplayFormatter(config=self.config)
666 self.display_formatter = DisplayFormatter(config=self.config)
666 self.configurables.append(self.display_formatter)
667 self.configurables.append(self.display_formatter)
667
668
668 def init_display_pub(self):
669 def init_display_pub(self):
669 self.display_pub = self.display_pub_class(config=self.config)
670 self.display_pub = self.display_pub_class(config=self.config)
670 self.configurables.append(self.display_pub)
671 self.configurables.append(self.display_pub)
671
672
672 def init_displayhook(self):
673 def init_displayhook(self):
673 # Initialize displayhook, set in/out prompts and printing system
674 # Initialize displayhook, set in/out prompts and printing system
674 self.displayhook = self.displayhook_class(
675 self.displayhook = self.displayhook_class(
675 config=self.config,
676 config=self.config,
676 shell=self,
677 shell=self,
677 cache_size=self.cache_size,
678 cache_size=self.cache_size,
678 )
679 )
679 self.configurables.append(self.displayhook)
680 self.configurables.append(self.displayhook)
680 # This is a context manager that installs/revmoes the displayhook at
681 # This is a context manager that installs/revmoes the displayhook at
681 # the appropriate time.
682 # the appropriate time.
682 self.display_trap = DisplayTrap(hook=self.displayhook)
683 self.display_trap = DisplayTrap(hook=self.displayhook)
683
684
684 def init_reload_doctest(self):
685 def init_reload_doctest(self):
685 # Do a proper resetting of doctest, including the necessary displayhook
686 # Do a proper resetting of doctest, including the necessary displayhook
686 # monkeypatching
687 # monkeypatching
687 try:
688 try:
688 doctest_reload()
689 doctest_reload()
689 except ImportError:
690 except ImportError:
690 warn("doctest module does not exist.")
691 warn("doctest module does not exist.")
691
692
692 def init_virtualenv(self):
693 def init_virtualenv(self):
693 """Add a virtualenv to sys.path so the user can import modules from it.
694 """Add a virtualenv to sys.path so the user can import modules from it.
694 This isn't perfect: it doesn't use the Python interpreter with which the
695 This isn't perfect: it doesn't use the Python interpreter with which the
695 virtualenv was built, and it ignores the --no-site-packages option. A
696 virtualenv was built, and it ignores the --no-site-packages option. A
696 warning will appear suggesting the user installs IPython in the
697 warning will appear suggesting the user installs IPython in the
697 virtualenv, but for many cases, it probably works well enough.
698 virtualenv, but for many cases, it probably works well enough.
698
699
699 Adapted from code snippets online.
700 Adapted from code snippets online.
700
701
701 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
702 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
702 """
703 """
703 if 'VIRTUAL_ENV' not in os.environ:
704 if 'VIRTUAL_ENV' not in os.environ:
704 # Not in a virtualenv
705 # Not in a virtualenv
705 return
706 return
706
707
707 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
708 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
708 # Running properly in the virtualenv, don't need to do anything
709 # Running properly in the virtualenv, don't need to do anything
709 return
710 return
710
711
711 warn("Attempting to work in a virtualenv. If you encounter problems, please "
712 warn("Attempting to work in a virtualenv. If you encounter problems, please "
712 "install IPython inside the virtualenv.\n")
713 "install IPython inside the virtualenv.\n")
713 if sys.platform == "win32":
714 if sys.platform == "win32":
714 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
715 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
715 else:
716 else:
716 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
717 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
717 'python%d.%d' % sys.version_info[:2], 'site-packages')
718 'python%d.%d' % sys.version_info[:2], 'site-packages')
718
719
719 import site
720 import site
720 sys.path.insert(0, virtual_env)
721 sys.path.insert(0, virtual_env)
721 site.addsitedir(virtual_env)
722 site.addsitedir(virtual_env)
722
723
723 #-------------------------------------------------------------------------
724 #-------------------------------------------------------------------------
724 # Things related to injections into the sys module
725 # Things related to injections into the sys module
725 #-------------------------------------------------------------------------
726 #-------------------------------------------------------------------------
726
727
727 def save_sys_module_state(self):
728 def save_sys_module_state(self):
728 """Save the state of hooks in the sys module.
729 """Save the state of hooks in the sys module.
729
730
730 This has to be called after self.user_module is created.
731 This has to be called after self.user_module is created.
731 """
732 """
732 self._orig_sys_module_state = {}
733 self._orig_sys_module_state = {}
733 self._orig_sys_module_state['stdin'] = sys.stdin
734 self._orig_sys_module_state['stdin'] = sys.stdin
734 self._orig_sys_module_state['stdout'] = sys.stdout
735 self._orig_sys_module_state['stdout'] = sys.stdout
735 self._orig_sys_module_state['stderr'] = sys.stderr
736 self._orig_sys_module_state['stderr'] = sys.stderr
736 self._orig_sys_module_state['excepthook'] = sys.excepthook
737 self._orig_sys_module_state['excepthook'] = sys.excepthook
737 self._orig_sys_modules_main_name = self.user_module.__name__
738 self._orig_sys_modules_main_name = self.user_module.__name__
738 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
739 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
739
740
740 def restore_sys_module_state(self):
741 def restore_sys_module_state(self):
741 """Restore the state of the sys module."""
742 """Restore the state of the sys module."""
742 try:
743 try:
743 for k, v in self._orig_sys_module_state.iteritems():
744 for k, v in self._orig_sys_module_state.iteritems():
744 setattr(sys, k, v)
745 setattr(sys, k, v)
745 except AttributeError:
746 except AttributeError:
746 pass
747 pass
747 # Reset what what done in self.init_sys_modules
748 # Reset what what done in self.init_sys_modules
748 if self._orig_sys_modules_main_mod is not None:
749 if self._orig_sys_modules_main_mod is not None:
749 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
750 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
750
751
751 #-------------------------------------------------------------------------
752 #-------------------------------------------------------------------------
752 # Things related to hooks
753 # Things related to hooks
753 #-------------------------------------------------------------------------
754 #-------------------------------------------------------------------------
754
755
755 def init_hooks(self):
756 def init_hooks(self):
756 # hooks holds pointers used for user-side customizations
757 # hooks holds pointers used for user-side customizations
757 self.hooks = Struct()
758 self.hooks = Struct()
758
759
759 self.strdispatchers = {}
760 self.strdispatchers = {}
760
761
761 # Set all default hooks, defined in the IPython.hooks module.
762 # Set all default hooks, defined in the IPython.hooks module.
762 hooks = IPython.core.hooks
763 hooks = IPython.core.hooks
763 for hook_name in hooks.__all__:
764 for hook_name in hooks.__all__:
764 # default hooks have priority 100, i.e. low; user hooks should have
765 # default hooks have priority 100, i.e. low; user hooks should have
765 # 0-100 priority
766 # 0-100 priority
766 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
767 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
767
768
768 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
769 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
769 """set_hook(name,hook) -> sets an internal IPython hook.
770 """set_hook(name,hook) -> sets an internal IPython hook.
770
771
771 IPython exposes some of its internal API as user-modifiable hooks. By
772 IPython exposes some of its internal API as user-modifiable hooks. By
772 adding your function to one of these hooks, you can modify IPython's
773 adding your function to one of these hooks, you can modify IPython's
773 behavior to call at runtime your own routines."""
774 behavior to call at runtime your own routines."""
774
775
775 # At some point in the future, this should validate the hook before it
776 # At some point in the future, this should validate the hook before it
776 # accepts it. Probably at least check that the hook takes the number
777 # accepts it. Probably at least check that the hook takes the number
777 # of args it's supposed to.
778 # of args it's supposed to.
778
779
779 f = types.MethodType(hook,self)
780 f = types.MethodType(hook,self)
780
781
781 # check if the hook is for strdispatcher first
782 # check if the hook is for strdispatcher first
782 if str_key is not None:
783 if str_key is not None:
783 sdp = self.strdispatchers.get(name, StrDispatch())
784 sdp = self.strdispatchers.get(name, StrDispatch())
784 sdp.add_s(str_key, f, priority )
785 sdp.add_s(str_key, f, priority )
785 self.strdispatchers[name] = sdp
786 self.strdispatchers[name] = sdp
786 return
787 return
787 if re_key is not None:
788 if re_key is not None:
788 sdp = self.strdispatchers.get(name, StrDispatch())
789 sdp = self.strdispatchers.get(name, StrDispatch())
789 sdp.add_re(re.compile(re_key), f, priority )
790 sdp.add_re(re.compile(re_key), f, priority )
790 self.strdispatchers[name] = sdp
791 self.strdispatchers[name] = sdp
791 return
792 return
792
793
793 dp = getattr(self.hooks, name, None)
794 dp = getattr(self.hooks, name, None)
794 if name not in IPython.core.hooks.__all__:
795 if name not in IPython.core.hooks.__all__:
795 print "Warning! Hook '%s' is not one of %s" % \
796 print("Warning! Hook '%s' is not one of %s" % \
796 (name, IPython.core.hooks.__all__ )
797 (name, IPython.core.hooks.__all__ ))
797 if not dp:
798 if not dp:
798 dp = IPython.core.hooks.CommandChainDispatcher()
799 dp = IPython.core.hooks.CommandChainDispatcher()
799
800
800 try:
801 try:
801 dp.add(f,priority)
802 dp.add(f,priority)
802 except AttributeError:
803 except AttributeError:
803 # it was not commandchain, plain old func - replace
804 # it was not commandchain, plain old func - replace
804 dp = f
805 dp = f
805
806
806 setattr(self.hooks,name, dp)
807 setattr(self.hooks,name, dp)
807
808
808 def register_post_execute(self, func):
809 def register_post_execute(self, func):
809 """Register a function for calling after code execution.
810 """Register a function for calling after code execution.
810 """
811 """
811 if not callable(func):
812 if not callable(func):
812 raise ValueError('argument %s must be callable' % func)
813 raise ValueError('argument %s must be callable' % func)
813 self._post_execute[func] = True
814 self._post_execute[func] = True
814
815
815 #-------------------------------------------------------------------------
816 #-------------------------------------------------------------------------
816 # Things related to the "main" module
817 # Things related to the "main" module
817 #-------------------------------------------------------------------------
818 #-------------------------------------------------------------------------
818
819
819 def new_main_mod(self,ns=None):
820 def new_main_mod(self,ns=None):
820 """Return a new 'main' module object for user code execution.
821 """Return a new 'main' module object for user code execution.
821 """
822 """
822 main_mod = self._user_main_module
823 main_mod = self._user_main_module
823 init_fakemod_dict(main_mod,ns)
824 init_fakemod_dict(main_mod,ns)
824 return main_mod
825 return main_mod
825
826
826 def cache_main_mod(self,ns,fname):
827 def cache_main_mod(self,ns,fname):
827 """Cache a main module's namespace.
828 """Cache a main module's namespace.
828
829
829 When scripts are executed via %run, we must keep a reference to the
830 When scripts are executed via %run, we must keep a reference to the
830 namespace of their __main__ module (a FakeModule instance) around so
831 namespace of their __main__ module (a FakeModule instance) around so
831 that Python doesn't clear it, rendering objects defined therein
832 that Python doesn't clear it, rendering objects defined therein
832 useless.
833 useless.
833
834
834 This method keeps said reference in a private dict, keyed by the
835 This method keeps said reference in a private dict, keyed by the
835 absolute path of the module object (which corresponds to the script
836 absolute path of the module object (which corresponds to the script
836 path). This way, for multiple executions of the same script we only
837 path). This way, for multiple executions of the same script we only
837 keep one copy of the namespace (the last one), thus preventing memory
838 keep one copy of the namespace (the last one), thus preventing memory
838 leaks from old references while allowing the objects from the last
839 leaks from old references while allowing the objects from the last
839 execution to be accessible.
840 execution to be accessible.
840
841
841 Note: we can not allow the actual FakeModule instances to be deleted,
842 Note: we can not allow the actual FakeModule instances to be deleted,
842 because of how Python tears down modules (it hard-sets all their
843 because of how Python tears down modules (it hard-sets all their
843 references to None without regard for reference counts). This method
844 references to None without regard for reference counts). This method
844 must therefore make a *copy* of the given namespace, to allow the
845 must therefore make a *copy* of the given namespace, to allow the
845 original module's __dict__ to be cleared and reused.
846 original module's __dict__ to be cleared and reused.
846
847
847
848
848 Parameters
849 Parameters
849 ----------
850 ----------
850 ns : a namespace (a dict, typically)
851 ns : a namespace (a dict, typically)
851
852
852 fname : str
853 fname : str
853 Filename associated with the namespace.
854 Filename associated with the namespace.
854
855
855 Examples
856 Examples
856 --------
857 --------
857
858
858 In [10]: import IPython
859 In [10]: import IPython
859
860
860 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
861 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
861
862
862 In [12]: IPython.__file__ in _ip._main_ns_cache
863 In [12]: IPython.__file__ in _ip._main_ns_cache
863 Out[12]: True
864 Out[12]: True
864 """
865 """
865 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
866 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
866
867
867 def clear_main_mod_cache(self):
868 def clear_main_mod_cache(self):
868 """Clear the cache of main modules.
869 """Clear the cache of main modules.
869
870
870 Mainly for use by utilities like %reset.
871 Mainly for use by utilities like %reset.
871
872
872 Examples
873 Examples
873 --------
874 --------
874
875
875 In [15]: import IPython
876 In [15]: import IPython
876
877
877 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
878 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
878
879
879 In [17]: len(_ip._main_ns_cache) > 0
880 In [17]: len(_ip._main_ns_cache) > 0
880 Out[17]: True
881 Out[17]: True
881
882
882 In [18]: _ip.clear_main_mod_cache()
883 In [18]: _ip.clear_main_mod_cache()
883
884
884 In [19]: len(_ip._main_ns_cache) == 0
885 In [19]: len(_ip._main_ns_cache) == 0
885 Out[19]: True
886 Out[19]: True
886 """
887 """
887 self._main_ns_cache.clear()
888 self._main_ns_cache.clear()
888
889
889 #-------------------------------------------------------------------------
890 #-------------------------------------------------------------------------
890 # Things related to debugging
891 # Things related to debugging
891 #-------------------------------------------------------------------------
892 #-------------------------------------------------------------------------
892
893
893 def init_pdb(self):
894 def init_pdb(self):
894 # Set calling of pdb on exceptions
895 # Set calling of pdb on exceptions
895 # self.call_pdb is a property
896 # self.call_pdb is a property
896 self.call_pdb = self.pdb
897 self.call_pdb = self.pdb
897
898
898 def _get_call_pdb(self):
899 def _get_call_pdb(self):
899 return self._call_pdb
900 return self._call_pdb
900
901
901 def _set_call_pdb(self,val):
902 def _set_call_pdb(self,val):
902
903
903 if val not in (0,1,False,True):
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 # store value in instance
907 # store value in instance
907 self._call_pdb = val
908 self._call_pdb = val
908
909
909 # notify the actual exception handlers
910 # notify the actual exception handlers
910 self.InteractiveTB.call_pdb = val
911 self.InteractiveTB.call_pdb = val
911
912
912 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
913 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
913 'Control auto-activation of pdb at exceptions')
914 'Control auto-activation of pdb at exceptions')
914
915
915 def debugger(self,force=False):
916 def debugger(self,force=False):
916 """Call the pydb/pdb debugger.
917 """Call the pydb/pdb debugger.
917
918
918 Keywords:
919 Keywords:
919
920
920 - force(False): by default, this routine checks the instance call_pdb
921 - force(False): by default, this routine checks the instance call_pdb
921 flag and does not actually invoke the debugger if the flag is false.
922 flag and does not actually invoke the debugger if the flag is false.
922 The 'force' option forces the debugger to activate even if the flag
923 The 'force' option forces the debugger to activate even if the flag
923 is false.
924 is false.
924 """
925 """
925
926
926 if not (force or self.call_pdb):
927 if not (force or self.call_pdb):
927 return
928 return
928
929
929 if not hasattr(sys,'last_traceback'):
930 if not hasattr(sys,'last_traceback'):
930 error('No traceback has been produced, nothing to debug.')
931 error('No traceback has been produced, nothing to debug.')
931 return
932 return
932
933
933 # use pydb if available
934 # use pydb if available
934 if debugger.has_pydb:
935 if debugger.has_pydb:
935 from pydb import pm
936 from pydb import pm
936 else:
937 else:
937 # fallback to our internal debugger
938 # fallback to our internal debugger
938 pm = lambda : self.InteractiveTB.debugger(force=True)
939 pm = lambda : self.InteractiveTB.debugger(force=True)
939
940
940 with self.readline_no_record:
941 with self.readline_no_record:
941 pm()
942 pm()
942
943
943 #-------------------------------------------------------------------------
944 #-------------------------------------------------------------------------
944 # Things related to IPython's various namespaces
945 # Things related to IPython's various namespaces
945 #-------------------------------------------------------------------------
946 #-------------------------------------------------------------------------
946 default_user_namespaces = True
947 default_user_namespaces = True
947
948
948 def init_create_namespaces(self, user_module=None, user_ns=None):
949 def init_create_namespaces(self, user_module=None, user_ns=None):
949 # Create the namespace where the user will operate. user_ns is
950 # Create the namespace where the user will operate. user_ns is
950 # normally the only one used, and it is passed to the exec calls as
951 # normally the only one used, and it is passed to the exec calls as
951 # the locals argument. But we do carry a user_global_ns namespace
952 # the locals argument. But we do carry a user_global_ns namespace
952 # given as the exec 'globals' argument, This is useful in embedding
953 # given as the exec 'globals' argument, This is useful in embedding
953 # situations where the ipython shell opens in a context where the
954 # situations where the ipython shell opens in a context where the
954 # distinction between locals and globals is meaningful. For
955 # distinction between locals and globals is meaningful. For
955 # non-embedded contexts, it is just the same object as the user_ns dict.
956 # non-embedded contexts, it is just the same object as the user_ns dict.
956
957
957 # FIXME. For some strange reason, __builtins__ is showing up at user
958 # FIXME. For some strange reason, __builtins__ is showing up at user
958 # level as a dict instead of a module. This is a manual fix, but I
959 # level as a dict instead of a module. This is a manual fix, but I
959 # should really track down where the problem is coming from. Alex
960 # should really track down where the problem is coming from. Alex
960 # Schmolck reported this problem first.
961 # Schmolck reported this problem first.
961
962
962 # A useful post by Alex Martelli on this topic:
963 # A useful post by Alex Martelli on this topic:
963 # Re: inconsistent value from __builtins__
964 # Re: inconsistent value from __builtins__
964 # Von: Alex Martelli <aleaxit@yahoo.com>
965 # Von: Alex Martelli <aleaxit@yahoo.com>
965 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
966 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
966 # Gruppen: comp.lang.python
967 # Gruppen: comp.lang.python
967
968
968 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
969 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
969 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
970 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
970 # > <type 'dict'>
971 # > <type 'dict'>
971 # > >>> print type(__builtins__)
972 # > >>> print type(__builtins__)
972 # > <type 'module'>
973 # > <type 'module'>
973 # > Is this difference in return value intentional?
974 # > Is this difference in return value intentional?
974
975
975 # Well, it's documented that '__builtins__' can be either a dictionary
976 # Well, it's documented that '__builtins__' can be either a dictionary
976 # or a module, and it's been that way for a long time. Whether it's
977 # or a module, and it's been that way for a long time. Whether it's
977 # intentional (or sensible), I don't know. In any case, the idea is
978 # intentional (or sensible), I don't know. In any case, the idea is
978 # that if you need to access the built-in namespace directly, you
979 # that if you need to access the built-in namespace directly, you
979 # should start with "import __builtin__" (note, no 's') which will
980 # should start with "import __builtin__" (note, no 's') which will
980 # definitely give you a module. Yeah, it's somewhat confusing:-(.
981 # definitely give you a module. Yeah, it's somewhat confusing:-(.
981
982
982 # These routines return a properly built module and dict as needed by
983 # These routines return a properly built module and dict as needed by
983 # the rest of the code, and can also be used by extension writers to
984 # the rest of the code, and can also be used by extension writers to
984 # generate properly initialized namespaces.
985 # generate properly initialized namespaces.
985 if (user_ns is not None) or (user_module is not None):
986 if (user_ns is not None) or (user_module is not None):
986 self.default_user_namespaces = False
987 self.default_user_namespaces = False
987 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
988 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
988
989
989 # A record of hidden variables we have added to the user namespace, so
990 # A record of hidden variables we have added to the user namespace, so
990 # we can list later only variables defined in actual interactive use.
991 # we can list later only variables defined in actual interactive use.
991 self.user_ns_hidden = set()
992 self.user_ns_hidden = set()
992
993
993 # Now that FakeModule produces a real module, we've run into a nasty
994 # Now that FakeModule produces a real module, we've run into a nasty
994 # problem: after script execution (via %run), the module where the user
995 # problem: after script execution (via %run), the module where the user
995 # code ran is deleted. Now that this object is a true module (needed
996 # code ran is deleted. Now that this object is a true module (needed
996 # so docetst and other tools work correctly), the Python module
997 # so docetst and other tools work correctly), the Python module
997 # teardown mechanism runs over it, and sets to None every variable
998 # teardown mechanism runs over it, and sets to None every variable
998 # present in that module. Top-level references to objects from the
999 # present in that module. Top-level references to objects from the
999 # script survive, because the user_ns is updated with them. However,
1000 # script survive, because the user_ns is updated with them. However,
1000 # calling functions defined in the script that use other things from
1001 # calling functions defined in the script that use other things from
1001 # the script will fail, because the function's closure had references
1002 # the script will fail, because the function's closure had references
1002 # to the original objects, which are now all None. So we must protect
1003 # to the original objects, which are now all None. So we must protect
1003 # these modules from deletion by keeping a cache.
1004 # these modules from deletion by keeping a cache.
1004 #
1005 #
1005 # To avoid keeping stale modules around (we only need the one from the
1006 # To avoid keeping stale modules around (we only need the one from the
1006 # last run), we use a dict keyed with the full path to the script, so
1007 # last run), we use a dict keyed with the full path to the script, so
1007 # only the last version of the module is held in the cache. Note,
1008 # only the last version of the module is held in the cache. Note,
1008 # however, that we must cache the module *namespace contents* (their
1009 # however, that we must cache the module *namespace contents* (their
1009 # __dict__). Because if we try to cache the actual modules, old ones
1010 # __dict__). Because if we try to cache the actual modules, old ones
1010 # (uncached) could be destroyed while still holding references (such as
1011 # (uncached) could be destroyed while still holding references (such as
1011 # those held by GUI objects that tend to be long-lived)>
1012 # those held by GUI objects that tend to be long-lived)>
1012 #
1013 #
1013 # The %reset command will flush this cache. See the cache_main_mod()
1014 # The %reset command will flush this cache. See the cache_main_mod()
1014 # and clear_main_mod_cache() methods for details on use.
1015 # and clear_main_mod_cache() methods for details on use.
1015
1016
1016 # This is the cache used for 'main' namespaces
1017 # This is the cache used for 'main' namespaces
1017 self._main_ns_cache = {}
1018 self._main_ns_cache = {}
1018 # And this is the single instance of FakeModule whose __dict__ we keep
1019 # And this is the single instance of FakeModule whose __dict__ we keep
1019 # copying and clearing for reuse on each %run
1020 # copying and clearing for reuse on each %run
1020 self._user_main_module = FakeModule()
1021 self._user_main_module = FakeModule()
1021
1022
1022 # A table holding all the namespaces IPython deals with, so that
1023 # A table holding all the namespaces IPython deals with, so that
1023 # introspection facilities can search easily.
1024 # introspection facilities can search easily.
1024 self.ns_table = {'user_global':self.user_module.__dict__,
1025 self.ns_table = {'user_global':self.user_module.__dict__,
1025 'user_local':self.user_ns,
1026 'user_local':self.user_ns,
1026 'builtin':builtin_mod.__dict__
1027 'builtin':builtin_mod.__dict__
1027 }
1028 }
1028
1029
1029 @property
1030 @property
1030 def user_global_ns(self):
1031 def user_global_ns(self):
1031 return self.user_module.__dict__
1032 return self.user_module.__dict__
1032
1033
1033 def prepare_user_module(self, user_module=None, user_ns=None):
1034 def prepare_user_module(self, user_module=None, user_ns=None):
1034 """Prepare the module and namespace in which user code will be run.
1035 """Prepare the module and namespace in which user code will be run.
1035
1036
1036 When IPython is started normally, both parameters are None: a new module
1037 When IPython is started normally, both parameters are None: a new module
1037 is created automatically, and its __dict__ used as the namespace.
1038 is created automatically, and its __dict__ used as the namespace.
1038
1039
1039 If only user_module is provided, its __dict__ is used as the namespace.
1040 If only user_module is provided, its __dict__ is used as the namespace.
1040 If only user_ns is provided, a dummy module is created, and user_ns
1041 If only user_ns is provided, a dummy module is created, and user_ns
1041 becomes the global namespace. If both are provided (as they may be
1042 becomes the global namespace. If both are provided (as they may be
1042 when embedding), user_ns is the local namespace, and user_module
1043 when embedding), user_ns is the local namespace, and user_module
1043 provides the global namespace.
1044 provides the global namespace.
1044
1045
1045 Parameters
1046 Parameters
1046 ----------
1047 ----------
1047 user_module : module, optional
1048 user_module : module, optional
1048 The current user module in which IPython is being run. If None,
1049 The current user module in which IPython is being run. If None,
1049 a clean module will be created.
1050 a clean module will be created.
1050 user_ns : dict, optional
1051 user_ns : dict, optional
1051 A namespace in which to run interactive commands.
1052 A namespace in which to run interactive commands.
1052
1053
1053 Returns
1054 Returns
1054 -------
1055 -------
1055 A tuple of user_module and user_ns, each properly initialised.
1056 A tuple of user_module and user_ns, each properly initialised.
1056 """
1057 """
1057 if user_module is None and user_ns is not None:
1058 if user_module is None and user_ns is not None:
1058 user_ns.setdefault("__name__", "__main__")
1059 user_ns.setdefault("__name__", "__main__")
1059 class DummyMod(object):
1060 class DummyMod(object):
1060 "A dummy module used for IPython's interactive namespace."
1061 "A dummy module used for IPython's interactive namespace."
1061 pass
1062 pass
1062 user_module = DummyMod()
1063 user_module = DummyMod()
1063 user_module.__dict__ = user_ns
1064 user_module.__dict__ = user_ns
1064
1065
1065 if user_module is None:
1066 if user_module is None:
1066 user_module = types.ModuleType("__main__",
1067 user_module = types.ModuleType("__main__",
1067 doc="Automatically created module for IPython interactive environment")
1068 doc="Automatically created module for IPython interactive environment")
1068
1069
1069 # We must ensure that __builtin__ (without the final 's') is always
1070 # We must ensure that __builtin__ (without the final 's') is always
1070 # available and pointing to the __builtin__ *module*. For more details:
1071 # available and pointing to the __builtin__ *module*. For more details:
1071 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1072 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1072 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1073 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1073 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1074 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1074
1075
1075 if user_ns is None:
1076 if user_ns is None:
1076 user_ns = user_module.__dict__
1077 user_ns = user_module.__dict__
1077
1078
1078 return user_module, user_ns
1079 return user_module, user_ns
1079
1080
1080 def init_sys_modules(self):
1081 def init_sys_modules(self):
1081 # We need to insert into sys.modules something that looks like a
1082 # We need to insert into sys.modules something that looks like a
1082 # module but which accesses the IPython namespace, for shelve and
1083 # module but which accesses the IPython namespace, for shelve and
1083 # pickle to work interactively. Normally they rely on getting
1084 # pickle to work interactively. Normally they rely on getting
1084 # everything out of __main__, but for embedding purposes each IPython
1085 # everything out of __main__, but for embedding purposes each IPython
1085 # instance has its own private namespace, so we can't go shoving
1086 # instance has its own private namespace, so we can't go shoving
1086 # everything into __main__.
1087 # everything into __main__.
1087
1088
1088 # note, however, that we should only do this for non-embedded
1089 # note, however, that we should only do this for non-embedded
1089 # ipythons, which really mimic the __main__.__dict__ with their own
1090 # ipythons, which really mimic the __main__.__dict__ with their own
1090 # namespace. Embedded instances, on the other hand, should not do
1091 # namespace. Embedded instances, on the other hand, should not do
1091 # this because they need to manage the user local/global namespaces
1092 # this because they need to manage the user local/global namespaces
1092 # only, but they live within a 'normal' __main__ (meaning, they
1093 # only, but they live within a 'normal' __main__ (meaning, they
1093 # shouldn't overtake the execution environment of the script they're
1094 # shouldn't overtake the execution environment of the script they're
1094 # embedded in).
1095 # embedded in).
1095
1096
1096 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1097 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1097 main_name = self.user_module.__name__
1098 main_name = self.user_module.__name__
1098 sys.modules[main_name] = self.user_module
1099 sys.modules[main_name] = self.user_module
1099
1100
1100 def init_user_ns(self):
1101 def init_user_ns(self):
1101 """Initialize all user-visible namespaces to their minimum defaults.
1102 """Initialize all user-visible namespaces to their minimum defaults.
1102
1103
1103 Certain history lists are also initialized here, as they effectively
1104 Certain history lists are also initialized here, as they effectively
1104 act as user namespaces.
1105 act as user namespaces.
1105
1106
1106 Notes
1107 Notes
1107 -----
1108 -----
1108 All data structures here are only filled in, they are NOT reset by this
1109 All data structures here are only filled in, they are NOT reset by this
1109 method. If they were not empty before, data will simply be added to
1110 method. If they were not empty before, data will simply be added to
1110 therm.
1111 therm.
1111 """
1112 """
1112 # This function works in two parts: first we put a few things in
1113 # This function works in two parts: first we put a few things in
1113 # user_ns, and we sync that contents into user_ns_hidden so that these
1114 # user_ns, and we sync that contents into user_ns_hidden so that these
1114 # initial variables aren't shown by %who. After the sync, we add the
1115 # initial variables aren't shown by %who. After the sync, we add the
1115 # rest of what we *do* want the user to see with %who even on a new
1116 # rest of what we *do* want the user to see with %who even on a new
1116 # session (probably nothing, so theye really only see their own stuff)
1117 # session (probably nothing, so theye really only see their own stuff)
1117
1118
1118 # The user dict must *always* have a __builtin__ reference to the
1119 # The user dict must *always* have a __builtin__ reference to the
1119 # Python standard __builtin__ namespace, which must be imported.
1120 # Python standard __builtin__ namespace, which must be imported.
1120 # This is so that certain operations in prompt evaluation can be
1121 # This is so that certain operations in prompt evaluation can be
1121 # reliably executed with builtins. Note that we can NOT use
1122 # reliably executed with builtins. Note that we can NOT use
1122 # __builtins__ (note the 's'), because that can either be a dict or a
1123 # __builtins__ (note the 's'), because that can either be a dict or a
1123 # module, and can even mutate at runtime, depending on the context
1124 # module, and can even mutate at runtime, depending on the context
1124 # (Python makes no guarantees on it). In contrast, __builtin__ is
1125 # (Python makes no guarantees on it). In contrast, __builtin__ is
1125 # always a module object, though it must be explicitly imported.
1126 # always a module object, though it must be explicitly imported.
1126
1127
1127 # For more details:
1128 # For more details:
1128 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1129 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1129 ns = dict()
1130 ns = dict()
1130
1131
1131 # Put 'help' in the user namespace
1132 # Put 'help' in the user namespace
1132 try:
1133 try:
1133 from site import _Helper
1134 from site import _Helper
1134 ns['help'] = _Helper()
1135 ns['help'] = _Helper()
1135 except ImportError:
1136 except ImportError:
1136 warn('help() not available - check site.py')
1137 warn('help() not available - check site.py')
1137
1138
1138 # make global variables for user access to the histories
1139 # make global variables for user access to the histories
1139 ns['_ih'] = self.history_manager.input_hist_parsed
1140 ns['_ih'] = self.history_manager.input_hist_parsed
1140 ns['_oh'] = self.history_manager.output_hist
1141 ns['_oh'] = self.history_manager.output_hist
1141 ns['_dh'] = self.history_manager.dir_hist
1142 ns['_dh'] = self.history_manager.dir_hist
1142
1143
1143 ns['_sh'] = shadowns
1144 ns['_sh'] = shadowns
1144
1145
1145 # user aliases to input and output histories. These shouldn't show up
1146 # user aliases to input and output histories. These shouldn't show up
1146 # in %who, as they can have very large reprs.
1147 # in %who, as they can have very large reprs.
1147 ns['In'] = self.history_manager.input_hist_parsed
1148 ns['In'] = self.history_manager.input_hist_parsed
1148 ns['Out'] = self.history_manager.output_hist
1149 ns['Out'] = self.history_manager.output_hist
1149
1150
1150 # Store myself as the public api!!!
1151 # Store myself as the public api!!!
1151 ns['get_ipython'] = self.get_ipython
1152 ns['get_ipython'] = self.get_ipython
1152
1153
1153 ns['exit'] = self.exiter
1154 ns['exit'] = self.exiter
1154 ns['quit'] = self.exiter
1155 ns['quit'] = self.exiter
1155
1156
1156 # Sync what we've added so far to user_ns_hidden so these aren't seen
1157 # Sync what we've added so far to user_ns_hidden so these aren't seen
1157 # by %who
1158 # by %who
1158 self.user_ns_hidden.update(ns)
1159 self.user_ns_hidden.update(ns)
1159
1160
1160 # Anything put into ns now would show up in %who. Think twice before
1161 # Anything put into ns now would show up in %who. Think twice before
1161 # putting anything here, as we really want %who to show the user their
1162 # putting anything here, as we really want %who to show the user their
1162 # stuff, not our variables.
1163 # stuff, not our variables.
1163
1164
1164 # Finally, update the real user's namespace
1165 # Finally, update the real user's namespace
1165 self.user_ns.update(ns)
1166 self.user_ns.update(ns)
1166
1167
1167 @property
1168 @property
1168 def all_ns_refs(self):
1169 def all_ns_refs(self):
1169 """Get a list of references to all the namespace dictionaries in which
1170 """Get a list of references to all the namespace dictionaries in which
1170 IPython might store a user-created object.
1171 IPython might store a user-created object.
1171
1172
1172 Note that this does not include the displayhook, which also caches
1173 Note that this does not include the displayhook, which also caches
1173 objects from the output."""
1174 objects from the output."""
1174 return [self.user_ns, self.user_global_ns,
1175 return [self.user_ns, self.user_global_ns,
1175 self._user_main_module.__dict__] + self._main_ns_cache.values()
1176 self._user_main_module.__dict__] + self._main_ns_cache.values()
1176
1177
1177 def reset(self, new_session=True):
1178 def reset(self, new_session=True):
1178 """Clear all internal namespaces, and attempt to release references to
1179 """Clear all internal namespaces, and attempt to release references to
1179 user objects.
1180 user objects.
1180
1181
1181 If new_session is True, a new history session will be opened.
1182 If new_session is True, a new history session will be opened.
1182 """
1183 """
1183 # Clear histories
1184 # Clear histories
1184 self.history_manager.reset(new_session)
1185 self.history_manager.reset(new_session)
1185 # Reset counter used to index all histories
1186 # Reset counter used to index all histories
1186 if new_session:
1187 if new_session:
1187 self.execution_count = 1
1188 self.execution_count = 1
1188
1189
1189 # Flush cached output items
1190 # Flush cached output items
1190 if self.displayhook.do_full_cache:
1191 if self.displayhook.do_full_cache:
1191 self.displayhook.flush()
1192 self.displayhook.flush()
1192
1193
1193 # The main execution namespaces must be cleared very carefully,
1194 # The main execution namespaces must be cleared very carefully,
1194 # skipping the deletion of the builtin-related keys, because doing so
1195 # skipping the deletion of the builtin-related keys, because doing so
1195 # would cause errors in many object's __del__ methods.
1196 # would cause errors in many object's __del__ methods.
1196 if self.user_ns is not self.user_global_ns:
1197 if self.user_ns is not self.user_global_ns:
1197 self.user_ns.clear()
1198 self.user_ns.clear()
1198 ns = self.user_global_ns
1199 ns = self.user_global_ns
1199 drop_keys = set(ns.keys())
1200 drop_keys = set(ns.keys())
1200 drop_keys.discard('__builtin__')
1201 drop_keys.discard('__builtin__')
1201 drop_keys.discard('__builtins__')
1202 drop_keys.discard('__builtins__')
1202 drop_keys.discard('__name__')
1203 drop_keys.discard('__name__')
1203 for k in drop_keys:
1204 for k in drop_keys:
1204 del ns[k]
1205 del ns[k]
1205
1206
1206 self.user_ns_hidden.clear()
1207 self.user_ns_hidden.clear()
1207
1208
1208 # Restore the user namespaces to minimal usability
1209 # Restore the user namespaces to minimal usability
1209 self.init_user_ns()
1210 self.init_user_ns()
1210
1211
1211 # Restore the default and user aliases
1212 # Restore the default and user aliases
1212 self.alias_manager.clear_aliases()
1213 self.alias_manager.clear_aliases()
1213 self.alias_manager.init_aliases()
1214 self.alias_manager.init_aliases()
1214
1215
1215 # Flush the private list of module references kept for script
1216 # Flush the private list of module references kept for script
1216 # execution protection
1217 # execution protection
1217 self.clear_main_mod_cache()
1218 self.clear_main_mod_cache()
1218
1219
1219 # Clear out the namespace from the last %run
1220 # Clear out the namespace from the last %run
1220 self.new_main_mod()
1221 self.new_main_mod()
1221
1222
1222 def del_var(self, varname, by_name=False):
1223 def del_var(self, varname, by_name=False):
1223 """Delete a variable from the various namespaces, so that, as
1224 """Delete a variable from the various namespaces, so that, as
1224 far as possible, we're not keeping any hidden references to it.
1225 far as possible, we're not keeping any hidden references to it.
1225
1226
1226 Parameters
1227 Parameters
1227 ----------
1228 ----------
1228 varname : str
1229 varname : str
1229 The name of the variable to delete.
1230 The name of the variable to delete.
1230 by_name : bool
1231 by_name : bool
1231 If True, delete variables with the given name in each
1232 If True, delete variables with the given name in each
1232 namespace. If False (default), find the variable in the user
1233 namespace. If False (default), find the variable in the user
1233 namespace, and delete references to it.
1234 namespace, and delete references to it.
1234 """
1235 """
1235 if varname in ('__builtin__', '__builtins__'):
1236 if varname in ('__builtin__', '__builtins__'):
1236 raise ValueError("Refusing to delete %s" % varname)
1237 raise ValueError("Refusing to delete %s" % varname)
1237
1238
1238 ns_refs = self.all_ns_refs
1239 ns_refs = self.all_ns_refs
1239
1240
1240 if by_name: # Delete by name
1241 if by_name: # Delete by name
1241 for ns in ns_refs:
1242 for ns in ns_refs:
1242 try:
1243 try:
1243 del ns[varname]
1244 del ns[varname]
1244 except KeyError:
1245 except KeyError:
1245 pass
1246 pass
1246 else: # Delete by object
1247 else: # Delete by object
1247 try:
1248 try:
1248 obj = self.user_ns[varname]
1249 obj = self.user_ns[varname]
1249 except KeyError:
1250 except KeyError:
1250 raise NameError("name '%s' is not defined" % varname)
1251 raise NameError("name '%s' is not defined" % varname)
1251 # Also check in output history
1252 # Also check in output history
1252 ns_refs.append(self.history_manager.output_hist)
1253 ns_refs.append(self.history_manager.output_hist)
1253 for ns in ns_refs:
1254 for ns in ns_refs:
1254 to_delete = [n for n, o in ns.iteritems() if o is obj]
1255 to_delete = [n for n, o in ns.iteritems() if o is obj]
1255 for name in to_delete:
1256 for name in to_delete:
1256 del ns[name]
1257 del ns[name]
1257
1258
1258 # displayhook keeps extra references, but not in a dictionary
1259 # displayhook keeps extra references, but not in a dictionary
1259 for name in ('_', '__', '___'):
1260 for name in ('_', '__', '___'):
1260 if getattr(self.displayhook, name) is obj:
1261 if getattr(self.displayhook, name) is obj:
1261 setattr(self.displayhook, name, None)
1262 setattr(self.displayhook, name, None)
1262
1263
1263 def reset_selective(self, regex=None):
1264 def reset_selective(self, regex=None):
1264 """Clear selective variables from internal namespaces based on a
1265 """Clear selective variables from internal namespaces based on a
1265 specified regular expression.
1266 specified regular expression.
1266
1267
1267 Parameters
1268 Parameters
1268 ----------
1269 ----------
1269 regex : string or compiled pattern, optional
1270 regex : string or compiled pattern, optional
1270 A regular expression pattern that will be used in searching
1271 A regular expression pattern that will be used in searching
1271 variable names in the users namespaces.
1272 variable names in the users namespaces.
1272 """
1273 """
1273 if regex is not None:
1274 if regex is not None:
1274 try:
1275 try:
1275 m = re.compile(regex)
1276 m = re.compile(regex)
1276 except TypeError:
1277 except TypeError:
1277 raise TypeError('regex must be a string or compiled pattern')
1278 raise TypeError('regex must be a string or compiled pattern')
1278 # Search for keys in each namespace that match the given regex
1279 # Search for keys in each namespace that match the given regex
1279 # If a match is found, delete the key/value pair.
1280 # If a match is found, delete the key/value pair.
1280 for ns in self.all_ns_refs:
1281 for ns in self.all_ns_refs:
1281 for var in ns:
1282 for var in ns:
1282 if m.search(var):
1283 if m.search(var):
1283 del ns[var]
1284 del ns[var]
1284
1285
1285 def push(self, variables, interactive=True):
1286 def push(self, variables, interactive=True):
1286 """Inject a group of variables into the IPython user namespace.
1287 """Inject a group of variables into the IPython user namespace.
1287
1288
1288 Parameters
1289 Parameters
1289 ----------
1290 ----------
1290 variables : dict, str or list/tuple of str
1291 variables : dict, str or list/tuple of str
1291 The variables to inject into the user's namespace. If a dict, a
1292 The variables to inject into the user's namespace. If a dict, a
1292 simple update is done. If a str, the string is assumed to have
1293 simple update is done. If a str, the string is assumed to have
1293 variable names separated by spaces. A list/tuple of str can also
1294 variable names separated by spaces. A list/tuple of str can also
1294 be used to give the variable names. If just the variable names are
1295 be used to give the variable names. If just the variable names are
1295 give (list/tuple/str) then the variable values looked up in the
1296 give (list/tuple/str) then the variable values looked up in the
1296 callers frame.
1297 callers frame.
1297 interactive : bool
1298 interactive : bool
1298 If True (default), the variables will be listed with the ``who``
1299 If True (default), the variables will be listed with the ``who``
1299 magic.
1300 magic.
1300 """
1301 """
1301 vdict = None
1302 vdict = None
1302
1303
1303 # We need a dict of name/value pairs to do namespace updates.
1304 # We need a dict of name/value pairs to do namespace updates.
1304 if isinstance(variables, dict):
1305 if isinstance(variables, dict):
1305 vdict = variables
1306 vdict = variables
1306 elif isinstance(variables, (basestring, list, tuple)):
1307 elif isinstance(variables, (basestring, list, tuple)):
1307 if isinstance(variables, basestring):
1308 if isinstance(variables, basestring):
1308 vlist = variables.split()
1309 vlist = variables.split()
1309 else:
1310 else:
1310 vlist = variables
1311 vlist = variables
1311 vdict = {}
1312 vdict = {}
1312 cf = sys._getframe(1)
1313 cf = sys._getframe(1)
1313 for name in vlist:
1314 for name in vlist:
1314 try:
1315 try:
1315 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1316 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1316 except:
1317 except:
1317 print ('Could not get variable %s from %s' %
1318 print('Could not get variable %s from %s' %
1318 (name,cf.f_code.co_name))
1319 (name,cf.f_code.co_name))
1319 else:
1320 else:
1320 raise ValueError('variables must be a dict/str/list/tuple')
1321 raise ValueError('variables must be a dict/str/list/tuple')
1321
1322
1322 # Propagate variables to user namespace
1323 # Propagate variables to user namespace
1323 self.user_ns.update(vdict)
1324 self.user_ns.update(vdict)
1324
1325
1325 # And configure interactive visibility
1326 # And configure interactive visibility
1326 user_ns_hidden = self.user_ns_hidden
1327 user_ns_hidden = self.user_ns_hidden
1327 if interactive:
1328 if interactive:
1328 user_ns_hidden.difference_update(vdict)
1329 user_ns_hidden.difference_update(vdict)
1329 else:
1330 else:
1330 user_ns_hidden.update(vdict)
1331 user_ns_hidden.update(vdict)
1331
1332
1332 def drop_by_id(self, variables):
1333 def drop_by_id(self, variables):
1333 """Remove a dict of variables from the user namespace, if they are the
1334 """Remove a dict of variables from the user namespace, if they are the
1334 same as the values in the dictionary.
1335 same as the values in the dictionary.
1335
1336
1336 This is intended for use by extensions: variables that they've added can
1337 This is intended for use by extensions: variables that they've added can
1337 be taken back out if they are unloaded, without removing any that the
1338 be taken back out if they are unloaded, without removing any that the
1338 user has overwritten.
1339 user has overwritten.
1339
1340
1340 Parameters
1341 Parameters
1341 ----------
1342 ----------
1342 variables : dict
1343 variables : dict
1343 A dictionary mapping object names (as strings) to the objects.
1344 A dictionary mapping object names (as strings) to the objects.
1344 """
1345 """
1345 for name, obj in variables.iteritems():
1346 for name, obj in variables.iteritems():
1346 if name in self.user_ns and self.user_ns[name] is obj:
1347 if name in self.user_ns and self.user_ns[name] is obj:
1347 del self.user_ns[name]
1348 del self.user_ns[name]
1348 self.user_ns_hidden.discard(name)
1349 self.user_ns_hidden.discard(name)
1349
1350
1350 #-------------------------------------------------------------------------
1351 #-------------------------------------------------------------------------
1351 # Things related to object introspection
1352 # Things related to object introspection
1352 #-------------------------------------------------------------------------
1353 #-------------------------------------------------------------------------
1353
1354
1354 def _ofind(self, oname, namespaces=None):
1355 def _ofind(self, oname, namespaces=None):
1355 """Find an object in the available namespaces.
1356 """Find an object in the available namespaces.
1356
1357
1357 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1358 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1358
1359
1359 Has special code to detect magic functions.
1360 Has special code to detect magic functions.
1360 """
1361 """
1361 oname = oname.strip()
1362 oname = oname.strip()
1362 #print '1- oname: <%r>' % oname # dbg
1363 #print '1- oname: <%r>' % oname # dbg
1363 if not oname.startswith(ESC_MAGIC) and \
1364 if not oname.startswith(ESC_MAGIC) and \
1364 not oname.startswith(ESC_MAGIC2) and \
1365 not oname.startswith(ESC_MAGIC2) and \
1365 not py3compat.isidentifier(oname, dotted=True):
1366 not py3compat.isidentifier(oname, dotted=True):
1366 return dict(found=False)
1367 return dict(found=False)
1367
1368
1368 alias_ns = None
1369 alias_ns = None
1369 if namespaces is None:
1370 if namespaces is None:
1370 # Namespaces to search in:
1371 # Namespaces to search in:
1371 # Put them in a list. The order is important so that we
1372 # Put them in a list. The order is important so that we
1372 # find things in the same order that Python finds them.
1373 # find things in the same order that Python finds them.
1373 namespaces = [ ('Interactive', self.user_ns),
1374 namespaces = [ ('Interactive', self.user_ns),
1374 ('Interactive (global)', self.user_global_ns),
1375 ('Interactive (global)', self.user_global_ns),
1375 ('Python builtin', builtin_mod.__dict__),
1376 ('Python builtin', builtin_mod.__dict__),
1376 ('Alias', self.alias_manager.alias_table),
1377 ('Alias', self.alias_manager.alias_table),
1377 ]
1378 ]
1378 alias_ns = self.alias_manager.alias_table
1379 alias_ns = self.alias_manager.alias_table
1379
1380
1380 # initialize results to 'null'
1381 # initialize results to 'null'
1381 found = False; obj = None; ospace = None; ds = None;
1382 found = False; obj = None; ospace = None; ds = None;
1382 ismagic = False; isalias = False; parent = None
1383 ismagic = False; isalias = False; parent = None
1383
1384
1384 # We need to special-case 'print', which as of python2.6 registers as a
1385 # We need to special-case 'print', which as of python2.6 registers as a
1385 # function but should only be treated as one if print_function was
1386 # function but should only be treated as one if print_function was
1386 # loaded with a future import. In this case, just bail.
1387 # loaded with a future import. In this case, just bail.
1387 if (oname == 'print' and not py3compat.PY3 and not \
1388 if (oname == 'print' and not py3compat.PY3 and not \
1388 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1389 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 return {'found':found, 'obj':obj, 'namespace':ospace,
1390 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1391
1392
1392 # Look for the given name by splitting it in parts. If the head is
1393 # Look for the given name by splitting it in parts. If the head is
1393 # found, then we look for all the remaining parts as members, and only
1394 # found, then we look for all the remaining parts as members, and only
1394 # declare success if we can find them all.
1395 # declare success if we can find them all.
1395 oname_parts = oname.split('.')
1396 oname_parts = oname.split('.')
1396 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1397 for nsname,ns in namespaces:
1398 for nsname,ns in namespaces:
1398 try:
1399 try:
1399 obj = ns[oname_head]
1400 obj = ns[oname_head]
1400 except KeyError:
1401 except KeyError:
1401 continue
1402 continue
1402 else:
1403 else:
1403 #print 'oname_rest:', oname_rest # dbg
1404 #print 'oname_rest:', oname_rest # dbg
1404 for part in oname_rest:
1405 for part in oname_rest:
1405 try:
1406 try:
1406 parent = obj
1407 parent = obj
1407 obj = getattr(obj,part)
1408 obj = getattr(obj,part)
1408 except:
1409 except:
1409 # Blanket except b/c some badly implemented objects
1410 # Blanket except b/c some badly implemented objects
1410 # allow __getattr__ to raise exceptions other than
1411 # allow __getattr__ to raise exceptions other than
1411 # AttributeError, which then crashes IPython.
1412 # AttributeError, which then crashes IPython.
1412 break
1413 break
1413 else:
1414 else:
1414 # If we finish the for loop (no break), we got all members
1415 # If we finish the for loop (no break), we got all members
1415 found = True
1416 found = True
1416 ospace = nsname
1417 ospace = nsname
1417 if ns == alias_ns:
1418 if ns == alias_ns:
1418 isalias = True
1419 isalias = True
1419 break # namespace loop
1420 break # namespace loop
1420
1421
1421 # Try to see if it's magic
1422 # Try to see if it's magic
1422 if not found:
1423 if not found:
1423 obj = None
1424 obj = None
1424 if oname.startswith(ESC_MAGIC2):
1425 if oname.startswith(ESC_MAGIC2):
1425 oname = oname.lstrip(ESC_MAGIC2)
1426 oname = oname.lstrip(ESC_MAGIC2)
1426 obj = self.find_cell_magic(oname)
1427 obj = self.find_cell_magic(oname)
1427 elif oname.startswith(ESC_MAGIC):
1428 elif oname.startswith(ESC_MAGIC):
1428 oname = oname.lstrip(ESC_MAGIC)
1429 oname = oname.lstrip(ESC_MAGIC)
1429 obj = self.find_line_magic(oname)
1430 obj = self.find_line_magic(oname)
1430 else:
1431 else:
1431 # search without prefix, so run? will find %run?
1432 # search without prefix, so run? will find %run?
1432 obj = self.find_line_magic(oname)
1433 obj = self.find_line_magic(oname)
1433 if obj is None:
1434 if obj is None:
1434 obj = self.find_cell_magic(oname)
1435 obj = self.find_cell_magic(oname)
1435 if obj is not None:
1436 if obj is not None:
1436 found = True
1437 found = True
1437 ospace = 'IPython internal'
1438 ospace = 'IPython internal'
1438 ismagic = True
1439 ismagic = True
1439
1440
1440 # Last try: special-case some literals like '', [], {}, etc:
1441 # Last try: special-case some literals like '', [], {}, etc:
1441 if not found and oname_head in ["''",'""','[]','{}','()']:
1442 if not found and oname_head in ["''",'""','[]','{}','()']:
1442 obj = eval(oname_head)
1443 obj = eval(oname_head)
1443 found = True
1444 found = True
1444 ospace = 'Interactive'
1445 ospace = 'Interactive'
1445
1446
1446 return {'found':found, 'obj':obj, 'namespace':ospace,
1447 return {'found':found, 'obj':obj, 'namespace':ospace,
1447 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1448 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1448
1449
1449 def _ofind_property(self, oname, info):
1450 def _ofind_property(self, oname, info):
1450 """Second part of object finding, to look for property details."""
1451 """Second part of object finding, to look for property details."""
1451 if info.found:
1452 if info.found:
1452 # Get the docstring of the class property if it exists.
1453 # Get the docstring of the class property if it exists.
1453 path = oname.split('.')
1454 path = oname.split('.')
1454 root = '.'.join(path[:-1])
1455 root = '.'.join(path[:-1])
1455 if info.parent is not None:
1456 if info.parent is not None:
1456 try:
1457 try:
1457 target = getattr(info.parent, '__class__')
1458 target = getattr(info.parent, '__class__')
1458 # The object belongs to a class instance.
1459 # The object belongs to a class instance.
1459 try:
1460 try:
1460 target = getattr(target, path[-1])
1461 target = getattr(target, path[-1])
1461 # The class defines the object.
1462 # The class defines the object.
1462 if isinstance(target, property):
1463 if isinstance(target, property):
1463 oname = root + '.__class__.' + path[-1]
1464 oname = root + '.__class__.' + path[-1]
1464 info = Struct(self._ofind(oname))
1465 info = Struct(self._ofind(oname))
1465 except AttributeError: pass
1466 except AttributeError: pass
1466 except AttributeError: pass
1467 except AttributeError: pass
1467
1468
1468 # We return either the new info or the unmodified input if the object
1469 # We return either the new info or the unmodified input if the object
1469 # hadn't been found
1470 # hadn't been found
1470 return info
1471 return info
1471
1472
1472 def _object_find(self, oname, namespaces=None):
1473 def _object_find(self, oname, namespaces=None):
1473 """Find an object and return a struct with info about it."""
1474 """Find an object and return a struct with info about it."""
1474 inf = Struct(self._ofind(oname, namespaces))
1475 inf = Struct(self._ofind(oname, namespaces))
1475 return Struct(self._ofind_property(oname, inf))
1476 return Struct(self._ofind_property(oname, inf))
1476
1477
1477 def _inspect(self, meth, oname, namespaces=None, **kw):
1478 def _inspect(self, meth, oname, namespaces=None, **kw):
1478 """Generic interface to the inspector system.
1479 """Generic interface to the inspector system.
1479
1480
1480 This function is meant to be called by pdef, pdoc & friends."""
1481 This function is meant to be called by pdef, pdoc & friends."""
1481 info = self._object_find(oname)
1482 info = self._object_find(oname)
1482 if info.found:
1483 if info.found:
1483 pmethod = getattr(self.inspector, meth)
1484 pmethod = getattr(self.inspector, meth)
1484 formatter = format_screen if info.ismagic else None
1485 formatter = format_screen if info.ismagic else None
1485 if meth == 'pdoc':
1486 if meth == 'pdoc':
1486 pmethod(info.obj, oname, formatter)
1487 pmethod(info.obj, oname, formatter)
1487 elif meth == 'pinfo':
1488 elif meth == 'pinfo':
1488 pmethod(info.obj, oname, formatter, info, **kw)
1489 pmethod(info.obj, oname, formatter, info, **kw)
1489 else:
1490 else:
1490 pmethod(info.obj, oname)
1491 pmethod(info.obj, oname)
1491 else:
1492 else:
1492 print 'Object `%s` not found.' % oname
1493 print('Object `%s` not found.' % oname)
1493 return 'not found' # so callers can take other action
1494 return 'not found' # so callers can take other action
1494
1495
1495 def object_inspect(self, oname, detail_level=0):
1496 def object_inspect(self, oname, detail_level=0):
1496 with self.builtin_trap:
1497 with self.builtin_trap:
1497 info = self._object_find(oname)
1498 info = self._object_find(oname)
1498 if info.found:
1499 if info.found:
1499 return self.inspector.info(info.obj, oname, info=info,
1500 return self.inspector.info(info.obj, oname, info=info,
1500 detail_level=detail_level
1501 detail_level=detail_level
1501 )
1502 )
1502 else:
1503 else:
1503 return oinspect.object_info(name=oname, found=False)
1504 return oinspect.object_info(name=oname, found=False)
1504
1505
1505 #-------------------------------------------------------------------------
1506 #-------------------------------------------------------------------------
1506 # Things related to history management
1507 # Things related to history management
1507 #-------------------------------------------------------------------------
1508 #-------------------------------------------------------------------------
1508
1509
1509 def init_history(self):
1510 def init_history(self):
1510 """Sets up the command history, and starts regular autosaves."""
1511 """Sets up the command history, and starts regular autosaves."""
1511 self.history_manager = HistoryManager(shell=self, config=self.config)
1512 self.history_manager = HistoryManager(shell=self, config=self.config)
1512 self.configurables.append(self.history_manager)
1513 self.configurables.append(self.history_manager)
1513
1514
1514 #-------------------------------------------------------------------------
1515 #-------------------------------------------------------------------------
1515 # Things related to exception handling and tracebacks (not debugging)
1516 # Things related to exception handling and tracebacks (not debugging)
1516 #-------------------------------------------------------------------------
1517 #-------------------------------------------------------------------------
1517
1518
1518 def init_traceback_handlers(self, custom_exceptions):
1519 def init_traceback_handlers(self, custom_exceptions):
1519 # Syntax error handler.
1520 # Syntax error handler.
1520 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1521 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1521
1522
1522 # The interactive one is initialized with an offset, meaning we always
1523 # The interactive one is initialized with an offset, meaning we always
1523 # want to remove the topmost item in the traceback, which is our own
1524 # want to remove the topmost item in the traceback, which is our own
1524 # internal code. Valid modes: ['Plain','Context','Verbose']
1525 # internal code. Valid modes: ['Plain','Context','Verbose']
1525 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1526 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1526 color_scheme='NoColor',
1527 color_scheme='NoColor',
1527 tb_offset = 1,
1528 tb_offset = 1,
1528 check_cache=self.compile.check_cache)
1529 check_cache=self.compile.check_cache)
1529
1530
1530 # The instance will store a pointer to the system-wide exception hook,
1531 # The instance will store a pointer to the system-wide exception hook,
1531 # so that runtime code (such as magics) can access it. This is because
1532 # so that runtime code (such as magics) can access it. This is because
1532 # during the read-eval loop, it may get temporarily overwritten.
1533 # during the read-eval loop, it may get temporarily overwritten.
1533 self.sys_excepthook = sys.excepthook
1534 self.sys_excepthook = sys.excepthook
1534
1535
1535 # and add any custom exception handlers the user may have specified
1536 # and add any custom exception handlers the user may have specified
1536 self.set_custom_exc(*custom_exceptions)
1537 self.set_custom_exc(*custom_exceptions)
1537
1538
1538 # Set the exception mode
1539 # Set the exception mode
1539 self.InteractiveTB.set_mode(mode=self.xmode)
1540 self.InteractiveTB.set_mode(mode=self.xmode)
1540
1541
1541 def set_custom_exc(self, exc_tuple, handler):
1542 def set_custom_exc(self, exc_tuple, handler):
1542 """set_custom_exc(exc_tuple,handler)
1543 """set_custom_exc(exc_tuple,handler)
1543
1544
1544 Set a custom exception handler, which will be called if any of the
1545 Set a custom exception handler, which will be called if any of the
1545 exceptions in exc_tuple occur in the mainloop (specifically, in the
1546 exceptions in exc_tuple occur in the mainloop (specifically, in the
1546 run_code() method).
1547 run_code() method).
1547
1548
1548 Parameters
1549 Parameters
1549 ----------
1550 ----------
1550
1551
1551 exc_tuple : tuple of exception classes
1552 exc_tuple : tuple of exception classes
1552 A *tuple* of exception classes, for which to call the defined
1553 A *tuple* of exception classes, for which to call the defined
1553 handler. It is very important that you use a tuple, and NOT A
1554 handler. It is very important that you use a tuple, and NOT A
1554 LIST here, because of the way Python's except statement works. If
1555 LIST here, because of the way Python's except statement works. If
1555 you only want to trap a single exception, use a singleton tuple::
1556 you only want to trap a single exception, use a singleton tuple::
1556
1557
1557 exc_tuple == (MyCustomException,)
1558 exc_tuple == (MyCustomException,)
1558
1559
1559 handler : callable
1560 handler : callable
1560 handler must have the following signature::
1561 handler must have the following signature::
1561
1562
1562 def my_handler(self, etype, value, tb, tb_offset=None):
1563 def my_handler(self, etype, value, tb, tb_offset=None):
1563 ...
1564 ...
1564 return structured_traceback
1565 return structured_traceback
1565
1566
1566 Your handler must return a structured traceback (a list of strings),
1567 Your handler must return a structured traceback (a list of strings),
1567 or None.
1568 or None.
1568
1569
1569 This will be made into an instance method (via types.MethodType)
1570 This will be made into an instance method (via types.MethodType)
1570 of IPython itself, and it will be called if any of the exceptions
1571 of IPython itself, and it will be called if any of the exceptions
1571 listed in the exc_tuple are caught. If the handler is None, an
1572 listed in the exc_tuple are caught. If the handler is None, an
1572 internal basic one is used, which just prints basic info.
1573 internal basic one is used, which just prints basic info.
1573
1574
1574 To protect IPython from crashes, if your handler ever raises an
1575 To protect IPython from crashes, if your handler ever raises an
1575 exception or returns an invalid result, it will be immediately
1576 exception or returns an invalid result, it will be immediately
1576 disabled.
1577 disabled.
1577
1578
1578 WARNING: by putting in your own exception handler into IPython's main
1579 WARNING: by putting in your own exception handler into IPython's main
1579 execution loop, you run a very good chance of nasty crashes. This
1580 execution loop, you run a very good chance of nasty crashes. This
1580 facility should only be used if you really know what you are doing."""
1581 facility should only be used if you really know what you are doing."""
1581
1582
1582 assert type(exc_tuple)==type(()) , \
1583 assert type(exc_tuple)==type(()) , \
1583 "The custom exceptions must be given AS A TUPLE."
1584 "The custom exceptions must be given AS A TUPLE."
1584
1585
1585 def dummy_handler(self,etype,value,tb,tb_offset=None):
1586 def dummy_handler(self,etype,value,tb,tb_offset=None):
1586 print '*** Simple custom exception handler ***'
1587 print('*** Simple custom exception handler ***')
1587 print 'Exception type :',etype
1588 print('Exception type :',etype)
1588 print 'Exception value:',value
1589 print('Exception value:',value)
1589 print 'Traceback :',tb
1590 print('Traceback :',tb)
1590 #print 'Source code :','\n'.join(self.buffer)
1591 #print 'Source code :','\n'.join(self.buffer)
1591
1592
1592 def validate_stb(stb):
1593 def validate_stb(stb):
1593 """validate structured traceback return type
1594 """validate structured traceback return type
1594
1595
1595 return type of CustomTB *should* be a list of strings, but allow
1596 return type of CustomTB *should* be a list of strings, but allow
1596 single strings or None, which are harmless.
1597 single strings or None, which are harmless.
1597
1598
1598 This function will *always* return a list of strings,
1599 This function will *always* return a list of strings,
1599 and will raise a TypeError if stb is inappropriate.
1600 and will raise a TypeError if stb is inappropriate.
1600 """
1601 """
1601 msg = "CustomTB must return list of strings, not %r" % stb
1602 msg = "CustomTB must return list of strings, not %r" % stb
1602 if stb is None:
1603 if stb is None:
1603 return []
1604 return []
1604 elif isinstance(stb, basestring):
1605 elif isinstance(stb, basestring):
1605 return [stb]
1606 return [stb]
1606 elif not isinstance(stb, list):
1607 elif not isinstance(stb, list):
1607 raise TypeError(msg)
1608 raise TypeError(msg)
1608 # it's a list
1609 # it's a list
1609 for line in stb:
1610 for line in stb:
1610 # check every element
1611 # check every element
1611 if not isinstance(line, basestring):
1612 if not isinstance(line, basestring):
1612 raise TypeError(msg)
1613 raise TypeError(msg)
1613 return stb
1614 return stb
1614
1615
1615 if handler is None:
1616 if handler is None:
1616 wrapped = dummy_handler
1617 wrapped = dummy_handler
1617 else:
1618 else:
1618 def wrapped(self,etype,value,tb,tb_offset=None):
1619 def wrapped(self,etype,value,tb,tb_offset=None):
1619 """wrap CustomTB handler, to protect IPython from user code
1620 """wrap CustomTB handler, to protect IPython from user code
1620
1621
1621 This makes it harder (but not impossible) for custom exception
1622 This makes it harder (but not impossible) for custom exception
1622 handlers to crash IPython.
1623 handlers to crash IPython.
1623 """
1624 """
1624 try:
1625 try:
1625 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1626 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1626 return validate_stb(stb)
1627 return validate_stb(stb)
1627 except:
1628 except:
1628 # clear custom handler immediately
1629 # clear custom handler immediately
1629 self.set_custom_exc((), None)
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 # show the exception in handler first
1632 # show the exception in handler first
1632 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1633 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1633 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1634 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1634 print >> io.stdout, "The original exception:"
1635 print("The original exception:", file=io.stdout)
1635 stb = self.InteractiveTB.structured_traceback(
1636 stb = self.InteractiveTB.structured_traceback(
1636 (etype,value,tb), tb_offset=tb_offset
1637 (etype,value,tb), tb_offset=tb_offset
1637 )
1638 )
1638 return stb
1639 return stb
1639
1640
1640 self.CustomTB = types.MethodType(wrapped,self)
1641 self.CustomTB = types.MethodType(wrapped,self)
1641 self.custom_exceptions = exc_tuple
1642 self.custom_exceptions = exc_tuple
1642
1643
1643 def excepthook(self, etype, value, tb):
1644 def excepthook(self, etype, value, tb):
1644 """One more defense for GUI apps that call sys.excepthook.
1645 """One more defense for GUI apps that call sys.excepthook.
1645
1646
1646 GUI frameworks like wxPython trap exceptions and call
1647 GUI frameworks like wxPython trap exceptions and call
1647 sys.excepthook themselves. I guess this is a feature that
1648 sys.excepthook themselves. I guess this is a feature that
1648 enables them to keep running after exceptions that would
1649 enables them to keep running after exceptions that would
1649 otherwise kill their mainloop. This is a bother for IPython
1650 otherwise kill their mainloop. This is a bother for IPython
1650 which excepts to catch all of the program exceptions with a try:
1651 which excepts to catch all of the program exceptions with a try:
1651 except: statement.
1652 except: statement.
1652
1653
1653 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1654 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1654 any app directly invokes sys.excepthook, it will look to the user like
1655 any app directly invokes sys.excepthook, it will look to the user like
1655 IPython crashed. In order to work around this, we can disable the
1656 IPython crashed. In order to work around this, we can disable the
1656 CrashHandler and replace it with this excepthook instead, which prints a
1657 CrashHandler and replace it with this excepthook instead, which prints a
1657 regular traceback using our InteractiveTB. In this fashion, apps which
1658 regular traceback using our InteractiveTB. In this fashion, apps which
1658 call sys.excepthook will generate a regular-looking exception from
1659 call sys.excepthook will generate a regular-looking exception from
1659 IPython, and the CrashHandler will only be triggered by real IPython
1660 IPython, and the CrashHandler will only be triggered by real IPython
1660 crashes.
1661 crashes.
1661
1662
1662 This hook should be used sparingly, only in places which are not likely
1663 This hook should be used sparingly, only in places which are not likely
1663 to be true IPython errors.
1664 to be true IPython errors.
1664 """
1665 """
1665 self.showtraceback((etype,value,tb),tb_offset=0)
1666 self.showtraceback((etype,value,tb),tb_offset=0)
1666
1667
1667 def _get_exc_info(self, exc_tuple=None):
1668 def _get_exc_info(self, exc_tuple=None):
1668 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1669 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1669
1670
1670 Ensures sys.last_type,value,traceback hold the exc_info we found,
1671 Ensures sys.last_type,value,traceback hold the exc_info we found,
1671 from whichever source.
1672 from whichever source.
1672
1673
1673 raises ValueError if none of these contain any information
1674 raises ValueError if none of these contain any information
1674 """
1675 """
1675 if exc_tuple is None:
1676 if exc_tuple is None:
1676 etype, value, tb = sys.exc_info()
1677 etype, value, tb = sys.exc_info()
1677 else:
1678 else:
1678 etype, value, tb = exc_tuple
1679 etype, value, tb = exc_tuple
1679
1680
1680 if etype is None:
1681 if etype is None:
1681 if hasattr(sys, 'last_type'):
1682 if hasattr(sys, 'last_type'):
1682 etype, value, tb = sys.last_type, sys.last_value, \
1683 etype, value, tb = sys.last_type, sys.last_value, \
1683 sys.last_traceback
1684 sys.last_traceback
1684
1685
1685 if etype is None:
1686 if etype is None:
1686 raise ValueError("No exception to find")
1687 raise ValueError("No exception to find")
1687
1688
1688 # Now store the exception info in sys.last_type etc.
1689 # Now store the exception info in sys.last_type etc.
1689 # WARNING: these variables are somewhat deprecated and not
1690 # WARNING: these variables are somewhat deprecated and not
1690 # necessarily safe to use in a threaded environment, but tools
1691 # necessarily safe to use in a threaded environment, but tools
1691 # like pdb depend on their existence, so let's set them. If we
1692 # like pdb depend on their existence, so let's set them. If we
1692 # find problems in the field, we'll need to revisit their use.
1693 # find problems in the field, we'll need to revisit their use.
1693 sys.last_type = etype
1694 sys.last_type = etype
1694 sys.last_value = value
1695 sys.last_value = value
1695 sys.last_traceback = tb
1696 sys.last_traceback = tb
1696
1697
1697 return etype, value, tb
1698 return etype, value, tb
1698
1699
1699
1700
1700 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1701 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1701 exception_only=False):
1702 exception_only=False):
1702 """Display the exception that just occurred.
1703 """Display the exception that just occurred.
1703
1704
1704 If nothing is known about the exception, this is the method which
1705 If nothing is known about the exception, this is the method which
1705 should be used throughout the code for presenting user tracebacks,
1706 should be used throughout the code for presenting user tracebacks,
1706 rather than directly invoking the InteractiveTB object.
1707 rather than directly invoking the InteractiveTB object.
1707
1708
1708 A specific showsyntaxerror() also exists, but this method can take
1709 A specific showsyntaxerror() also exists, but this method can take
1709 care of calling it if needed, so unless you are explicitly catching a
1710 care of calling it if needed, so unless you are explicitly catching a
1710 SyntaxError exception, don't try to analyze the stack manually and
1711 SyntaxError exception, don't try to analyze the stack manually and
1711 simply call this method."""
1712 simply call this method."""
1712
1713
1713 try:
1714 try:
1714 try:
1715 try:
1715 etype, value, tb = self._get_exc_info(exc_tuple)
1716 etype, value, tb = self._get_exc_info(exc_tuple)
1716 except ValueError:
1717 except ValueError:
1717 self.write_err('No traceback available to show.\n')
1718 self.write_err('No traceback available to show.\n')
1718 return
1719 return
1719
1720
1720 if etype is SyntaxError:
1721 if etype is SyntaxError:
1721 # Though this won't be called by syntax errors in the input
1722 # Though this won't be called by syntax errors in the input
1722 # line, there may be SyntaxError cases with imported code.
1723 # line, there may be SyntaxError cases with imported code.
1723 self.showsyntaxerror(filename)
1724 self.showsyntaxerror(filename)
1724 elif etype is UsageError:
1725 elif etype is UsageError:
1725 self.write_err("UsageError: %s" % value)
1726 self.write_err("UsageError: %s" % value)
1726 elif issubclass(etype, RemoteError):
1727 elif issubclass(etype, RemoteError):
1727 # IPython.parallel remote exceptions.
1728 # IPython.parallel remote exceptions.
1728 # Draw the remote traceback, not the local one.
1729 # Draw the remote traceback, not the local one.
1729 self._showtraceback(etype, value, value.render_traceback())
1730 self._showtraceback(etype, value, value.render_traceback())
1730 else:
1731 else:
1731 if exception_only:
1732 if exception_only:
1732 stb = ['An exception has occurred, use %tb to see '
1733 stb = ['An exception has occurred, use %tb to see '
1733 'the full traceback.\n']
1734 'the full traceback.\n']
1734 stb.extend(self.InteractiveTB.get_exception_only(etype,
1735 stb.extend(self.InteractiveTB.get_exception_only(etype,
1735 value))
1736 value))
1736 else:
1737 else:
1737 stb = self.InteractiveTB.structured_traceback(etype,
1738 stb = self.InteractiveTB.structured_traceback(etype,
1738 value, tb, tb_offset=tb_offset)
1739 value, tb, tb_offset=tb_offset)
1739
1740
1740 self._showtraceback(etype, value, stb)
1741 self._showtraceback(etype, value, stb)
1741 if self.call_pdb:
1742 if self.call_pdb:
1742 # drop into debugger
1743 # drop into debugger
1743 self.debugger(force=True)
1744 self.debugger(force=True)
1744 return
1745 return
1745
1746
1746 # Actually show the traceback
1747 # Actually show the traceback
1747 self._showtraceback(etype, value, stb)
1748 self._showtraceback(etype, value, stb)
1748
1749
1749 except KeyboardInterrupt:
1750 except KeyboardInterrupt:
1750 self.write_err("\nKeyboardInterrupt\n")
1751 self.write_err("\nKeyboardInterrupt\n")
1751
1752
1752 def _showtraceback(self, etype, evalue, stb):
1753 def _showtraceback(self, etype, evalue, stb):
1753 """Actually show a traceback.
1754 """Actually show a traceback.
1754
1755
1755 Subclasses may override this method to put the traceback on a different
1756 Subclasses may override this method to put the traceback on a different
1756 place, like a side channel.
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 def showsyntaxerror(self, filename=None):
1761 def showsyntaxerror(self, filename=None):
1761 """Display the syntax error that just occurred.
1762 """Display the syntax error that just occurred.
1762
1763
1763 This doesn't display a stack trace because there isn't one.
1764 This doesn't display a stack trace because there isn't one.
1764
1765
1765 If a filename is given, it is stuffed in the exception instead
1766 If a filename is given, it is stuffed in the exception instead
1766 of what was there before (because Python's parser always uses
1767 of what was there before (because Python's parser always uses
1767 "<string>" when reading from a string).
1768 "<string>" when reading from a string).
1768 """
1769 """
1769 etype, value, last_traceback = self._get_exc_info()
1770 etype, value, last_traceback = self._get_exc_info()
1770
1771
1771 if filename and etype is SyntaxError:
1772 if filename and etype is SyntaxError:
1772 try:
1773 try:
1773 value.filename = filename
1774 value.filename = filename
1774 except:
1775 except:
1775 # Not the format we expect; leave it alone
1776 # Not the format we expect; leave it alone
1776 pass
1777 pass
1777
1778
1778 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1779 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1779 self._showtraceback(etype, value, stb)
1780 self._showtraceback(etype, value, stb)
1780
1781
1781 # This is overridden in TerminalInteractiveShell to show a message about
1782 # This is overridden in TerminalInteractiveShell to show a message about
1782 # the %paste magic.
1783 # the %paste magic.
1783 def showindentationerror(self):
1784 def showindentationerror(self):
1784 """Called by run_cell when there's an IndentationError in code entered
1785 """Called by run_cell when there's an IndentationError in code entered
1785 at the prompt.
1786 at the prompt.
1786
1787
1787 This is overridden in TerminalInteractiveShell to show a message about
1788 This is overridden in TerminalInteractiveShell to show a message about
1788 the %paste magic."""
1789 the %paste magic."""
1789 self.showsyntaxerror()
1790 self.showsyntaxerror()
1790
1791
1791 #-------------------------------------------------------------------------
1792 #-------------------------------------------------------------------------
1792 # Things related to readline
1793 # Things related to readline
1793 #-------------------------------------------------------------------------
1794 #-------------------------------------------------------------------------
1794
1795
1795 def init_readline(self):
1796 def init_readline(self):
1796 """Command history completion/saving/reloading."""
1797 """Command history completion/saving/reloading."""
1797
1798
1798 if self.readline_use:
1799 if self.readline_use:
1799 import IPython.utils.rlineimpl as readline
1800 import IPython.utils.rlineimpl as readline
1800
1801
1801 self.rl_next_input = None
1802 self.rl_next_input = None
1802 self.rl_do_indent = False
1803 self.rl_do_indent = False
1803
1804
1804 if not self.readline_use or not readline.have_readline:
1805 if not self.readline_use or not readline.have_readline:
1805 self.has_readline = False
1806 self.has_readline = False
1806 self.readline = None
1807 self.readline = None
1807 # Set a number of methods that depend on readline to be no-op
1808 # Set a number of methods that depend on readline to be no-op
1808 self.readline_no_record = no_op_context
1809 self.readline_no_record = no_op_context
1809 self.set_readline_completer = no_op
1810 self.set_readline_completer = no_op
1810 self.set_custom_completer = no_op
1811 self.set_custom_completer = no_op
1811 self.set_completer_frame = no_op
1812 self.set_completer_frame = no_op
1812 if self.readline_use:
1813 if self.readline_use:
1813 warn('Readline services not available or not loaded.')
1814 warn('Readline services not available or not loaded.')
1814 else:
1815 else:
1815 self.has_readline = True
1816 self.has_readline = True
1816 self.readline = readline
1817 self.readline = readline
1817 sys.modules['readline'] = readline
1818 sys.modules['readline'] = readline
1818
1819
1819 # Platform-specific configuration
1820 # Platform-specific configuration
1820 if os.name == 'nt':
1821 if os.name == 'nt':
1821 # FIXME - check with Frederick to see if we can harmonize
1822 # FIXME - check with Frederick to see if we can harmonize
1822 # naming conventions with pyreadline to avoid this
1823 # naming conventions with pyreadline to avoid this
1823 # platform-dependent check
1824 # platform-dependent check
1824 self.readline_startup_hook = readline.set_pre_input_hook
1825 self.readline_startup_hook = readline.set_pre_input_hook
1825 else:
1826 else:
1826 self.readline_startup_hook = readline.set_startup_hook
1827 self.readline_startup_hook = readline.set_startup_hook
1827
1828
1828 # Load user's initrc file (readline config)
1829 # Load user's initrc file (readline config)
1829 # Or if libedit is used, load editrc.
1830 # Or if libedit is used, load editrc.
1830 inputrc_name = os.environ.get('INPUTRC')
1831 inputrc_name = os.environ.get('INPUTRC')
1831 if inputrc_name is None:
1832 if inputrc_name is None:
1832 inputrc_name = '.inputrc'
1833 inputrc_name = '.inputrc'
1833 if readline.uses_libedit:
1834 if readline.uses_libedit:
1834 inputrc_name = '.editrc'
1835 inputrc_name = '.editrc'
1835 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1836 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1836 if os.path.isfile(inputrc_name):
1837 if os.path.isfile(inputrc_name):
1837 try:
1838 try:
1838 readline.read_init_file(inputrc_name)
1839 readline.read_init_file(inputrc_name)
1839 except:
1840 except:
1840 warn('Problems reading readline initialization file <%s>'
1841 warn('Problems reading readline initialization file <%s>'
1841 % inputrc_name)
1842 % inputrc_name)
1842
1843
1843 # Configure readline according to user's prefs
1844 # Configure readline according to user's prefs
1844 # This is only done if GNU readline is being used. If libedit
1845 # This is only done if GNU readline is being used. If libedit
1845 # is being used (as on Leopard) the readline config is
1846 # is being used (as on Leopard) the readline config is
1846 # not run as the syntax for libedit is different.
1847 # not run as the syntax for libedit is different.
1847 if not readline.uses_libedit:
1848 if not readline.uses_libedit:
1848 for rlcommand in self.readline_parse_and_bind:
1849 for rlcommand in self.readline_parse_and_bind:
1849 #print "loading rl:",rlcommand # dbg
1850 #print "loading rl:",rlcommand # dbg
1850 readline.parse_and_bind(rlcommand)
1851 readline.parse_and_bind(rlcommand)
1851
1852
1852 # Remove some chars from the delimiters list. If we encounter
1853 # Remove some chars from the delimiters list. If we encounter
1853 # unicode chars, discard them.
1854 # unicode chars, discard them.
1854 delims = readline.get_completer_delims()
1855 delims = readline.get_completer_delims()
1855 if not py3compat.PY3:
1856 if not py3compat.PY3:
1856 delims = delims.encode("ascii", "ignore")
1857 delims = delims.encode("ascii", "ignore")
1857 for d in self.readline_remove_delims:
1858 for d in self.readline_remove_delims:
1858 delims = delims.replace(d, "")
1859 delims = delims.replace(d, "")
1859 delims = delims.replace(ESC_MAGIC, '')
1860 delims = delims.replace(ESC_MAGIC, '')
1860 readline.set_completer_delims(delims)
1861 readline.set_completer_delims(delims)
1861 # otherwise we end up with a monster history after a while:
1862 # otherwise we end up with a monster history after a while:
1862 readline.set_history_length(self.history_length)
1863 readline.set_history_length(self.history_length)
1863
1864
1864 self.refill_readline_hist()
1865 self.refill_readline_hist()
1865 self.readline_no_record = ReadlineNoRecord(self)
1866 self.readline_no_record = ReadlineNoRecord(self)
1866
1867
1867 # Configure auto-indent for all platforms
1868 # Configure auto-indent for all platforms
1868 self.set_autoindent(self.autoindent)
1869 self.set_autoindent(self.autoindent)
1869
1870
1870 def refill_readline_hist(self):
1871 def refill_readline_hist(self):
1871 # Load the last 1000 lines from history
1872 # Load the last 1000 lines from history
1872 self.readline.clear_history()
1873 self.readline.clear_history()
1873 stdin_encoding = sys.stdin.encoding or "utf-8"
1874 stdin_encoding = sys.stdin.encoding or "utf-8"
1874 last_cell = u""
1875 last_cell = u""
1875 for _, _, cell in self.history_manager.get_tail(1000,
1876 for _, _, cell in self.history_manager.get_tail(1000,
1876 include_latest=True):
1877 include_latest=True):
1877 # Ignore blank lines and consecutive duplicates
1878 # Ignore blank lines and consecutive duplicates
1878 cell = cell.rstrip()
1879 cell = cell.rstrip()
1879 if cell and (cell != last_cell):
1880 if cell and (cell != last_cell):
1880 if self.multiline_history:
1881 if self.multiline_history:
1881 self.readline.add_history(py3compat.unicode_to_str(cell,
1882 self.readline.add_history(py3compat.unicode_to_str(cell,
1882 stdin_encoding))
1883 stdin_encoding))
1883 else:
1884 else:
1884 for line in cell.splitlines():
1885 for line in cell.splitlines():
1885 self.readline.add_history(py3compat.unicode_to_str(line,
1886 self.readline.add_history(py3compat.unicode_to_str(line,
1886 stdin_encoding))
1887 stdin_encoding))
1887 last_cell = cell
1888 last_cell = cell
1888
1889
1889 def set_next_input(self, s):
1890 def set_next_input(self, s):
1890 """ Sets the 'default' input string for the next command line.
1891 """ Sets the 'default' input string for the next command line.
1891
1892
1892 Requires readline.
1893 Requires readline.
1893
1894
1894 Example:
1895 Example:
1895
1896
1896 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1897 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1897 [D:\ipython]|2> Hello Word_ # cursor is here
1898 [D:\ipython]|2> Hello Word_ # cursor is here
1898 """
1899 """
1899 self.rl_next_input = py3compat.cast_bytes_py2(s)
1900 self.rl_next_input = py3compat.cast_bytes_py2(s)
1900
1901
1901 # Maybe move this to the terminal subclass?
1902 # Maybe move this to the terminal subclass?
1902 def pre_readline(self):
1903 def pre_readline(self):
1903 """readline hook to be used at the start of each line.
1904 """readline hook to be used at the start of each line.
1904
1905
1905 Currently it handles auto-indent only."""
1906 Currently it handles auto-indent only."""
1906
1907
1907 if self.rl_do_indent:
1908 if self.rl_do_indent:
1908 self.readline.insert_text(self._indent_current_str())
1909 self.readline.insert_text(self._indent_current_str())
1909 if self.rl_next_input is not None:
1910 if self.rl_next_input is not None:
1910 self.readline.insert_text(self.rl_next_input)
1911 self.readline.insert_text(self.rl_next_input)
1911 self.rl_next_input = None
1912 self.rl_next_input = None
1912
1913
1913 def _indent_current_str(self):
1914 def _indent_current_str(self):
1914 """return the current level of indentation as a string"""
1915 """return the current level of indentation as a string"""
1915 return self.input_splitter.indent_spaces * ' '
1916 return self.input_splitter.indent_spaces * ' '
1916
1917
1917 #-------------------------------------------------------------------------
1918 #-------------------------------------------------------------------------
1918 # Things related to text completion
1919 # Things related to text completion
1919 #-------------------------------------------------------------------------
1920 #-------------------------------------------------------------------------
1920
1921
1921 def init_completer(self):
1922 def init_completer(self):
1922 """Initialize the completion machinery.
1923 """Initialize the completion machinery.
1923
1924
1924 This creates completion machinery that can be used by client code,
1925 This creates completion machinery that can be used by client code,
1925 either interactively in-process (typically triggered by the readline
1926 either interactively in-process (typically triggered by the readline
1926 library), programatically (such as in test suites) or out-of-prcess
1927 library), programatically (such as in test suites) or out-of-prcess
1927 (typically over the network by remote frontends).
1928 (typically over the network by remote frontends).
1928 """
1929 """
1929 from IPython.core.completer import IPCompleter
1930 from IPython.core.completer import IPCompleter
1930 from IPython.core.completerlib import (module_completer,
1931 from IPython.core.completerlib import (module_completer,
1931 magic_run_completer, cd_completer, reset_completer)
1932 magic_run_completer, cd_completer, reset_completer)
1932
1933
1933 self.Completer = IPCompleter(shell=self,
1934 self.Completer = IPCompleter(shell=self,
1934 namespace=self.user_ns,
1935 namespace=self.user_ns,
1935 global_namespace=self.user_global_ns,
1936 global_namespace=self.user_global_ns,
1936 alias_table=self.alias_manager.alias_table,
1937 alias_table=self.alias_manager.alias_table,
1937 use_readline=self.has_readline,
1938 use_readline=self.has_readline,
1938 config=self.config,
1939 config=self.config,
1939 )
1940 )
1940 self.configurables.append(self.Completer)
1941 self.configurables.append(self.Completer)
1941
1942
1942 # Add custom completers to the basic ones built into IPCompleter
1943 # Add custom completers to the basic ones built into IPCompleter
1943 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1944 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1944 self.strdispatchers['complete_command'] = sdisp
1945 self.strdispatchers['complete_command'] = sdisp
1945 self.Completer.custom_completers = sdisp
1946 self.Completer.custom_completers = sdisp
1946
1947
1947 self.set_hook('complete_command', module_completer, str_key = 'import')
1948 self.set_hook('complete_command', module_completer, str_key = 'import')
1948 self.set_hook('complete_command', module_completer, str_key = 'from')
1949 self.set_hook('complete_command', module_completer, str_key = 'from')
1949 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1950 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1950 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1951 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1951 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1952 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1952
1953
1953 # Only configure readline if we truly are using readline. IPython can
1954 # Only configure readline if we truly are using readline. IPython can
1954 # do tab-completion over the network, in GUIs, etc, where readline
1955 # do tab-completion over the network, in GUIs, etc, where readline
1955 # itself may be absent
1956 # itself may be absent
1956 if self.has_readline:
1957 if self.has_readline:
1957 self.set_readline_completer()
1958 self.set_readline_completer()
1958
1959
1959 def complete(self, text, line=None, cursor_pos=None):
1960 def complete(self, text, line=None, cursor_pos=None):
1960 """Return the completed text and a list of completions.
1961 """Return the completed text and a list of completions.
1961
1962
1962 Parameters
1963 Parameters
1963 ----------
1964 ----------
1964
1965
1965 text : string
1966 text : string
1966 A string of text to be completed on. It can be given as empty and
1967 A string of text to be completed on. It can be given as empty and
1967 instead a line/position pair are given. In this case, the
1968 instead a line/position pair are given. In this case, the
1968 completer itself will split the line like readline does.
1969 completer itself will split the line like readline does.
1969
1970
1970 line : string, optional
1971 line : string, optional
1971 The complete line that text is part of.
1972 The complete line that text is part of.
1972
1973
1973 cursor_pos : int, optional
1974 cursor_pos : int, optional
1974 The position of the cursor on the input line.
1975 The position of the cursor on the input line.
1975
1976
1976 Returns
1977 Returns
1977 -------
1978 -------
1978 text : string
1979 text : string
1979 The actual text that was completed.
1980 The actual text that was completed.
1980
1981
1981 matches : list
1982 matches : list
1982 A sorted list with all possible completions.
1983 A sorted list with all possible completions.
1983
1984
1984 The optional arguments allow the completion to take more context into
1985 The optional arguments allow the completion to take more context into
1985 account, and are part of the low-level completion API.
1986 account, and are part of the low-level completion API.
1986
1987
1987 This is a wrapper around the completion mechanism, similar to what
1988 This is a wrapper around the completion mechanism, similar to what
1988 readline does at the command line when the TAB key is hit. By
1989 readline does at the command line when the TAB key is hit. By
1989 exposing it as a method, it can be used by other non-readline
1990 exposing it as a method, it can be used by other non-readline
1990 environments (such as GUIs) for text completion.
1991 environments (such as GUIs) for text completion.
1991
1992
1992 Simple usage example:
1993 Simple usage example:
1993
1994
1994 In [1]: x = 'hello'
1995 In [1]: x = 'hello'
1995
1996
1996 In [2]: _ip.complete('x.l')
1997 In [2]: _ip.complete('x.l')
1997 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1998 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1998 """
1999 """
1999
2000
2000 # Inject names into __builtin__ so we can complete on the added names.
2001 # Inject names into __builtin__ so we can complete on the added names.
2001 with self.builtin_trap:
2002 with self.builtin_trap:
2002 return self.Completer.complete(text, line, cursor_pos)
2003 return self.Completer.complete(text, line, cursor_pos)
2003
2004
2004 def set_custom_completer(self, completer, pos=0):
2005 def set_custom_completer(self, completer, pos=0):
2005 """Adds a new custom completer function.
2006 """Adds a new custom completer function.
2006
2007
2007 The position argument (defaults to 0) is the index in the completers
2008 The position argument (defaults to 0) is the index in the completers
2008 list where you want the completer to be inserted."""
2009 list where you want the completer to be inserted."""
2009
2010
2010 newcomp = types.MethodType(completer,self.Completer)
2011 newcomp = types.MethodType(completer,self.Completer)
2011 self.Completer.matchers.insert(pos,newcomp)
2012 self.Completer.matchers.insert(pos,newcomp)
2012
2013
2013 def set_readline_completer(self):
2014 def set_readline_completer(self):
2014 """Reset readline's completer to be our own."""
2015 """Reset readline's completer to be our own."""
2015 self.readline.set_completer(self.Completer.rlcomplete)
2016 self.readline.set_completer(self.Completer.rlcomplete)
2016
2017
2017 def set_completer_frame(self, frame=None):
2018 def set_completer_frame(self, frame=None):
2018 """Set the frame of the completer."""
2019 """Set the frame of the completer."""
2019 if frame:
2020 if frame:
2020 self.Completer.namespace = frame.f_locals
2021 self.Completer.namespace = frame.f_locals
2021 self.Completer.global_namespace = frame.f_globals
2022 self.Completer.global_namespace = frame.f_globals
2022 else:
2023 else:
2023 self.Completer.namespace = self.user_ns
2024 self.Completer.namespace = self.user_ns
2024 self.Completer.global_namespace = self.user_global_ns
2025 self.Completer.global_namespace = self.user_global_ns
2025
2026
2026 #-------------------------------------------------------------------------
2027 #-------------------------------------------------------------------------
2027 # Things related to magics
2028 # Things related to magics
2028 #-------------------------------------------------------------------------
2029 #-------------------------------------------------------------------------
2029
2030
2030 def init_magics(self):
2031 def init_magics(self):
2031 from IPython.core import magics as m
2032 from IPython.core import magics as m
2032 self.magics_manager = magic.MagicsManager(shell=self,
2033 self.magics_manager = magic.MagicsManager(shell=self,
2033 confg=self.config,
2034 confg=self.config,
2034 user_magics=m.UserMagics(self))
2035 user_magics=m.UserMagics(self))
2035 self.configurables.append(self.magics_manager)
2036 self.configurables.append(self.magics_manager)
2036
2037
2037 # Expose as public API from the magics manager
2038 # Expose as public API from the magics manager
2038 self.register_magics = self.magics_manager.register
2039 self.register_magics = self.magics_manager.register
2039 self.register_magic_function = self.magics_manager.register_function
2040 self.register_magic_function = self.magics_manager.register_function
2040 self.define_magic = self.magics_manager.define_magic
2041 self.define_magic = self.magics_manager.define_magic
2041
2042
2042 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2043 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2043 m.ConfigMagics, m.DeprecatedMagics, m.ExecutionMagics,
2044 m.ConfigMagics, m.DeprecatedMagics, m.ExecutionMagics,
2044 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2045 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2045 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2046 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2046 )
2047 )
2047
2048
2048 # FIXME: Move the color initialization to the DisplayHook, which
2049 # FIXME: Move the color initialization to the DisplayHook, which
2049 # should be split into a prompt manager and displayhook. We probably
2050 # should be split into a prompt manager and displayhook. We probably
2050 # even need a centralize colors management object.
2051 # even need a centralize colors management object.
2051 self.magic('colors %s' % self.colors)
2052 self.magic('colors %s' % self.colors)
2052
2053
2053 def run_line_magic(self, magic_name, line):
2054 def run_line_magic(self, magic_name, line):
2054 """Execute the given line magic.
2055 """Execute the given line magic.
2055
2056
2056 Parameters
2057 Parameters
2057 ----------
2058 ----------
2058 magic_name : str
2059 magic_name : str
2059 Name of the desired magic function, without '%' prefix.
2060 Name of the desired magic function, without '%' prefix.
2060
2061
2061 line : str
2062 line : str
2062 The rest of the input line as a single string.
2063 The rest of the input line as a single string.
2063 """
2064 """
2064 fn = self.find_line_magic(magic_name)
2065 fn = self.find_line_magic(magic_name)
2065 if fn is None:
2066 if fn is None:
2066 cm = self.find_cell_magic(magic_name)
2067 cm = self.find_cell_magic(magic_name)
2067 etpl = "Line magic function `%%%s` not found%s."
2068 etpl = "Line magic function `%%%s` not found%s."
2068 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2069 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2069 'did you mean that instead?)' % magic_name )
2070 'did you mean that instead?)' % magic_name )
2070 error(etpl % (magic_name, extra))
2071 error(etpl % (magic_name, extra))
2071 else:
2072 else:
2072 # Note: this is the distance in the stack to the user's frame.
2073 # Note: this is the distance in the stack to the user's frame.
2073 # This will need to be updated if the internal calling logic gets
2074 # This will need to be updated if the internal calling logic gets
2074 # refactored, or else we'll be expanding the wrong variables.
2075 # refactored, or else we'll be expanding the wrong variables.
2075 stack_depth = 2
2076 stack_depth = 2
2076 magic_arg_s = self.var_expand(line, stack_depth)
2077 magic_arg_s = self.var_expand(line, stack_depth)
2077 # Put magic args in a list so we can call with f(*a) syntax
2078 # Put magic args in a list so we can call with f(*a) syntax
2078 args = [magic_arg_s]
2079 args = [magic_arg_s]
2079 # Grab local namespace if we need it:
2080 # Grab local namespace if we need it:
2080 if getattr(fn, "needs_local_scope", False):
2081 if getattr(fn, "needs_local_scope", False):
2081 args.append(sys._getframe(stack_depth).f_locals)
2082 args.append(sys._getframe(stack_depth).f_locals)
2082 with self.builtin_trap:
2083 with self.builtin_trap:
2083 result = fn(*args)
2084 result = fn(*args)
2084 return result
2085 return result
2085
2086
2086 def run_cell_magic(self, magic_name, line, cell):
2087 def run_cell_magic(self, magic_name, line, cell):
2087 """Execute the given cell magic.
2088 """Execute the given cell magic.
2088
2089
2089 Parameters
2090 Parameters
2090 ----------
2091 ----------
2091 magic_name : str
2092 magic_name : str
2092 Name of the desired magic function, without '%' prefix.
2093 Name of the desired magic function, without '%' prefix.
2093
2094
2094 line : str
2095 line : str
2095 The rest of the first input line as a single string.
2096 The rest of the first input line as a single string.
2096
2097
2097 cell : str
2098 cell : str
2098 The body of the cell as a (possibly multiline) string.
2099 The body of the cell as a (possibly multiline) string.
2099 """
2100 """
2100 fn = self.find_cell_magic(magic_name)
2101 fn = self.find_cell_magic(magic_name)
2101 if fn is None:
2102 if fn is None:
2102 lm = self.find_line_magic(magic_name)
2103 lm = self.find_line_magic(magic_name)
2103 etpl = "Cell magic function `%%%%%s` not found%s."
2104 etpl = "Cell magic function `%%%%%s` not found%s."
2104 extra = '' if lm is None else (' (But line magic `%%%s` exists, '
2105 extra = '' if lm is None else (' (But line magic `%%%s` exists, '
2105 'did you mean that instead?)' % magic_name )
2106 'did you mean that instead?)' % magic_name )
2106 error(etpl % (magic_name, extra))
2107 error(etpl % (magic_name, extra))
2107 else:
2108 else:
2108 # Note: this is the distance in the stack to the user's frame.
2109 # Note: this is the distance in the stack to the user's frame.
2109 # This will need to be updated if the internal calling logic gets
2110 # This will need to be updated if the internal calling logic gets
2110 # refactored, or else we'll be expanding the wrong variables.
2111 # refactored, or else we'll be expanding the wrong variables.
2111 stack_depth = 2
2112 stack_depth = 2
2112 magic_arg_s = self.var_expand(line, stack_depth)
2113 magic_arg_s = self.var_expand(line, stack_depth)
2113 with self.builtin_trap:
2114 with self.builtin_trap:
2114 result = fn(line, cell)
2115 result = fn(line, cell)
2115 return result
2116 return result
2116
2117
2117 def find_line_magic(self, magic_name):
2118 def find_line_magic(self, magic_name):
2118 """Find and return a line magic by name.
2119 """Find and return a line magic by name.
2119
2120
2120 Returns None if the magic isn't found."""
2121 Returns None if the magic isn't found."""
2121 return self.magics_manager.magics['line'].get(magic_name)
2122 return self.magics_manager.magics['line'].get(magic_name)
2122
2123
2123 def find_cell_magic(self, magic_name):
2124 def find_cell_magic(self, magic_name):
2124 """Find and return a cell magic by name.
2125 """Find and return a cell magic by name.
2125
2126
2126 Returns None if the magic isn't found."""
2127 Returns None if the magic isn't found."""
2127 return self.magics_manager.magics['cell'].get(magic_name)
2128 return self.magics_manager.magics['cell'].get(magic_name)
2128
2129
2129 def find_magic(self, magic_name, magic_kind='line'):
2130 def find_magic(self, magic_name, magic_kind='line'):
2130 """Find and return a magic of the given type by name.
2131 """Find and return a magic of the given type by name.
2131
2132
2132 Returns None if the magic isn't found."""
2133 Returns None if the magic isn't found."""
2133 return self.magics_manager.magics[magic_kind].get(magic_name)
2134 return self.magics_manager.magics[magic_kind].get(magic_name)
2134
2135
2135 def magic(self, arg_s):
2136 def magic(self, arg_s):
2136 """DEPRECATED. Use run_line_magic() instead.
2137 """DEPRECATED. Use run_line_magic() instead.
2137
2138
2138 Call a magic function by name.
2139 Call a magic function by name.
2139
2140
2140 Input: a string containing the name of the magic function to call and
2141 Input: a string containing the name of the magic function to call and
2141 any additional arguments to be passed to the magic.
2142 any additional arguments to be passed to the magic.
2142
2143
2143 magic('name -opt foo bar') is equivalent to typing at the ipython
2144 magic('name -opt foo bar') is equivalent to typing at the ipython
2144 prompt:
2145 prompt:
2145
2146
2146 In[1]: %name -opt foo bar
2147 In[1]: %name -opt foo bar
2147
2148
2148 To call a magic without arguments, simply use magic('name').
2149 To call a magic without arguments, simply use magic('name').
2149
2150
2150 This provides a proper Python function to call IPython's magics in any
2151 This provides a proper Python function to call IPython's magics in any
2151 valid Python code you can type at the interpreter, including loops and
2152 valid Python code you can type at the interpreter, including loops and
2152 compound statements.
2153 compound statements.
2153 """
2154 """
2154 # TODO: should we issue a loud deprecation warning here?
2155 # TODO: should we issue a loud deprecation warning here?
2155 magic_name, _, magic_arg_s = arg_s.partition(' ')
2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2156 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2157 return self.run_line_magic(magic_name, magic_arg_s)
2158 return self.run_line_magic(magic_name, magic_arg_s)
2158
2159
2159 #-------------------------------------------------------------------------
2160 #-------------------------------------------------------------------------
2160 # Things related to macros
2161 # Things related to macros
2161 #-------------------------------------------------------------------------
2162 #-------------------------------------------------------------------------
2162
2163
2163 def define_macro(self, name, themacro):
2164 def define_macro(self, name, themacro):
2164 """Define a new macro
2165 """Define a new macro
2165
2166
2166 Parameters
2167 Parameters
2167 ----------
2168 ----------
2168 name : str
2169 name : str
2169 The name of the macro.
2170 The name of the macro.
2170 themacro : str or Macro
2171 themacro : str or Macro
2171 The action to do upon invoking the macro. If a string, a new
2172 The action to do upon invoking the macro. If a string, a new
2172 Macro object is created by passing the string to it.
2173 Macro object is created by passing the string to it.
2173 """
2174 """
2174
2175
2175 from IPython.core import macro
2176 from IPython.core import macro
2176
2177
2177 if isinstance(themacro, basestring):
2178 if isinstance(themacro, basestring):
2178 themacro = macro.Macro(themacro)
2179 themacro = macro.Macro(themacro)
2179 if not isinstance(themacro, macro.Macro):
2180 if not isinstance(themacro, macro.Macro):
2180 raise ValueError('A macro must be a string or a Macro instance.')
2181 raise ValueError('A macro must be a string or a Macro instance.')
2181 self.user_ns[name] = themacro
2182 self.user_ns[name] = themacro
2182
2183
2183 #-------------------------------------------------------------------------
2184 #-------------------------------------------------------------------------
2184 # Things related to the running of system commands
2185 # Things related to the running of system commands
2185 #-------------------------------------------------------------------------
2186 #-------------------------------------------------------------------------
2186
2187
2187 def system_piped(self, cmd):
2188 def system_piped(self, cmd):
2188 """Call the given cmd in a subprocess, piping stdout/err
2189 """Call the given cmd in a subprocess, piping stdout/err
2189
2190
2190 Parameters
2191 Parameters
2191 ----------
2192 ----------
2192 cmd : str
2193 cmd : str
2193 Command to execute (can not end in '&', as background processes are
2194 Command to execute (can not end in '&', as background processes are
2194 not supported. Should not be a command that expects input
2195 not supported. Should not be a command that expects input
2195 other than simple text.
2196 other than simple text.
2196 """
2197 """
2197 if cmd.rstrip().endswith('&'):
2198 if cmd.rstrip().endswith('&'):
2198 # this is *far* from a rigorous test
2199 # this is *far* from a rigorous test
2199 # We do not support backgrounding processes because we either use
2200 # We do not support backgrounding processes because we either use
2200 # pexpect or pipes to read from. Users can always just call
2201 # pexpect or pipes to read from. Users can always just call
2201 # os.system() or use ip.system=ip.system_raw
2202 # os.system() or use ip.system=ip.system_raw
2202 # if they really want a background process.
2203 # if they really want a background process.
2203 raise OSError("Background processes not supported.")
2204 raise OSError("Background processes not supported.")
2204
2205
2205 # we explicitly do NOT return the subprocess status code, because
2206 # we explicitly do NOT return the subprocess status code, because
2206 # a non-None value would trigger :func:`sys.displayhook` calls.
2207 # a non-None value would trigger :func:`sys.displayhook` calls.
2207 # Instead, we store the exit_code in user_ns.
2208 # Instead, we store the exit_code in user_ns.
2208 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2209 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2209
2210
2210 def system_raw(self, cmd):
2211 def system_raw(self, cmd):
2211 """Call the given cmd in a subprocess using os.system
2212 """Call the given cmd in a subprocess using os.system
2212
2213
2213 Parameters
2214 Parameters
2214 ----------
2215 ----------
2215 cmd : str
2216 cmd : str
2216 Command to execute.
2217 Command to execute.
2217 """
2218 """
2218 cmd = self.var_expand(cmd, depth=1)
2219 cmd = self.var_expand(cmd, depth=1)
2219 # protect os.system from UNC paths on Windows, which it can't handle:
2220 # protect os.system from UNC paths on Windows, which it can't handle:
2220 if sys.platform == 'win32':
2221 if sys.platform == 'win32':
2221 from IPython.utils._process_win32 import AvoidUNCPath
2222 from IPython.utils._process_win32 import AvoidUNCPath
2222 with AvoidUNCPath() as path:
2223 with AvoidUNCPath() as path:
2223 if path is not None:
2224 if path is not None:
2224 cmd = '"pushd %s &&"%s' % (path, cmd)
2225 cmd = '"pushd %s &&"%s' % (path, cmd)
2225 cmd = py3compat.unicode_to_str(cmd)
2226 cmd = py3compat.unicode_to_str(cmd)
2226 ec = os.system(cmd)
2227 ec = os.system(cmd)
2227 else:
2228 else:
2228 cmd = py3compat.unicode_to_str(cmd)
2229 cmd = py3compat.unicode_to_str(cmd)
2229 ec = os.system(cmd)
2230 ec = os.system(cmd)
2230
2231
2231 # We explicitly do NOT return the subprocess status code, because
2232 # We explicitly do NOT return the subprocess status code, because
2232 # a non-None value would trigger :func:`sys.displayhook` calls.
2233 # a non-None value would trigger :func:`sys.displayhook` calls.
2233 # Instead, we store the exit_code in user_ns.
2234 # Instead, we store the exit_code in user_ns.
2234 self.user_ns['_exit_code'] = ec
2235 self.user_ns['_exit_code'] = ec
2235
2236
2236 # use piped system by default, because it is better behaved
2237 # use piped system by default, because it is better behaved
2237 system = system_piped
2238 system = system_piped
2238
2239
2239 def getoutput(self, cmd, split=True, depth=0):
2240 def getoutput(self, cmd, split=True, depth=0):
2240 """Get output (possibly including stderr) from a subprocess.
2241 """Get output (possibly including stderr) from a subprocess.
2241
2242
2242 Parameters
2243 Parameters
2243 ----------
2244 ----------
2244 cmd : str
2245 cmd : str
2245 Command to execute (can not end in '&', as background processes are
2246 Command to execute (can not end in '&', as background processes are
2246 not supported.
2247 not supported.
2247 split : bool, optional
2248 split : bool, optional
2248 If True, split the output into an IPython SList. Otherwise, an
2249 If True, split the output into an IPython SList. Otherwise, an
2249 IPython LSString is returned. These are objects similar to normal
2250 IPython LSString is returned. These are objects similar to normal
2250 lists and strings, with a few convenience attributes for easier
2251 lists and strings, with a few convenience attributes for easier
2251 manipulation of line-based output. You can use '?' on them for
2252 manipulation of line-based output. You can use '?' on them for
2252 details.
2253 details.
2253 depth : int, optional
2254 depth : int, optional
2254 How many frames above the caller are the local variables which should
2255 How many frames above the caller are the local variables which should
2255 be expanded in the command string? The default (0) assumes that the
2256 be expanded in the command string? The default (0) assumes that the
2256 expansion variables are in the stack frame calling this function.
2257 expansion variables are in the stack frame calling this function.
2257 """
2258 """
2258 if cmd.rstrip().endswith('&'):
2259 if cmd.rstrip().endswith('&'):
2259 # this is *far* from a rigorous test
2260 # this is *far* from a rigorous test
2260 raise OSError("Background processes not supported.")
2261 raise OSError("Background processes not supported.")
2261 out = getoutput(self.var_expand(cmd, depth=depth+1))
2262 out = getoutput(self.var_expand(cmd, depth=depth+1))
2262 if split:
2263 if split:
2263 out = SList(out.splitlines())
2264 out = SList(out.splitlines())
2264 else:
2265 else:
2265 out = LSString(out)
2266 out = LSString(out)
2266 return out
2267 return out
2267
2268
2268 #-------------------------------------------------------------------------
2269 #-------------------------------------------------------------------------
2269 # Things related to aliases
2270 # Things related to aliases
2270 #-------------------------------------------------------------------------
2271 #-------------------------------------------------------------------------
2271
2272
2272 def init_alias(self):
2273 def init_alias(self):
2273 self.alias_manager = AliasManager(shell=self, config=self.config)
2274 self.alias_manager = AliasManager(shell=self, config=self.config)
2274 self.configurables.append(self.alias_manager)
2275 self.configurables.append(self.alias_manager)
2275 self.ns_table['alias'] = self.alias_manager.alias_table,
2276 self.ns_table['alias'] = self.alias_manager.alias_table,
2276
2277
2277 #-------------------------------------------------------------------------
2278 #-------------------------------------------------------------------------
2278 # Things related to extensions and plugins
2279 # Things related to extensions and plugins
2279 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2280
2281
2281 def init_extension_manager(self):
2282 def init_extension_manager(self):
2282 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2283 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2283 self.configurables.append(self.extension_manager)
2284 self.configurables.append(self.extension_manager)
2284
2285
2285 def init_plugin_manager(self):
2286 def init_plugin_manager(self):
2286 self.plugin_manager = PluginManager(config=self.config)
2287 self.plugin_manager = PluginManager(config=self.config)
2287 self.configurables.append(self.plugin_manager)
2288 self.configurables.append(self.plugin_manager)
2288
2289
2289
2290
2290 #-------------------------------------------------------------------------
2291 #-------------------------------------------------------------------------
2291 # Things related to payloads
2292 # Things related to payloads
2292 #-------------------------------------------------------------------------
2293 #-------------------------------------------------------------------------
2293
2294
2294 def init_payload(self):
2295 def init_payload(self):
2295 self.payload_manager = PayloadManager(config=self.config)
2296 self.payload_manager = PayloadManager(config=self.config)
2296 self.configurables.append(self.payload_manager)
2297 self.configurables.append(self.payload_manager)
2297
2298
2298 #-------------------------------------------------------------------------
2299 #-------------------------------------------------------------------------
2299 # Things related to the prefilter
2300 # Things related to the prefilter
2300 #-------------------------------------------------------------------------
2301 #-------------------------------------------------------------------------
2301
2302
2302 def init_prefilter(self):
2303 def init_prefilter(self):
2303 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2304 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2304 self.configurables.append(self.prefilter_manager)
2305 self.configurables.append(self.prefilter_manager)
2305 # Ultimately this will be refactored in the new interpreter code, but
2306 # Ultimately this will be refactored in the new interpreter code, but
2306 # for now, we should expose the main prefilter method (there's legacy
2307 # for now, we should expose the main prefilter method (there's legacy
2307 # code out there that may rely on this).
2308 # code out there that may rely on this).
2308 self.prefilter = self.prefilter_manager.prefilter_lines
2309 self.prefilter = self.prefilter_manager.prefilter_lines
2309
2310
2310 def auto_rewrite_input(self, cmd):
2311 def auto_rewrite_input(self, cmd):
2311 """Print to the screen the rewritten form of the user's command.
2312 """Print to the screen the rewritten form of the user's command.
2312
2313
2313 This shows visual feedback by rewriting input lines that cause
2314 This shows visual feedback by rewriting input lines that cause
2314 automatic calling to kick in, like::
2315 automatic calling to kick in, like::
2315
2316
2316 /f x
2317 /f x
2317
2318
2318 into::
2319 into::
2319
2320
2320 ------> f(x)
2321 ------> f(x)
2321
2322
2322 after the user's input prompt. This helps the user understand that the
2323 after the user's input prompt. This helps the user understand that the
2323 input line was transformed automatically by IPython.
2324 input line was transformed automatically by IPython.
2324 """
2325 """
2325 if not self.show_rewritten_input:
2326 if not self.show_rewritten_input:
2326 return
2327 return
2327
2328
2328 rw = self.prompt_manager.render('rewrite') + cmd
2329 rw = self.prompt_manager.render('rewrite') + cmd
2329
2330
2330 try:
2331 try:
2331 # plain ascii works better w/ pyreadline, on some machines, so
2332 # plain ascii works better w/ pyreadline, on some machines, so
2332 # we use it and only print uncolored rewrite if we have unicode
2333 # we use it and only print uncolored rewrite if we have unicode
2333 rw = str(rw)
2334 rw = str(rw)
2334 print >> io.stdout, rw
2335 print(rw, file=io.stdout)
2335 except UnicodeEncodeError:
2336 except UnicodeEncodeError:
2336 print "------> " + cmd
2337 print("------> " + cmd)
2337
2338
2338 #-------------------------------------------------------------------------
2339 #-------------------------------------------------------------------------
2339 # Things related to extracting values/expressions from kernel and user_ns
2340 # Things related to extracting values/expressions from kernel and user_ns
2340 #-------------------------------------------------------------------------
2341 #-------------------------------------------------------------------------
2341
2342
2342 def _simple_error(self):
2343 def _simple_error(self):
2343 etype, value = sys.exc_info()[:2]
2344 etype, value = sys.exc_info()[:2]
2344 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2345 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2345
2346
2346 def user_variables(self, names):
2347 def user_variables(self, names):
2347 """Get a list of variable names from the user's namespace.
2348 """Get a list of variable names from the user's namespace.
2348
2349
2349 Parameters
2350 Parameters
2350 ----------
2351 ----------
2351 names : list of strings
2352 names : list of strings
2352 A list of names of variables to be read from the user namespace.
2353 A list of names of variables to be read from the user namespace.
2353
2354
2354 Returns
2355 Returns
2355 -------
2356 -------
2356 A dict, keyed by the input names and with the repr() of each value.
2357 A dict, keyed by the input names and with the repr() of each value.
2357 """
2358 """
2358 out = {}
2359 out = {}
2359 user_ns = self.user_ns
2360 user_ns = self.user_ns
2360 for varname in names:
2361 for varname in names:
2361 try:
2362 try:
2362 value = repr(user_ns[varname])
2363 value = repr(user_ns[varname])
2363 except:
2364 except:
2364 value = self._simple_error()
2365 value = self._simple_error()
2365 out[varname] = value
2366 out[varname] = value
2366 return out
2367 return out
2367
2368
2368 def user_expressions(self, expressions):
2369 def user_expressions(self, expressions):
2369 """Evaluate a dict of expressions in the user's namespace.
2370 """Evaluate a dict of expressions in the user's namespace.
2370
2371
2371 Parameters
2372 Parameters
2372 ----------
2373 ----------
2373 expressions : dict
2374 expressions : dict
2374 A dict with string keys and string values. The expression values
2375 A dict with string keys and string values. The expression values
2375 should be valid Python expressions, each of which will be evaluated
2376 should be valid Python expressions, each of which will be evaluated
2376 in the user namespace.
2377 in the user namespace.
2377
2378
2378 Returns
2379 Returns
2379 -------
2380 -------
2380 A dict, keyed like the input expressions dict, with the repr() of each
2381 A dict, keyed like the input expressions dict, with the repr() of each
2381 value.
2382 value.
2382 """
2383 """
2383 out = {}
2384 out = {}
2384 user_ns = self.user_ns
2385 user_ns = self.user_ns
2385 global_ns = self.user_global_ns
2386 global_ns = self.user_global_ns
2386 for key, expr in expressions.iteritems():
2387 for key, expr in expressions.iteritems():
2387 try:
2388 try:
2388 value = repr(eval(expr, global_ns, user_ns))
2389 value = repr(eval(expr, global_ns, user_ns))
2389 except:
2390 except:
2390 value = self._simple_error()
2391 value = self._simple_error()
2391 out[key] = value
2392 out[key] = value
2392 return out
2393 return out
2393
2394
2394 #-------------------------------------------------------------------------
2395 #-------------------------------------------------------------------------
2395 # Things related to the running of code
2396 # Things related to the running of code
2396 #-------------------------------------------------------------------------
2397 #-------------------------------------------------------------------------
2397
2398
2398 def ex(self, cmd):
2399 def ex(self, cmd):
2399 """Execute a normal python statement in user namespace."""
2400 """Execute a normal python statement in user namespace."""
2400 with self.builtin_trap:
2401 with self.builtin_trap:
2401 exec cmd in self.user_global_ns, self.user_ns
2402 exec cmd in self.user_global_ns, self.user_ns
2402
2403
2403 def ev(self, expr):
2404 def ev(self, expr):
2404 """Evaluate python expression expr in user namespace.
2405 """Evaluate python expression expr in user namespace.
2405
2406
2406 Returns the result of evaluation
2407 Returns the result of evaluation
2407 """
2408 """
2408 with self.builtin_trap:
2409 with self.builtin_trap:
2409 return eval(expr, self.user_global_ns, self.user_ns)
2410 return eval(expr, self.user_global_ns, self.user_ns)
2410
2411
2411 def safe_execfile(self, fname, *where, **kw):
2412 def safe_execfile(self, fname, *where, **kw):
2412 """A safe version of the builtin execfile().
2413 """A safe version of the builtin execfile().
2413
2414
2414 This version will never throw an exception, but instead print
2415 This version will never throw an exception, but instead print
2415 helpful error messages to the screen. This only works on pure
2416 helpful error messages to the screen. This only works on pure
2416 Python files with the .py extension.
2417 Python files with the .py extension.
2417
2418
2418 Parameters
2419 Parameters
2419 ----------
2420 ----------
2420 fname : string
2421 fname : string
2421 The name of the file to be executed.
2422 The name of the file to be executed.
2422 where : tuple
2423 where : tuple
2423 One or two namespaces, passed to execfile() as (globals,locals).
2424 One or two namespaces, passed to execfile() as (globals,locals).
2424 If only one is given, it is passed as both.
2425 If only one is given, it is passed as both.
2425 exit_ignore : bool (False)
2426 exit_ignore : bool (False)
2426 If True, then silence SystemExit for non-zero status (it is always
2427 If True, then silence SystemExit for non-zero status (it is always
2427 silenced for zero status, as it is so common).
2428 silenced for zero status, as it is so common).
2428 raise_exceptions : bool (False)
2429 raise_exceptions : bool (False)
2429 If True raise exceptions everywhere. Meant for testing.
2430 If True raise exceptions everywhere. Meant for testing.
2430
2431
2431 """
2432 """
2432 kw.setdefault('exit_ignore', False)
2433 kw.setdefault('exit_ignore', False)
2433 kw.setdefault('raise_exceptions', False)
2434 kw.setdefault('raise_exceptions', False)
2434
2435
2435 fname = os.path.abspath(os.path.expanduser(fname))
2436 fname = os.path.abspath(os.path.expanduser(fname))
2436
2437
2437 # Make sure we can open the file
2438 # Make sure we can open the file
2438 try:
2439 try:
2439 with open(fname) as thefile:
2440 with open(fname) as thefile:
2440 pass
2441 pass
2441 except:
2442 except:
2442 warn('Could not open file <%s> for safe execution.' % fname)
2443 warn('Could not open file <%s> for safe execution.' % fname)
2443 return
2444 return
2444
2445
2445 # Find things also in current directory. This is needed to mimic the
2446 # Find things also in current directory. This is needed to mimic the
2446 # behavior of running a script from the system command line, where
2447 # behavior of running a script from the system command line, where
2447 # Python inserts the script's directory into sys.path
2448 # Python inserts the script's directory into sys.path
2448 dname = os.path.dirname(fname)
2449 dname = os.path.dirname(fname)
2449
2450
2450 with prepended_to_syspath(dname):
2451 with prepended_to_syspath(dname):
2451 try:
2452 try:
2452 py3compat.execfile(fname,*where)
2453 py3compat.execfile(fname,*where)
2453 except SystemExit as status:
2454 except SystemExit as status:
2454 # If the call was made with 0 or None exit status (sys.exit(0)
2455 # If the call was made with 0 or None exit status (sys.exit(0)
2455 # or sys.exit() ), don't bother showing a traceback, as both of
2456 # or sys.exit() ), don't bother showing a traceback, as both of
2456 # these are considered normal by the OS:
2457 # these are considered normal by the OS:
2457 # > python -c'import sys;sys.exit(0)'; echo $?
2458 # > python -c'import sys;sys.exit(0)'; echo $?
2458 # 0
2459 # 0
2459 # > python -c'import sys;sys.exit()'; echo $?
2460 # > python -c'import sys;sys.exit()'; echo $?
2460 # 0
2461 # 0
2461 # For other exit status, we show the exception unless
2462 # For other exit status, we show the exception unless
2462 # explicitly silenced, but only in short form.
2463 # explicitly silenced, but only in short form.
2463 if kw['raise_exceptions']:
2464 if kw['raise_exceptions']:
2464 raise
2465 raise
2465 if status.code not in (0, None) and not kw['exit_ignore']:
2466 if status.code not in (0, None) and not kw['exit_ignore']:
2466 self.showtraceback(exception_only=True)
2467 self.showtraceback(exception_only=True)
2467 except:
2468 except:
2468 if kw['raise_exceptions']:
2469 if kw['raise_exceptions']:
2469 raise
2470 raise
2470 self.showtraceback()
2471 self.showtraceback()
2471
2472
2472 def safe_execfile_ipy(self, fname):
2473 def safe_execfile_ipy(self, fname):
2473 """Like safe_execfile, but for .ipy files with IPython syntax.
2474 """Like safe_execfile, but for .ipy files with IPython syntax.
2474
2475
2475 Parameters
2476 Parameters
2476 ----------
2477 ----------
2477 fname : str
2478 fname : str
2478 The name of the file to execute. The filename must have a
2479 The name of the file to execute. The filename must have a
2479 .ipy extension.
2480 .ipy extension.
2480 """
2481 """
2481 fname = os.path.abspath(os.path.expanduser(fname))
2482 fname = os.path.abspath(os.path.expanduser(fname))
2482
2483
2483 # Make sure we can open the file
2484 # Make sure we can open the file
2484 try:
2485 try:
2485 with open(fname) as thefile:
2486 with open(fname) as thefile:
2486 pass
2487 pass
2487 except:
2488 except:
2488 warn('Could not open file <%s> for safe execution.' % fname)
2489 warn('Could not open file <%s> for safe execution.' % fname)
2489 return
2490 return
2490
2491
2491 # Find things also in current directory. This is needed to mimic the
2492 # Find things also in current directory. This is needed to mimic the
2492 # behavior of running a script from the system command line, where
2493 # behavior of running a script from the system command line, where
2493 # Python inserts the script's directory into sys.path
2494 # Python inserts the script's directory into sys.path
2494 dname = os.path.dirname(fname)
2495 dname = os.path.dirname(fname)
2495
2496
2496 with prepended_to_syspath(dname):
2497 with prepended_to_syspath(dname):
2497 try:
2498 try:
2498 with open(fname) as thefile:
2499 with open(fname) as thefile:
2499 # self.run_cell currently captures all exceptions
2500 # self.run_cell currently captures all exceptions
2500 # raised in user code. It would be nice if there were
2501 # raised in user code. It would be nice if there were
2501 # versions of runlines, execfile that did raise, so
2502 # versions of runlines, execfile that did raise, so
2502 # we could catch the errors.
2503 # we could catch the errors.
2503 self.run_cell(thefile.read(), store_history=False)
2504 self.run_cell(thefile.read(), store_history=False)
2504 except:
2505 except:
2505 self.showtraceback()
2506 self.showtraceback()
2506 warn('Unknown failure executing file: <%s>' % fname)
2507 warn('Unknown failure executing file: <%s>' % fname)
2507
2508
2508 def safe_run_module(self, mod_name, where):
2509 def safe_run_module(self, mod_name, where):
2509 """A safe version of runpy.run_module().
2510 """A safe version of runpy.run_module().
2510
2511
2511 This version will never throw an exception, but instead print
2512 This version will never throw an exception, but instead print
2512 helpful error messages to the screen.
2513 helpful error messages to the screen.
2513
2514
2514 Parameters
2515 Parameters
2515 ----------
2516 ----------
2516 mod_name : string
2517 mod_name : string
2517 The name of the module to be executed.
2518 The name of the module to be executed.
2518 where : dict
2519 where : dict
2519 The globals namespace.
2520 The globals namespace.
2520 """
2521 """
2521 try:
2522 try:
2522 where.update(
2523 where.update(
2523 runpy.run_module(str(mod_name), run_name="__main__",
2524 runpy.run_module(str(mod_name), run_name="__main__",
2524 alter_sys=True)
2525 alter_sys=True)
2525 )
2526 )
2526 except:
2527 except:
2527 self.showtraceback()
2528 self.showtraceback()
2528 warn('Unknown failure executing module: <%s>' % mod_name)
2529 warn('Unknown failure executing module: <%s>' % mod_name)
2529
2530
2530 def _run_cached_cell_magic(self, magic_name, line):
2531 def _run_cached_cell_magic(self, magic_name, line):
2531 """Special method to call a cell magic with the data stored in self.
2532 """Special method to call a cell magic with the data stored in self.
2532 """
2533 """
2533 cell = self._current_cell_magic_body
2534 cell = self._current_cell_magic_body
2534 self._current_cell_magic_body = None
2535 self._current_cell_magic_body = None
2535 return self.run_cell_magic(magic_name, line, cell)
2536 return self.run_cell_magic(magic_name, line, cell)
2536
2537
2537 def run_cell(self, raw_cell, store_history=False, silent=False):
2538 def run_cell(self, raw_cell, store_history=False, silent=False):
2538 """Run a complete IPython cell.
2539 """Run a complete IPython cell.
2539
2540
2540 Parameters
2541 Parameters
2541 ----------
2542 ----------
2542 raw_cell : str
2543 raw_cell : str
2543 The code (including IPython code such as %magic functions) to run.
2544 The code (including IPython code such as %magic functions) to run.
2544 store_history : bool
2545 store_history : bool
2545 If True, the raw and translated cell will be stored in IPython's
2546 If True, the raw and translated cell will be stored in IPython's
2546 history. For user code calling back into IPython's machinery, this
2547 history. For user code calling back into IPython's machinery, this
2547 should be set to False.
2548 should be set to False.
2548 silent : bool
2549 silent : bool
2549 If True, avoid side-effets, such as implicit displayhooks, history,
2550 If True, avoid side-effets, such as implicit displayhooks, history,
2550 and logging. silent=True forces store_history=False.
2551 and logging. silent=True forces store_history=False.
2551 """
2552 """
2552 if (not raw_cell) or raw_cell.isspace():
2553 if (not raw_cell) or raw_cell.isspace():
2553 return
2554 return
2554
2555
2555 if silent:
2556 if silent:
2556 store_history = False
2557 store_history = False
2557
2558
2558 self.input_splitter.push(raw_cell)
2559 self.input_splitter.push(raw_cell)
2559
2560
2560 # Check for cell magics, which leave state behind. This interface is
2561 # Check for cell magics, which leave state behind. This interface is
2561 # ugly, we need to do something cleaner later... Now the logic is
2562 # ugly, we need to do something cleaner later... Now the logic is
2562 # simply that the input_splitter remembers if there was a cell magic,
2563 # simply that the input_splitter remembers if there was a cell magic,
2563 # and in that case we grab the cell body.
2564 # and in that case we grab the cell body.
2564 if self.input_splitter.cell_magic_parts:
2565 if self.input_splitter.cell_magic_parts:
2565 self._current_cell_magic_body = \
2566 self._current_cell_magic_body = \
2566 ''.join(self.input_splitter.cell_magic_parts)
2567 ''.join(self.input_splitter.cell_magic_parts)
2567 cell = self.input_splitter.source_reset()
2568 cell = self.input_splitter.source_reset()
2568
2569
2569 with self.builtin_trap:
2570 with self.builtin_trap:
2570 prefilter_failed = False
2571 prefilter_failed = False
2571 if len(cell.splitlines()) == 1:
2572 if len(cell.splitlines()) == 1:
2572 try:
2573 try:
2573 # use prefilter_lines to handle trailing newlines
2574 # use prefilter_lines to handle trailing newlines
2574 # restore trailing newline for ast.parse
2575 # restore trailing newline for ast.parse
2575 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2576 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2576 except AliasError as e:
2577 except AliasError as e:
2577 error(e)
2578 error(e)
2578 prefilter_failed = True
2579 prefilter_failed = True
2579 except Exception:
2580 except Exception:
2580 # don't allow prefilter errors to crash IPython
2581 # don't allow prefilter errors to crash IPython
2581 self.showtraceback()
2582 self.showtraceback()
2582 prefilter_failed = True
2583 prefilter_failed = True
2583
2584
2584 # Store raw and processed history
2585 # Store raw and processed history
2585 if store_history:
2586 if store_history:
2586 self.history_manager.store_inputs(self.execution_count,
2587 self.history_manager.store_inputs(self.execution_count,
2587 cell, raw_cell)
2588 cell, raw_cell)
2588 if not silent:
2589 if not silent:
2589 self.logger.log(cell, raw_cell)
2590 self.logger.log(cell, raw_cell)
2590
2591
2591 if not prefilter_failed:
2592 if not prefilter_failed:
2592 # don't run if prefilter failed
2593 # don't run if prefilter failed
2593 cell_name = self.compile.cache(cell, self.execution_count)
2594 cell_name = self.compile.cache(cell, self.execution_count)
2594
2595
2595 with self.display_trap:
2596 with self.display_trap:
2596 try:
2597 try:
2597 code_ast = self.compile.ast_parse(cell,
2598 code_ast = self.compile.ast_parse(cell,
2598 filename=cell_name)
2599 filename=cell_name)
2599 except IndentationError:
2600 except IndentationError:
2600 self.showindentationerror()
2601 self.showindentationerror()
2601 if store_history:
2602 if store_history:
2602 self.execution_count += 1
2603 self.execution_count += 1
2603 return None
2604 return None
2604 except (OverflowError, SyntaxError, ValueError, TypeError,
2605 except (OverflowError, SyntaxError, ValueError, TypeError,
2605 MemoryError):
2606 MemoryError):
2606 self.showsyntaxerror()
2607 self.showsyntaxerror()
2607 if store_history:
2608 if store_history:
2608 self.execution_count += 1
2609 self.execution_count += 1
2609 return None
2610 return None
2610
2611
2611 interactivity = "none" if silent else self.ast_node_interactivity
2612 interactivity = "none" if silent else self.ast_node_interactivity
2612 self.run_ast_nodes(code_ast.body, cell_name,
2613 self.run_ast_nodes(code_ast.body, cell_name,
2613 interactivity=interactivity)
2614 interactivity=interactivity)
2614
2615
2615 # Execute any registered post-execution functions.
2616 # Execute any registered post-execution functions.
2616 # unless we are silent
2617 # unless we are silent
2617 post_exec = [] if silent else self._post_execute.iteritems()
2618 post_exec = [] if silent else self._post_execute.iteritems()
2618
2619
2619 for func, status in post_exec:
2620 for func, status in post_exec:
2620 if self.disable_failing_post_execute and not status:
2621 if self.disable_failing_post_execute and not status:
2621 continue
2622 continue
2622 try:
2623 try:
2623 func()
2624 func()
2624 except KeyboardInterrupt:
2625 except KeyboardInterrupt:
2625 print >> io.stderr, "\nKeyboardInterrupt"
2626 print("\nKeyboardInterrupt", file=io.stderr)
2626 except Exception:
2627 except Exception:
2627 # register as failing:
2628 # register as failing:
2628 self._post_execute[func] = False
2629 self._post_execute[func] = False
2629 self.showtraceback()
2630 self.showtraceback()
2630 print >> io.stderr, '\n'.join([
2631 print('\n'.join([
2631 "post-execution function %r produced an error." % func,
2632 "post-execution function %r produced an error." % func,
2632 "If this problem persists, you can disable failing post-exec functions with:",
2633 "If this problem persists, you can disable failing post-exec functions with:",
2633 "",
2634 "",
2634 " get_ipython().disable_failing_post_execute = True"
2635 " get_ipython().disable_failing_post_execute = True"
2635 ])
2636 ]), file=io.stderr)
2636
2637
2637 if store_history:
2638 if store_history:
2638 # Write output to the database. Does nothing unless
2639 # Write output to the database. Does nothing unless
2639 # history output logging is enabled.
2640 # history output logging is enabled.
2640 self.history_manager.store_output(self.execution_count)
2641 self.history_manager.store_output(self.execution_count)
2641 # Each cell is a *single* input, regardless of how many lines it has
2642 # Each cell is a *single* input, regardless of how many lines it has
2642 self.execution_count += 1
2643 self.execution_count += 1
2643
2644
2644 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2645 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2645 """Run a sequence of AST nodes. The execution mode depends on the
2646 """Run a sequence of AST nodes. The execution mode depends on the
2646 interactivity parameter.
2647 interactivity parameter.
2647
2648
2648 Parameters
2649 Parameters
2649 ----------
2650 ----------
2650 nodelist : list
2651 nodelist : list
2651 A sequence of AST nodes to run.
2652 A sequence of AST nodes to run.
2652 cell_name : str
2653 cell_name : str
2653 Will be passed to the compiler as the filename of the cell. Typically
2654 Will be passed to the compiler as the filename of the cell. Typically
2654 the value returned by ip.compile.cache(cell).
2655 the value returned by ip.compile.cache(cell).
2655 interactivity : str
2656 interactivity : str
2656 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2657 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2657 run interactively (displaying output from expressions). 'last_expr'
2658 run interactively (displaying output from expressions). 'last_expr'
2658 will run the last node interactively only if it is an expression (i.e.
2659 will run the last node interactively only if it is an expression (i.e.
2659 expressions in loops or other blocks are not displayed. Other values
2660 expressions in loops or other blocks are not displayed. Other values
2660 for this parameter will raise a ValueError.
2661 for this parameter will raise a ValueError.
2661 """
2662 """
2662 if not nodelist:
2663 if not nodelist:
2663 return
2664 return
2664
2665
2665 if interactivity == 'last_expr':
2666 if interactivity == 'last_expr':
2666 if isinstance(nodelist[-1], ast.Expr):
2667 if isinstance(nodelist[-1], ast.Expr):
2667 interactivity = "last"
2668 interactivity = "last"
2668 else:
2669 else:
2669 interactivity = "none"
2670 interactivity = "none"
2670
2671
2671 if interactivity == 'none':
2672 if interactivity == 'none':
2672 to_run_exec, to_run_interactive = nodelist, []
2673 to_run_exec, to_run_interactive = nodelist, []
2673 elif interactivity == 'last':
2674 elif interactivity == 'last':
2674 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2675 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2675 elif interactivity == 'all':
2676 elif interactivity == 'all':
2676 to_run_exec, to_run_interactive = [], nodelist
2677 to_run_exec, to_run_interactive = [], nodelist
2677 else:
2678 else:
2678 raise ValueError("Interactivity was %r" % interactivity)
2679 raise ValueError("Interactivity was %r" % interactivity)
2679
2680
2680 exec_count = self.execution_count
2681 exec_count = self.execution_count
2681
2682
2682 try:
2683 try:
2683 for i, node in enumerate(to_run_exec):
2684 for i, node in enumerate(to_run_exec):
2684 mod = ast.Module([node])
2685 mod = ast.Module([node])
2685 code = self.compile(mod, cell_name, "exec")
2686 code = self.compile(mod, cell_name, "exec")
2686 if self.run_code(code):
2687 if self.run_code(code):
2687 return True
2688 return True
2688
2689
2689 for i, node in enumerate(to_run_interactive):
2690 for i, node in enumerate(to_run_interactive):
2690 mod = ast.Interactive([node])
2691 mod = ast.Interactive([node])
2691 code = self.compile(mod, cell_name, "single")
2692 code = self.compile(mod, cell_name, "single")
2692 if self.run_code(code):
2693 if self.run_code(code):
2693 return True
2694 return True
2694
2695
2695 # Flush softspace
2696 # Flush softspace
2696 if softspace(sys.stdout, 0):
2697 if softspace(sys.stdout, 0):
2697 print
2698 print()
2698
2699
2699 except:
2700 except:
2700 # It's possible to have exceptions raised here, typically by
2701 # It's possible to have exceptions raised here, typically by
2701 # compilation of odd code (such as a naked 'return' outside a
2702 # compilation of odd code (such as a naked 'return' outside a
2702 # function) that did parse but isn't valid. Typically the exception
2703 # function) that did parse but isn't valid. Typically the exception
2703 # is a SyntaxError, but it's safest just to catch anything and show
2704 # is a SyntaxError, but it's safest just to catch anything and show
2704 # the user a traceback.
2705 # the user a traceback.
2705
2706
2706 # We do only one try/except outside the loop to minimize the impact
2707 # We do only one try/except outside the loop to minimize the impact
2707 # on runtime, and also because if any node in the node list is
2708 # on runtime, and also because if any node in the node list is
2708 # broken, we should stop execution completely.
2709 # broken, we should stop execution completely.
2709 self.showtraceback()
2710 self.showtraceback()
2710
2711
2711 return False
2712 return False
2712
2713
2713 def run_code(self, code_obj):
2714 def run_code(self, code_obj):
2714 """Execute a code object.
2715 """Execute a code object.
2715
2716
2716 When an exception occurs, self.showtraceback() is called to display a
2717 When an exception occurs, self.showtraceback() is called to display a
2717 traceback.
2718 traceback.
2718
2719
2719 Parameters
2720 Parameters
2720 ----------
2721 ----------
2721 code_obj : code object
2722 code_obj : code object
2722 A compiled code object, to be executed
2723 A compiled code object, to be executed
2723
2724
2724 Returns
2725 Returns
2725 -------
2726 -------
2726 False : successful execution.
2727 False : successful execution.
2727 True : an error occurred.
2728 True : an error occurred.
2728 """
2729 """
2729
2730
2730 # Set our own excepthook in case the user code tries to call it
2731 # Set our own excepthook in case the user code tries to call it
2731 # directly, so that the IPython crash handler doesn't get triggered
2732 # directly, so that the IPython crash handler doesn't get triggered
2732 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2733 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2733
2734
2734 # we save the original sys.excepthook in the instance, in case config
2735 # we save the original sys.excepthook in the instance, in case config
2735 # code (such as magics) needs access to it.
2736 # code (such as magics) needs access to it.
2736 self.sys_excepthook = old_excepthook
2737 self.sys_excepthook = old_excepthook
2737 outflag = 1 # happens in more places, so it's easier as default
2738 outflag = 1 # happens in more places, so it's easier as default
2738 try:
2739 try:
2739 try:
2740 try:
2740 self.hooks.pre_run_code_hook()
2741 self.hooks.pre_run_code_hook()
2741 #rprint('Running code', repr(code_obj)) # dbg
2742 #rprint('Running code', repr(code_obj)) # dbg
2742 exec code_obj in self.user_global_ns, self.user_ns
2743 exec code_obj in self.user_global_ns, self.user_ns
2743 finally:
2744 finally:
2744 # Reset our crash handler in place
2745 # Reset our crash handler in place
2745 sys.excepthook = old_excepthook
2746 sys.excepthook = old_excepthook
2746 except SystemExit:
2747 except SystemExit:
2747 self.showtraceback(exception_only=True)
2748 self.showtraceback(exception_only=True)
2748 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2749 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2749 except self.custom_exceptions:
2750 except self.custom_exceptions:
2750 etype,value,tb = sys.exc_info()
2751 etype,value,tb = sys.exc_info()
2751 self.CustomTB(etype,value,tb)
2752 self.CustomTB(etype,value,tb)
2752 except:
2753 except:
2753 self.showtraceback()
2754 self.showtraceback()
2754 else:
2755 else:
2755 outflag = 0
2756 outflag = 0
2756 return outflag
2757 return outflag
2757
2758
2758 # For backwards compatibility
2759 # For backwards compatibility
2759 runcode = run_code
2760 runcode = run_code
2760
2761
2761 #-------------------------------------------------------------------------
2762 #-------------------------------------------------------------------------
2762 # Things related to GUI support and pylab
2763 # Things related to GUI support and pylab
2763 #-------------------------------------------------------------------------
2764 #-------------------------------------------------------------------------
2764
2765
2765 def enable_gui(self, gui=None):
2766 def enable_gui(self, gui=None):
2766 raise NotImplementedError('Implement enable_gui in a subclass')
2767 raise NotImplementedError('Implement enable_gui in a subclass')
2767
2768
2768 def enable_pylab(self, gui=None, import_all=True):
2769 def enable_pylab(self, gui=None, import_all=True):
2769 """Activate pylab support at runtime.
2770 """Activate pylab support at runtime.
2770
2771
2771 This turns on support for matplotlib, preloads into the interactive
2772 This turns on support for matplotlib, preloads into the interactive
2772 namespace all of numpy and pylab, and configures IPython to correctly
2773 namespace all of numpy and pylab, and configures IPython to correctly
2773 interact with the GUI event loop. The GUI backend to be used can be
2774 interact with the GUI event loop. The GUI backend to be used can be
2774 optionally selected with the optional :param:`gui` argument.
2775 optionally selected with the optional :param:`gui` argument.
2775
2776
2776 Parameters
2777 Parameters
2777 ----------
2778 ----------
2778 gui : optional, string
2779 gui : optional, string
2779
2780
2780 If given, dictates the choice of matplotlib GUI backend to use
2781 If given, dictates the choice of matplotlib GUI backend to use
2781 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2782 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2782 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2783 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2783 matplotlib (as dictated by the matplotlib build-time options plus the
2784 matplotlib (as dictated by the matplotlib build-time options plus the
2784 user's matplotlibrc configuration file). Note that not all backends
2785 user's matplotlibrc configuration file). Note that not all backends
2785 make sense in all contexts, for example a terminal ipython can't
2786 make sense in all contexts, for example a terminal ipython can't
2786 display figures inline.
2787 display figures inline.
2787 """
2788 """
2788 from IPython.core.pylabtools import mpl_runner
2789 from IPython.core.pylabtools import mpl_runner
2789 # We want to prevent the loading of pylab to pollute the user's
2790 # We want to prevent the loading of pylab to pollute the user's
2790 # namespace as shown by the %who* magics, so we execute the activation
2791 # namespace as shown by the %who* magics, so we execute the activation
2791 # code in an empty namespace, and we update *both* user_ns and
2792 # code in an empty namespace, and we update *both* user_ns and
2792 # user_ns_hidden with this information.
2793 # user_ns_hidden with this information.
2793 ns = {}
2794 ns = {}
2794 try:
2795 try:
2795 gui = pylab_activate(ns, gui, import_all, self)
2796 gui = pylab_activate(ns, gui, import_all, self)
2796 except KeyError:
2797 except KeyError:
2797 error("Backend %r not supported" % gui)
2798 error("Backend %r not supported" % gui)
2798 return
2799 return
2799 self.user_ns.update(ns)
2800 self.user_ns.update(ns)
2800 self.user_ns_hidden.update(ns)
2801 self.user_ns_hidden.update(ns)
2801 # Now we must activate the gui pylab wants to use, and fix %run to take
2802 # Now we must activate the gui pylab wants to use, and fix %run to take
2802 # plot updates into account
2803 # plot updates into account
2803 self.enable_gui(gui)
2804 self.enable_gui(gui)
2804 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2805 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2805 mpl_runner(self.safe_execfile)
2806 mpl_runner(self.safe_execfile)
2806
2807
2807 #-------------------------------------------------------------------------
2808 #-------------------------------------------------------------------------
2808 # Utilities
2809 # Utilities
2809 #-------------------------------------------------------------------------
2810 #-------------------------------------------------------------------------
2810
2811
2811 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2812 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2812 """Expand python variables in a string.
2813 """Expand python variables in a string.
2813
2814
2814 The depth argument indicates how many frames above the caller should
2815 The depth argument indicates how many frames above the caller should
2815 be walked to look for the local namespace where to expand variables.
2816 be walked to look for the local namespace where to expand variables.
2816
2817
2817 The global namespace for expansion is always the user's interactive
2818 The global namespace for expansion is always the user's interactive
2818 namespace.
2819 namespace.
2819 """
2820 """
2820 ns = self.user_ns.copy()
2821 ns = self.user_ns.copy()
2821 ns.update(sys._getframe(depth+1).f_locals)
2822 ns.update(sys._getframe(depth+1).f_locals)
2822 ns.pop('self', None)
2823 ns.pop('self', None)
2823 try:
2824 try:
2824 cmd = formatter.format(cmd, **ns)
2825 cmd = formatter.format(cmd, **ns)
2825 except Exception:
2826 except Exception:
2826 # if formatter couldn't format, just let it go untransformed
2827 # if formatter couldn't format, just let it go untransformed
2827 pass
2828 pass
2828 return cmd
2829 return cmd
2829
2830
2830 def mktempfile(self, data=None, prefix='ipython_edit_'):
2831 def mktempfile(self, data=None, prefix='ipython_edit_'):
2831 """Make a new tempfile and return its filename.
2832 """Make a new tempfile and return its filename.
2832
2833
2833 This makes a call to tempfile.mktemp, but it registers the created
2834 This makes a call to tempfile.mktemp, but it registers the created
2834 filename internally so ipython cleans it up at exit time.
2835 filename internally so ipython cleans it up at exit time.
2835
2836
2836 Optional inputs:
2837 Optional inputs:
2837
2838
2838 - data(None): if data is given, it gets written out to the temp file
2839 - data(None): if data is given, it gets written out to the temp file
2839 immediately, and the file is closed again."""
2840 immediately, and the file is closed again."""
2840
2841
2841 filename = tempfile.mktemp('.py', prefix)
2842 filename = tempfile.mktemp('.py', prefix)
2842 self.tempfiles.append(filename)
2843 self.tempfiles.append(filename)
2843
2844
2844 if data:
2845 if data:
2845 tmp_file = open(filename,'w')
2846 tmp_file = open(filename,'w')
2846 tmp_file.write(data)
2847 tmp_file.write(data)
2847 tmp_file.close()
2848 tmp_file.close()
2848 return filename
2849 return filename
2849
2850
2850 # TODO: This should be removed when Term is refactored.
2851 # TODO: This should be removed when Term is refactored.
2851 def write(self,data):
2852 def write(self,data):
2852 """Write a string to the default output"""
2853 """Write a string to the default output"""
2853 io.stdout.write(data)
2854 io.stdout.write(data)
2854
2855
2855 # TODO: This should be removed when Term is refactored.
2856 # TODO: This should be removed when Term is refactored.
2856 def write_err(self,data):
2857 def write_err(self,data):
2857 """Write a string to the default error output"""
2858 """Write a string to the default error output"""
2858 io.stderr.write(data)
2859 io.stderr.write(data)
2859
2860
2860 def ask_yes_no(self, prompt, default=None):
2861 def ask_yes_no(self, prompt, default=None):
2861 if self.quiet:
2862 if self.quiet:
2862 return True
2863 return True
2863 return ask_yes_no(prompt,default)
2864 return ask_yes_no(prompt,default)
2864
2865
2865 def show_usage(self):
2866 def show_usage(self):
2866 """Show a usage message"""
2867 """Show a usage message"""
2867 page.page(IPython.core.usage.interactive_usage)
2868 page.page(IPython.core.usage.interactive_usage)
2868
2869
2869 def extract_input_lines(self, range_str, raw=False):
2870 def extract_input_lines(self, range_str, raw=False):
2870 """Return as a string a set of input history slices.
2871 """Return as a string a set of input history slices.
2871
2872
2872 Parameters
2873 Parameters
2873 ----------
2874 ----------
2874 range_str : string
2875 range_str : string
2875 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2876 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2876 since this function is for use by magic functions which get their
2877 since this function is for use by magic functions which get their
2877 arguments as strings. The number before the / is the session
2878 arguments as strings. The number before the / is the session
2878 number: ~n goes n back from the current session.
2879 number: ~n goes n back from the current session.
2879
2880
2880 Optional Parameters:
2881 Optional Parameters:
2881 - raw(False): by default, the processed input is used. If this is
2882 - raw(False): by default, the processed input is used. If this is
2882 true, the raw input history is used instead.
2883 true, the raw input history is used instead.
2883
2884
2884 Note that slices can be called with two notations:
2885 Note that slices can be called with two notations:
2885
2886
2886 N:M -> standard python form, means including items N...(M-1).
2887 N:M -> standard python form, means including items N...(M-1).
2887
2888
2888 N-M -> include items N..M (closed endpoint)."""
2889 N-M -> include items N..M (closed endpoint)."""
2889 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2890 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2890 return "\n".join(x for _, _, x in lines)
2891 return "\n".join(x for _, _, x in lines)
2891
2892
2892 def find_user_code(self, target, raw=True, py_only=False):
2893 def find_user_code(self, target, raw=True, py_only=False):
2893 """Get a code string from history, file, url, or a string or macro.
2894 """Get a code string from history, file, url, or a string or macro.
2894
2895
2895 This is mainly used by magic functions.
2896 This is mainly used by magic functions.
2896
2897
2897 Parameters
2898 Parameters
2898 ----------
2899 ----------
2899
2900
2900 target : str
2901 target : str
2901
2902
2902 A string specifying code to retrieve. This will be tried respectively
2903 A string specifying code to retrieve. This will be tried respectively
2903 as: ranges of input history (see %history for syntax), url,
2904 as: ranges of input history (see %history for syntax), url,
2904 correspnding .py file, filename, or an expression evaluating to a
2905 correspnding .py file, filename, or an expression evaluating to a
2905 string or Macro in the user namespace.
2906 string or Macro in the user namespace.
2906
2907
2907 raw : bool
2908 raw : bool
2908 If true (default), retrieve raw history. Has no effect on the other
2909 If true (default), retrieve raw history. Has no effect on the other
2909 retrieval mechanisms.
2910 retrieval mechanisms.
2910
2911
2911 py_only : bool (default False)
2912 py_only : bool (default False)
2912 Only try to fetch python code, do not try alternative methods to decode file
2913 Only try to fetch python code, do not try alternative methods to decode file
2913 if unicode fails.
2914 if unicode fails.
2914
2915
2915 Returns
2916 Returns
2916 -------
2917 -------
2917 A string of code.
2918 A string of code.
2918
2919
2919 ValueError is raised if nothing is found, and TypeError if it evaluates
2920 ValueError is raised if nothing is found, and TypeError if it evaluates
2920 to an object of another type. In each case, .args[0] is a printable
2921 to an object of another type. In each case, .args[0] is a printable
2921 message.
2922 message.
2922 """
2923 """
2923 code = self.extract_input_lines(target, raw=raw) # Grab history
2924 code = self.extract_input_lines(target, raw=raw) # Grab history
2924 if code:
2925 if code:
2925 return code
2926 return code
2926 utarget = unquote_filename(target)
2927 utarget = unquote_filename(target)
2927 try:
2928 try:
2928 if utarget.startswith(('http://', 'https://')):
2929 if utarget.startswith(('http://', 'https://')):
2929 return openpy.read_py_url(utarget, skip_encoding_cookie=True)
2930 return openpy.read_py_url(utarget, skip_encoding_cookie=True)
2930 except UnicodeDecodeError:
2931 except UnicodeDecodeError:
2931 if not py_only :
2932 if not py_only :
2932 response = urllib.urlopen(target)
2933 response = urllib.urlopen(target)
2933 return response.read().decode('latin1')
2934 return response.read().decode('latin1')
2934 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2935 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2935
2936
2936 potential_target = [target]
2937 potential_target = [target]
2937 try :
2938 try :
2938 potential_target.insert(0,get_py_filename(target))
2939 potential_target.insert(0,get_py_filename(target))
2939 except IOError:
2940 except IOError:
2940 pass
2941 pass
2941
2942
2942 for tgt in potential_target :
2943 for tgt in potential_target :
2943 if os.path.isfile(tgt): # Read file
2944 if os.path.isfile(tgt): # Read file
2944 try :
2945 try :
2945 return openpy.read_py_file(tgt, skip_encoding_cookie=True)
2946 return openpy.read_py_file(tgt, skip_encoding_cookie=True)
2946 except UnicodeDecodeError :
2947 except UnicodeDecodeError :
2947 if not py_only :
2948 if not py_only :
2948 with io_open(tgt,'r', encoding='latin1') as f :
2949 with io_open(tgt,'r', encoding='latin1') as f :
2949 return f.read()
2950 return f.read()
2950 raise ValueError(("'%s' seem to be unreadable.") % target)
2951 raise ValueError(("'%s' seem to be unreadable.") % target)
2951
2952
2952 try: # User namespace
2953 try: # User namespace
2953 codeobj = eval(target, self.user_ns)
2954 codeobj = eval(target, self.user_ns)
2954 except Exception:
2955 except Exception:
2955 raise ValueError(("'%s' was not found in history, as a file, url, "
2956 raise ValueError(("'%s' was not found in history, as a file, url, "
2956 "nor in the user namespace.") % target)
2957 "nor in the user namespace.") % target)
2957 if isinstance(codeobj, basestring):
2958 if isinstance(codeobj, basestring):
2958 return codeobj
2959 return codeobj
2959 elif isinstance(codeobj, Macro):
2960 elif isinstance(codeobj, Macro):
2960 return codeobj.value
2961 return codeobj.value
2961
2962
2962 raise TypeError("%s is neither a string nor a macro." % target,
2963 raise TypeError("%s is neither a string nor a macro." % target,
2963 codeobj)
2964 codeobj)
2964
2965
2965 #-------------------------------------------------------------------------
2966 #-------------------------------------------------------------------------
2966 # Things related to IPython exiting
2967 # Things related to IPython exiting
2967 #-------------------------------------------------------------------------
2968 #-------------------------------------------------------------------------
2968 def atexit_operations(self):
2969 def atexit_operations(self):
2969 """This will be executed at the time of exit.
2970 """This will be executed at the time of exit.
2970
2971
2971 Cleanup operations and saving of persistent data that is done
2972 Cleanup operations and saving of persistent data that is done
2972 unconditionally by IPython should be performed here.
2973 unconditionally by IPython should be performed here.
2973
2974
2974 For things that may depend on startup flags or platform specifics (such
2975 For things that may depend on startup flags or platform specifics (such
2975 as having readline or not), register a separate atexit function in the
2976 as having readline or not), register a separate atexit function in the
2976 code that has the appropriate information, rather than trying to
2977 code that has the appropriate information, rather than trying to
2977 clutter
2978 clutter
2978 """
2979 """
2979 # Close the history session (this stores the end time and line count)
2980 # Close the history session (this stores the end time and line count)
2980 # this must be *before* the tempfile cleanup, in case of temporary
2981 # this must be *before* the tempfile cleanup, in case of temporary
2981 # history db
2982 # history db
2982 self.history_manager.end_session()
2983 self.history_manager.end_session()
2983
2984
2984 # Cleanup all tempfiles left around
2985 # Cleanup all tempfiles left around
2985 for tfile in self.tempfiles:
2986 for tfile in self.tempfiles:
2986 try:
2987 try:
2987 os.unlink(tfile)
2988 os.unlink(tfile)
2988 except OSError:
2989 except OSError:
2989 pass
2990 pass
2990
2991
2991 # Clear all user namespaces to release all references cleanly.
2992 # Clear all user namespaces to release all references cleanly.
2992 self.reset(new_session=False)
2993 self.reset(new_session=False)
2993
2994
2994 # Run user hooks
2995 # Run user hooks
2995 self.hooks.shutdown_hook()
2996 self.hooks.shutdown_hook()
2996
2997
2997 def cleanup(self):
2998 def cleanup(self):
2998 self.restore_sys_module_state()
2999 self.restore_sys_module_state()
2999
3000
3000
3001
3001 class InteractiveShellABC(object):
3002 class InteractiveShellABC(object):
3002 """An abstract base class for InteractiveShell."""
3003 """An abstract base class for InteractiveShell."""
3003 __metaclass__ = abc.ABCMeta
3004 __metaclass__ = abc.ABCMeta
3004
3005
3005 InteractiveShellABC.register(InteractiveShell)
3006 InteractiveShellABC.register(InteractiveShell)
@@ -1,220 +1,220 b''
1 """Logger class for IPython's logging facilities.
1 """Logger class for IPython's logging facilities.
2 """
2 """
3
3
4 #*****************************************************************************
4 #*****************************************************************************
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #*****************************************************************************
10 #*****************************************************************************
11
11
12 #****************************************************************************
12 #****************************************************************************
13 # Modules and globals
13 # Modules and globals
14
14
15 # Python standard modules
15 # Python standard modules
16 import glob
16 import glob
17 import io
17 import io
18 import os
18 import os
19 import time
19 import time
20
20
21 from IPython.utils.py3compat import str_to_unicode
21 from IPython.utils.py3compat import str_to_unicode
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
25 # ipython and does input cache management. Finish cleanup later...
25 # ipython and does input cache management. Finish cleanup later...
26
26
27 class Logger(object):
27 class Logger(object):
28 """A Logfile class with different policies for file creation"""
28 """A Logfile class with different policies for file creation"""
29
29
30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
31 logmode='over'):
31 logmode='over'):
32
32
33 # this is the full ipython instance, we need some attributes from it
33 # this is the full ipython instance, we need some attributes from it
34 # which won't exist until later. What a mess, clean up later...
34 # which won't exist until later. What a mess, clean up later...
35 self.home_dir = home_dir
35 self.home_dir = home_dir
36
36
37 self.logfname = logfname
37 self.logfname = logfname
38 self.loghead = loghead
38 self.loghead = loghead
39 self.logmode = logmode
39 self.logmode = logmode
40 self.logfile = None
40 self.logfile = None
41
41
42 # Whether to log raw or processed input
42 # Whether to log raw or processed input
43 self.log_raw_input = False
43 self.log_raw_input = False
44
44
45 # whether to also log output
45 # whether to also log output
46 self.log_output = False
46 self.log_output = False
47
47
48 # whether to put timestamps before each log entry
48 # whether to put timestamps before each log entry
49 self.timestamp = False
49 self.timestamp = False
50
50
51 # activity control flags
51 # activity control flags
52 self.log_active = False
52 self.log_active = False
53
53
54 # logmode is a validated property
54 # logmode is a validated property
55 def _set_mode(self,mode):
55 def _set_mode(self,mode):
56 if mode not in ['append','backup','global','over','rotate']:
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 self._logmode = mode
58 self._logmode = mode
59
59
60 def _get_mode(self):
60 def _get_mode(self):
61 return self._logmode
61 return self._logmode
62
62
63 logmode = property(_get_mode,_set_mode)
63 logmode = property(_get_mode,_set_mode)
64
64
65 def logstart(self, logfname=None, loghead=None, logmode=None,
65 def logstart(self, logfname=None, loghead=None, logmode=None,
66 log_output=False, timestamp=False, log_raw_input=False):
66 log_output=False, timestamp=False, log_raw_input=False):
67 """Generate a new log-file with a default header.
67 """Generate a new log-file with a default header.
68
68
69 Raises RuntimeError if the log has already been started"""
69 Raises RuntimeError if the log has already been started"""
70
70
71 if self.logfile is not None:
71 if self.logfile is not None:
72 raise RuntimeError('Log file is already active: %s' %
72 raise RuntimeError('Log file is already active: %s' %
73 self.logfname)
73 self.logfname)
74
74
75 # The parameters can override constructor defaults
75 # The parameters can override constructor defaults
76 if logfname is not None: self.logfname = logfname
76 if logfname is not None: self.logfname = logfname
77 if loghead is not None: self.loghead = loghead
77 if loghead is not None: self.loghead = loghead
78 if logmode is not None: self.logmode = logmode
78 if logmode is not None: self.logmode = logmode
79
79
80 # Parameters not part of the constructor
80 # Parameters not part of the constructor
81 self.timestamp = timestamp
81 self.timestamp = timestamp
82 self.log_output = log_output
82 self.log_output = log_output
83 self.log_raw_input = log_raw_input
83 self.log_raw_input = log_raw_input
84
84
85 # init depending on the log mode requested
85 # init depending on the log mode requested
86 isfile = os.path.isfile
86 isfile = os.path.isfile
87 logmode = self.logmode
87 logmode = self.logmode
88
88
89 if logmode == 'append':
89 if logmode == 'append':
90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
91
91
92 elif logmode == 'backup':
92 elif logmode == 'backup':
93 if isfile(self.logfname):
93 if isfile(self.logfname):
94 backup_logname = self.logfname+'~'
94 backup_logname = self.logfname+'~'
95 # Manually remove any old backup, since os.rename may fail
95 # Manually remove any old backup, since os.rename may fail
96 # under Windows.
96 # under Windows.
97 if isfile(backup_logname):
97 if isfile(backup_logname):
98 os.remove(backup_logname)
98 os.remove(backup_logname)
99 os.rename(self.logfname,backup_logname)
99 os.rename(self.logfname,backup_logname)
100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
101
101
102 elif logmode == 'global':
102 elif logmode == 'global':
103 self.logfname = os.path.join(self.home_dir,self.logfname)
103 self.logfname = os.path.join(self.home_dir,self.logfname)
104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
105
105
106 elif logmode == 'over':
106 elif logmode == 'over':
107 if isfile(self.logfname):
107 if isfile(self.logfname):
108 os.remove(self.logfname)
108 os.remove(self.logfname)
109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
110
110
111 elif logmode == 'rotate':
111 elif logmode == 'rotate':
112 if isfile(self.logfname):
112 if isfile(self.logfname):
113 if isfile(self.logfname+'.001~'):
113 if isfile(self.logfname+'.001~'):
114 old = glob.glob(self.logfname+'.*~')
114 old = glob.glob(self.logfname+'.*~')
115 old.sort()
115 old.sort()
116 old.reverse()
116 old.reverse()
117 for f in old:
117 for f in old:
118 root, ext = os.path.splitext(f)
118 root, ext = os.path.splitext(f)
119 num = int(ext[1:-1])+1
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 os.rename(self.logfname, self.logfname+'.001~')
121 os.rename(self.logfname, self.logfname+'.001~')
122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
123
123
124 if logmode != 'append':
124 if logmode != 'append':
125 self.logfile.write(self.loghead)
125 self.logfile.write(self.loghead)
126
126
127 self.logfile.flush()
127 self.logfile.flush()
128 self.log_active = True
128 self.log_active = True
129
129
130 def switch_log(self,val):
130 def switch_log(self,val):
131 """Switch logging on/off. val should be ONLY a boolean."""
131 """Switch logging on/off. val should be ONLY a boolean."""
132
132
133 if val not in [False,True,0,1]:
133 if val not in [False,True,0,1]:
134 raise ValueError, \
134 raise ValueError('Call switch_log ONLY with a boolean argument, '
135 'Call switch_log ONLY with a boolean argument, not with:',val
135 'not with: %s' % val)
136
136
137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138
138
139 if self.logfile is None:
139 if self.logfile is None:
140 print """
140 print """
141 Logging hasn't been started yet (use logstart for that).
141 Logging hasn't been started yet (use logstart for that).
142
142
143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 which already exists. But you must first start the logging process with
144 which already exists. But you must first start the logging process with
145 %logstart (optionally giving a logfile name)."""
145 %logstart (optionally giving a logfile name)."""
146
146
147 else:
147 else:
148 if self.log_active == val:
148 if self.log_active == val:
149 print 'Logging is already',label[val]
149 print 'Logging is already',label[val]
150 else:
150 else:
151 print 'Switching logging',label[val]
151 print 'Switching logging',label[val]
152 self.log_active = not self.log_active
152 self.log_active = not self.log_active
153 self.log_active_out = self.log_active
153 self.log_active_out = self.log_active
154
154
155 def logstate(self):
155 def logstate(self):
156 """Print a status message about the logger."""
156 """Print a status message about the logger."""
157 if self.logfile is None:
157 if self.logfile is None:
158 print 'Logging has not been activated.'
158 print 'Logging has not been activated.'
159 else:
159 else:
160 state = self.log_active and 'active' or 'temporarily suspended'
160 state = self.log_active and 'active' or 'temporarily suspended'
161 print 'Filename :',self.logfname
161 print 'Filename :',self.logfname
162 print 'Mode :',self.logmode
162 print 'Mode :',self.logmode
163 print 'Output logging :',self.log_output
163 print 'Output logging :',self.log_output
164 print 'Raw input log :',self.log_raw_input
164 print 'Raw input log :',self.log_raw_input
165 print 'Timestamping :',self.timestamp
165 print 'Timestamping :',self.timestamp
166 print 'State :',state
166 print 'State :',state
167
167
168 def log(self, line_mod, line_ori):
168 def log(self, line_mod, line_ori):
169 """Write the sources to a log.
169 """Write the sources to a log.
170
170
171 Inputs:
171 Inputs:
172
172
173 - line_mod: possibly modified input, such as the transformations made
173 - line_mod: possibly modified input, such as the transformations made
174 by input prefilters or input handlers of various kinds. This should
174 by input prefilters or input handlers of various kinds. This should
175 always be valid Python.
175 always be valid Python.
176
176
177 - line_ori: unmodified input line from the user. This is not
177 - line_ori: unmodified input line from the user. This is not
178 necessarily valid Python.
178 necessarily valid Python.
179 """
179 """
180
180
181 # Write the log line, but decide which one according to the
181 # Write the log line, but decide which one according to the
182 # log_raw_input flag, set when the log is started.
182 # log_raw_input flag, set when the log is started.
183 if self.log_raw_input:
183 if self.log_raw_input:
184 self.log_write(line_ori)
184 self.log_write(line_ori)
185 else:
185 else:
186 self.log_write(line_mod)
186 self.log_write(line_mod)
187
187
188 def log_write(self, data, kind='input'):
188 def log_write(self, data, kind='input'):
189 """Write data to the log file, if active"""
189 """Write data to the log file, if active"""
190
190
191 #print 'data: %r' % data # dbg
191 #print 'data: %r' % data # dbg
192 if self.log_active and data:
192 if self.log_active and data:
193 write = self.logfile.write
193 write = self.logfile.write
194 if kind=='input':
194 if kind=='input':
195 if self.timestamp:
195 if self.timestamp:
196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
197 time.localtime())))
197 time.localtime())))
198 write(data)
198 write(data)
199 elif kind=='output' and self.log_output:
199 elif kind=='output' and self.log_output:
200 odata = u'\n'.join([u'#[Out]# %s' % s
200 odata = u'\n'.join([u'#[Out]# %s' % s
201 for s in data.splitlines()])
201 for s in data.splitlines()])
202 write(u'%s\n' % odata)
202 write(u'%s\n' % odata)
203 self.logfile.flush()
203 self.logfile.flush()
204
204
205 def logstop(self):
205 def logstop(self):
206 """Fully stop logging and close log file.
206 """Fully stop logging and close log file.
207
207
208 In order to start logging again, a new logstart() call needs to be
208 In order to start logging again, a new logstart() call needs to be
209 made, possibly (though not necessarily) with a new filename, mode and
209 made, possibly (though not necessarily) with a new filename, mode and
210 other options."""
210 other options."""
211
211
212 if self.logfile is not None:
212 if self.logfile is not None:
213 self.logfile.close()
213 self.logfile.close()
214 self.logfile = None
214 self.logfile = None
215 else:
215 else:
216 print "Logging hadn't been started."
216 print "Logging hadn't been started."
217 self.log_active = False
217 self.log_active = False
218
218
219 # For backwards compatibility, in case anyone was using this.
219 # For backwards compatibility, in case anyone was using this.
220 close_log = logstop
220 close_log = logstop
@@ -1,617 +1,617 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Stdlib
17 # Stdlib
18 import os
18 import os
19 import re
19 import re
20 import sys
20 import sys
21 import types
21 import types
22 from getopt import getopt, GetoptError
22 from getopt import getopt, GetoptError
23
23
24 # Our own
24 # Our own
25 from IPython.config.configurable import Configurable
25 from IPython.config.configurable import Configurable
26 from IPython.core import oinspect
26 from IPython.core import oinspect
27 from IPython.core.error import UsageError
27 from IPython.core.error import UsageError
28 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
28 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
29 from IPython.external.decorator import decorator
29 from IPython.external.decorator import decorator
30 from IPython.utils.ipstruct import Struct
30 from IPython.utils.ipstruct import Struct
31 from IPython.utils.process import arg_split
31 from IPython.utils.process import arg_split
32 from IPython.utils.text import dedent
32 from IPython.utils.text import dedent
33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
34 from IPython.utils.warn import error, warn
34 from IPython.utils.warn import error, warn
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Globals
37 # Globals
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 # A dict we'll use for each class that has magics, used as temporary storage to
40 # A dict we'll use for each class that has magics, used as temporary storage to
41 # pass information between the @line/cell_magic method decorators and the
41 # pass information between the @line/cell_magic method decorators and the
42 # @magics_class class decorator, because the method decorators have no
42 # @magics_class class decorator, because the method decorators have no
43 # access to the class when they run. See for more details:
43 # access to the class when they run. See for more details:
44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
45
45
46 magics = dict(line={}, cell={})
46 magics = dict(line={}, cell={})
47
47
48 magic_kinds = ('line', 'cell')
48 magic_kinds = ('line', 'cell')
49 magic_spec = ('line', 'cell', 'line_cell')
49 magic_spec = ('line', 'cell', 'line_cell')
50 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
50 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
51
51
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53 # Utility classes and functions
53 # Utility classes and functions
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55
55
56 class Bunch: pass
56 class Bunch: pass
57
57
58
58
59 def on_off(tag):
59 def on_off(tag):
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 return ['OFF','ON'][tag]
61 return ['OFF','ON'][tag]
62
62
63
63
64 def compress_dhist(dh):
64 def compress_dhist(dh):
65 """Compress a directory history into a new one with at most 20 entries.
65 """Compress a directory history into a new one with at most 20 entries.
66
66
67 Return a new list made from the first and last 10 elements of dhist after
67 Return a new list made from the first and last 10 elements of dhist after
68 removal of duplicates.
68 removal of duplicates.
69 """
69 """
70 head, tail = dh[:-10], dh[-10:]
70 head, tail = dh[:-10], dh[-10:]
71
71
72 newhead = []
72 newhead = []
73 done = set()
73 done = set()
74 for h in head:
74 for h in head:
75 if h in done:
75 if h in done:
76 continue
76 continue
77 newhead.append(h)
77 newhead.append(h)
78 done.add(h)
78 done.add(h)
79
79
80 return newhead + tail
80 return newhead + tail
81
81
82
82
83 def needs_local_scope(func):
83 def needs_local_scope(func):
84 """Decorator to mark magic functions which need to local scope to run."""
84 """Decorator to mark magic functions which need to local scope to run."""
85 func.needs_local_scope = True
85 func.needs_local_scope = True
86 return func
86 return func
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89 # Class and method decorators for registering magics
89 # Class and method decorators for registering magics
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91
91
92 def magics_class(cls):
92 def magics_class(cls):
93 """Class decorator for all subclasses of the main Magics class.
93 """Class decorator for all subclasses of the main Magics class.
94
94
95 Any class that subclasses Magics *must* also apply this decorator, to
95 Any class that subclasses Magics *must* also apply this decorator, to
96 ensure that all the methods that have been decorated as line/cell magics
96 ensure that all the methods that have been decorated as line/cell magics
97 get correctly registered in the class instance. This is necessary because
97 get correctly registered in the class instance. This is necessary because
98 when method decorators run, the class does not exist yet, so they
98 when method decorators run, the class does not exist yet, so they
99 temporarily store their information into a module global. Application of
99 temporarily store their information into a module global. Application of
100 this class decorator copies that global data to the class instance and
100 this class decorator copies that global data to the class instance and
101 clears the global.
101 clears the global.
102
102
103 Obviously, this mechanism is not thread-safe, which means that the
103 Obviously, this mechanism is not thread-safe, which means that the
104 *creation* of subclasses of Magic should only be done in a single-thread
104 *creation* of subclasses of Magic should only be done in a single-thread
105 context. Instantiation of the classes has no restrictions. Given that
105 context. Instantiation of the classes has no restrictions. Given that
106 these classes are typically created at IPython startup time and before user
106 these classes are typically created at IPython startup time and before user
107 application code becomes active, in practice this should not pose any
107 application code becomes active, in practice this should not pose any
108 problems.
108 problems.
109 """
109 """
110 cls.registered = True
110 cls.registered = True
111 cls.magics = dict(line = magics['line'],
111 cls.magics = dict(line = magics['line'],
112 cell = magics['cell'])
112 cell = magics['cell'])
113 magics['line'] = {}
113 magics['line'] = {}
114 magics['cell'] = {}
114 magics['cell'] = {}
115 return cls
115 return cls
116
116
117
117
118 def record_magic(dct, magic_kind, magic_name, func):
118 def record_magic(dct, magic_kind, magic_name, func):
119 """Utility function to store a function as a magic of a specific kind.
119 """Utility function to store a function as a magic of a specific kind.
120
120
121 Parameters
121 Parameters
122 ----------
122 ----------
123 dct : dict
123 dct : dict
124 A dictionary with 'line' and 'cell' subdicts.
124 A dictionary with 'line' and 'cell' subdicts.
125
125
126 magic_kind : str
126 magic_kind : str
127 Kind of magic to be stored.
127 Kind of magic to be stored.
128
128
129 magic_name : str
129 magic_name : str
130 Key to store the magic as.
130 Key to store the magic as.
131
131
132 func : function
132 func : function
133 Callable object to store.
133 Callable object to store.
134 """
134 """
135 if magic_kind == 'line_cell':
135 if magic_kind == 'line_cell':
136 dct['line'][magic_name] = dct['cell'][magic_name] = func
136 dct['line'][magic_name] = dct['cell'][magic_name] = func
137 else:
137 else:
138 dct[magic_kind][magic_name] = func
138 dct[magic_kind][magic_name] = func
139
139
140
140
141 def validate_type(magic_kind):
141 def validate_type(magic_kind):
142 """Ensure that the given magic_kind is valid.
142 """Ensure that the given magic_kind is valid.
143
143
144 Check that the given magic_kind is one of the accepted spec types (stored
144 Check that the given magic_kind is one of the accepted spec types (stored
145 in the global `magic_spec`), raise ValueError otherwise.
145 in the global `magic_spec`), raise ValueError otherwise.
146 """
146 """
147 if magic_kind not in magic_spec:
147 if magic_kind not in magic_spec:
148 raise ValueError('magic_kind must be one of %s, %s given' %
148 raise ValueError('magic_kind must be one of %s, %s given' %
149 magic_kinds, magic_kind)
149 magic_kinds, magic_kind)
150
150
151
151
152 # The docstrings for the decorator below will be fairly similar for the two
152 # The docstrings for the decorator below will be fairly similar for the two
153 # types (method and function), so we generate them here once and reuse the
153 # types (method and function), so we generate them here once and reuse the
154 # templates below.
154 # templates below.
155 _docstring_template = \
155 _docstring_template = \
156 """Decorate the given {0} as {1} magic.
156 """Decorate the given {0} as {1} magic.
157
157
158 The decorator can be used with or without arguments, as follows.
158 The decorator can be used with or without arguments, as follows.
159
159
160 i) without arguments: it will create a {1} magic named as the {0} being
160 i) without arguments: it will create a {1} magic named as the {0} being
161 decorated::
161 decorated::
162
162
163 @deco
163 @deco
164 def foo(...)
164 def foo(...)
165
165
166 will create a {1} magic named `foo`.
166 will create a {1} magic named `foo`.
167
167
168 ii) with one string argument: which will be used as the actual name of the
168 ii) with one string argument: which will be used as the actual name of the
169 resulting magic::
169 resulting magic::
170
170
171 @deco('bar')
171 @deco('bar')
172 def foo(...)
172 def foo(...)
173
173
174 will create a {1} magic named `bar`.
174 will create a {1} magic named `bar`.
175 """
175 """
176
176
177 # These two are decorator factories. While they are conceptually very similar,
177 # These two are decorator factories. While they are conceptually very similar,
178 # there are enough differences in the details that it's simpler to have them
178 # there are enough differences in the details that it's simpler to have them
179 # written as completely standalone functions rather than trying to share code
179 # written as completely standalone functions rather than trying to share code
180 # and make a single one with convoluted logic.
180 # and make a single one with convoluted logic.
181
181
182 def _method_magic_marker(magic_kind):
182 def _method_magic_marker(magic_kind):
183 """Decorator factory for methods in Magics subclasses.
183 """Decorator factory for methods in Magics subclasses.
184 """
184 """
185
185
186 validate_type(magic_kind)
186 validate_type(magic_kind)
187
187
188 # This is a closure to capture the magic_kind. We could also use a class,
188 # This is a closure to capture the magic_kind. We could also use a class,
189 # but it's overkill for just that one bit of state.
189 # but it's overkill for just that one bit of state.
190 def magic_deco(arg):
190 def magic_deco(arg):
191 call = lambda f, *a, **k: f(*a, **k)
191 call = lambda f, *a, **k: f(*a, **k)
192
192
193 if callable(arg):
193 if callable(arg):
194 # "Naked" decorator call (just @foo, no args)
194 # "Naked" decorator call (just @foo, no args)
195 func = arg
195 func = arg
196 name = func.func_name
196 name = func.func_name
197 retval = decorator(call, func)
197 retval = decorator(call, func)
198 record_magic(magics, magic_kind, name, name)
198 record_magic(magics, magic_kind, name, name)
199 elif isinstance(arg, basestring):
199 elif isinstance(arg, basestring):
200 # Decorator called with arguments (@foo('bar'))
200 # Decorator called with arguments (@foo('bar'))
201 name = arg
201 name = arg
202 def mark(func, *a, **kw):
202 def mark(func, *a, **kw):
203 record_magic(magics, magic_kind, name, func.func_name)
203 record_magic(magics, magic_kind, name, func.func_name)
204 return decorator(call, func)
204 return decorator(call, func)
205 retval = mark
205 retval = mark
206 else:
206 else:
207 raise TypeError("Decorator can only be called with "
207 raise TypeError("Decorator can only be called with "
208 "string or function")
208 "string or function")
209 return retval
209 return retval
210
210
211 # Ensure the resulting decorator has a usable docstring
211 # Ensure the resulting decorator has a usable docstring
212 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
212 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
213 return magic_deco
213 return magic_deco
214
214
215
215
216 def _function_magic_marker(magic_kind):
216 def _function_magic_marker(magic_kind):
217 """Decorator factory for standalone functions.
217 """Decorator factory for standalone functions.
218 """
218 """
219 validate_type(magic_kind)
219 validate_type(magic_kind)
220
220
221 # This is a closure to capture the magic_kind. We could also use a class,
221 # This is a closure to capture the magic_kind. We could also use a class,
222 # but it's overkill for just that one bit of state.
222 # but it's overkill for just that one bit of state.
223 def magic_deco(arg):
223 def magic_deco(arg):
224 call = lambda f, *a, **k: f(*a, **k)
224 call = lambda f, *a, **k: f(*a, **k)
225
225
226 # Find get_ipython() in the caller's namespace
226 # Find get_ipython() in the caller's namespace
227 caller = sys._getframe(1)
227 caller = sys._getframe(1)
228 for ns in ['f_locals', 'f_globals', 'f_builtins']:
228 for ns in ['f_locals', 'f_globals', 'f_builtins']:
229 get_ipython = getattr(caller, ns).get('get_ipython')
229 get_ipython = getattr(caller, ns).get('get_ipython')
230 if get_ipython is not None:
230 if get_ipython is not None:
231 break
231 break
232 else:
232 else:
233 raise NameError('Decorator can only run in context where '
233 raise NameError('Decorator can only run in context where '
234 '`get_ipython` exists')
234 '`get_ipython` exists')
235
235
236 ip = get_ipython()
236 ip = get_ipython()
237
237
238 if callable(arg):
238 if callable(arg):
239 # "Naked" decorator call (just @foo, no args)
239 # "Naked" decorator call (just @foo, no args)
240 func = arg
240 func = arg
241 name = func.func_name
241 name = func.func_name
242 ip.register_magic_function(func, magic_kind, name)
242 ip.register_magic_function(func, magic_kind, name)
243 retval = decorator(call, func)
243 retval = decorator(call, func)
244 elif isinstance(arg, basestring):
244 elif isinstance(arg, basestring):
245 # Decorator called with arguments (@foo('bar'))
245 # Decorator called with arguments (@foo('bar'))
246 name = arg
246 name = arg
247 def mark(func, *a, **kw):
247 def mark(func, *a, **kw):
248 ip.register_magic_function(func, magic_kind, name)
248 ip.register_magic_function(func, magic_kind, name)
249 return decorator(call, func)
249 return decorator(call, func)
250 retval = mark
250 retval = mark
251 else:
251 else:
252 raise TypeError("Decorator can only be called with "
252 raise TypeError("Decorator can only be called with "
253 "string or function")
253 "string or function")
254 return retval
254 return retval
255
255
256 # Ensure the resulting decorator has a usable docstring
256 # Ensure the resulting decorator has a usable docstring
257 ds = _docstring_template.format('function', magic_kind)
257 ds = _docstring_template.format('function', magic_kind)
258
258
259 ds += dedent("""
259 ds += dedent("""
260 Note: this decorator can only be used in a context where IPython is already
260 Note: this decorator can only be used in a context where IPython is already
261 active, so that the `get_ipython()` call succeeds. You can therefore use
261 active, so that the `get_ipython()` call succeeds. You can therefore use
262 it in your startup files loaded after IPython initializes, but *not* in the
262 it in your startup files loaded after IPython initializes, but *not* in the
263 IPython configuration file itself, which is executed before IPython is
263 IPython configuration file itself, which is executed before IPython is
264 fully up and running. Any file located in the `startup` subdirectory of
264 fully up and running. Any file located in the `startup` subdirectory of
265 your configuration profile will be OK in this sense.
265 your configuration profile will be OK in this sense.
266 """)
266 """)
267
267
268 magic_deco.__doc__ = ds
268 magic_deco.__doc__ = ds
269 return magic_deco
269 return magic_deco
270
270
271
271
272 # Create the actual decorators for public use
272 # Create the actual decorators for public use
273
273
274 # These three are used to decorate methods in class definitions
274 # These three are used to decorate methods in class definitions
275 line_magic = _method_magic_marker('line')
275 line_magic = _method_magic_marker('line')
276 cell_magic = _method_magic_marker('cell')
276 cell_magic = _method_magic_marker('cell')
277 line_cell_magic = _method_magic_marker('line_cell')
277 line_cell_magic = _method_magic_marker('line_cell')
278
278
279 # These three decorate standalone functions and perform the decoration
279 # These three decorate standalone functions and perform the decoration
280 # immediately. They can only run where get_ipython() works
280 # immediately. They can only run where get_ipython() works
281 register_line_magic = _function_magic_marker('line')
281 register_line_magic = _function_magic_marker('line')
282 register_cell_magic = _function_magic_marker('cell')
282 register_cell_magic = _function_magic_marker('cell')
283 register_line_cell_magic = _function_magic_marker('line_cell')
283 register_line_cell_magic = _function_magic_marker('line_cell')
284
284
285 #-----------------------------------------------------------------------------
285 #-----------------------------------------------------------------------------
286 # Core Magic classes
286 # Core Magic classes
287 #-----------------------------------------------------------------------------
287 #-----------------------------------------------------------------------------
288
288
289 class MagicsManager(Configurable):
289 class MagicsManager(Configurable):
290 """Object that handles all magic-related functionality for IPython.
290 """Object that handles all magic-related functionality for IPython.
291 """
291 """
292 # Non-configurable class attributes
292 # Non-configurable class attributes
293
293
294 # A two-level dict, first keyed by magic type, then by magic function, and
294 # A two-level dict, first keyed by magic type, then by magic function, and
295 # holding the actual callable object as value. This is the dict used for
295 # holding the actual callable object as value. This is the dict used for
296 # magic function dispatch
296 # magic function dispatch
297 magics = Dict
297 magics = Dict
298
298
299 # A registry of the original objects that we've been given holding magics.
299 # A registry of the original objects that we've been given holding magics.
300 registry = Dict
300 registry = Dict
301
301
302 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
302 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
303
303
304 auto_magic = Bool(True, config=True, help=
304 auto_magic = Bool(True, config=True, help=
305 "Automatically call line magics without requiring explicit % prefix")
305 "Automatically call line magics without requiring explicit % prefix")
306
306
307 _auto_status = [
307 _auto_status = [
308 'Automagic is OFF, % prefix IS needed for line magics.',
308 'Automagic is OFF, % prefix IS needed for line magics.',
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
310
310
311 user_magics = Instance('IPython.core.magics.UserMagics')
311 user_magics = Instance('IPython.core.magics.UserMagics')
312
312
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
314
314
315 super(MagicsManager, self).__init__(shell=shell, config=config,
315 super(MagicsManager, self).__init__(shell=shell, config=config,
316 user_magics=user_magics, **traits)
316 user_magics=user_magics, **traits)
317 self.magics = dict(line={}, cell={})
317 self.magics = dict(line={}, cell={})
318 # Let's add the user_magics to the registry for uniformity, so *all*
318 # Let's add the user_magics to the registry for uniformity, so *all*
319 # registered magic containers can be found there.
319 # registered magic containers can be found there.
320 self.registry[user_magics.__class__.__name__] = user_magics
320 self.registry[user_magics.__class__.__name__] = user_magics
321
321
322 def auto_status(self):
322 def auto_status(self):
323 """Return descriptive string with automagic status."""
323 """Return descriptive string with automagic status."""
324 return self._auto_status[self.auto_magic]
324 return self._auto_status[self.auto_magic]
325
325
326 def lsmagic_info(self):
326 def lsmagic_info(self):
327 magic_list = []
327 magic_list = []
328 for m_type in self.magics :
328 for m_type in self.magics :
329 for m_name,mgc in self.magics[m_type].items():
329 for m_name,mgc in self.magics[m_type].items():
330 try :
330 try :
331 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
331 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
332 except AttributeError :
332 except AttributeError :
333 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
333 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
334 return magic_list
334 return magic_list
335
335
336 def lsmagic(self):
336 def lsmagic(self):
337 """Return a dict of currently available magic functions.
337 """Return a dict of currently available magic functions.
338
338
339 The return dict has the keys 'line' and 'cell', corresponding to the
339 The return dict has the keys 'line' and 'cell', corresponding to the
340 two types of magics we support. Each value is a list of names.
340 two types of magics we support. Each value is a list of names.
341 """
341 """
342 return self.magics
342 return self.magics
343
343
344 def lsmagic_docs(self, brief=False, missing=''):
344 def lsmagic_docs(self, brief=False, missing=''):
345 """Return dict of documentation of magic functions.
345 """Return dict of documentation of magic functions.
346
346
347 The return dict has the keys 'line' and 'cell', corresponding to the
347 The return dict has the keys 'line' and 'cell', corresponding to the
348 two types of magics we support. Each value is a dict keyed by magic
348 two types of magics we support. Each value is a dict keyed by magic
349 name whose value is the function docstring. If a docstring is
349 name whose value is the function docstring. If a docstring is
350 unavailable, the value of `missing` is used instead.
350 unavailable, the value of `missing` is used instead.
351
351
352 If brief is True, only the first line of each docstring will be returned.
352 If brief is True, only the first line of each docstring will be returned.
353 """
353 """
354 docs = {}
354 docs = {}
355 for m_type in self.magics:
355 for m_type in self.magics:
356 m_docs = {}
356 m_docs = {}
357 for m_name, m_func in self.magics[m_type].iteritems():
357 for m_name, m_func in self.magics[m_type].iteritems():
358 if m_func.__doc__:
358 if m_func.__doc__:
359 if brief:
359 if brief:
360 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
360 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
361 else:
361 else:
362 m_docs[m_name] = m_func.__doc__.rstrip()
362 m_docs[m_name] = m_func.__doc__.rstrip()
363 else:
363 else:
364 m_docs[m_name] = missing
364 m_docs[m_name] = missing
365 docs[m_type] = m_docs
365 docs[m_type] = m_docs
366 return docs
366 return docs
367
367
368 def register(self, *magic_objects):
368 def register(self, *magic_objects):
369 """Register one or more instances of Magics.
369 """Register one or more instances of Magics.
370
370
371 Take one or more classes or instances of classes that subclass the main
371 Take one or more classes or instances of classes that subclass the main
372 `core.Magic` class, and register them with IPython to use the magic
372 `core.Magic` class, and register them with IPython to use the magic
373 functions they provide. The registration process will then ensure that
373 functions they provide. The registration process will then ensure that
374 any methods that have decorated to provide line and/or cell magics will
374 any methods that have decorated to provide line and/or cell magics will
375 be recognized with the `%x`/`%%x` syntax as a line/cell magic
375 be recognized with the `%x`/`%%x` syntax as a line/cell magic
376 respectively.
376 respectively.
377
377
378 If classes are given, they will be instantiated with the default
378 If classes are given, they will be instantiated with the default
379 constructor. If your classes need a custom constructor, you should
379 constructor. If your classes need a custom constructor, you should
380 instanitate them first and pass the instance.
380 instanitate them first and pass the instance.
381
381
382 The provided arguments can be an arbitrary mix of classes and instances.
382 The provided arguments can be an arbitrary mix of classes and instances.
383
383
384 Parameters
384 Parameters
385 ----------
385 ----------
386 magic_objects : one or more classes or instances
386 magic_objects : one or more classes or instances
387 """
387 """
388 # Start by validating them to ensure they have all had their magic
388 # Start by validating them to ensure they have all had their magic
389 # methods registered at the instance level
389 # methods registered at the instance level
390 for m in magic_objects:
390 for m in magic_objects:
391 if not m.registered:
391 if not m.registered:
392 raise ValueError("Class of magics %r was constructed without "
392 raise ValueError("Class of magics %r was constructed without "
393 "the @register_magics class decorator")
393 "the @register_magics class decorator")
394 if type(m) in (type, MetaHasTraits):
394 if type(m) in (type, MetaHasTraits):
395 # If we're given an uninstantiated class
395 # If we're given an uninstantiated class
396 m = m(shell=self.shell)
396 m = m(shell=self.shell)
397
397
398 # Now that we have an instance, we can register it and update the
398 # Now that we have an instance, we can register it and update the
399 # table of callables
399 # table of callables
400 self.registry[m.__class__.__name__] = m
400 self.registry[m.__class__.__name__] = m
401 for mtype in magic_kinds:
401 for mtype in magic_kinds:
402 self.magics[mtype].update(m.magics[mtype])
402 self.magics[mtype].update(m.magics[mtype])
403
403
404 def register_function(self, func, magic_kind='line', magic_name=None):
404 def register_function(self, func, magic_kind='line', magic_name=None):
405 """Expose a standalone function as magic function for IPython.
405 """Expose a standalone function as magic function for IPython.
406
406
407 This will create an IPython magic (line, cell or both) from a
407 This will create an IPython magic (line, cell or both) from a
408 standalone function. The functions should have the following
408 standalone function. The functions should have the following
409 signatures:
409 signatures:
410
410
411 * For line magics: `def f(line)`
411 * For line magics: `def f(line)`
412 * For cell magics: `def f(line, cell)`
412 * For cell magics: `def f(line, cell)`
413 * For a function that does both: `def f(line, cell=None)`
413 * For a function that does both: `def f(line, cell=None)`
414
414
415 In the latter case, the function will be called with `cell==None` when
415 In the latter case, the function will be called with `cell==None` when
416 invoked as `%f`, and with cell as a string when invoked as `%%f`.
416 invoked as `%f`, and with cell as a string when invoked as `%%f`.
417
417
418 Parameters
418 Parameters
419 ----------
419 ----------
420 func : callable
420 func : callable
421 Function to be registered as a magic.
421 Function to be registered as a magic.
422
422
423 magic_kind : str
423 magic_kind : str
424 Kind of magic, one of 'line', 'cell' or 'line_cell'
424 Kind of magic, one of 'line', 'cell' or 'line_cell'
425
425
426 magic_name : optional str
426 magic_name : optional str
427 If given, the name the magic will have in the IPython namespace. By
427 If given, the name the magic will have in the IPython namespace. By
428 default, the name of the function itself is used.
428 default, the name of the function itself is used.
429 """
429 """
430
430
431 # Create the new method in the user_magics and register it in the
431 # Create the new method in the user_magics and register it in the
432 # global table
432 # global table
433 validate_type(magic_kind)
433 validate_type(magic_kind)
434 magic_name = func.func_name if magic_name is None else magic_name
434 magic_name = func.func_name if magic_name is None else magic_name
435 setattr(self.user_magics, magic_name, func)
435 setattr(self.user_magics, magic_name, func)
436 record_magic(self.magics, magic_kind, magic_name, func)
436 record_magic(self.magics, magic_kind, magic_name, func)
437
437
438 def define_magic(self, name, func):
438 def define_magic(self, name, func):
439 """[Deprecated] Expose own function as magic function for IPython.
439 """[Deprecated] Expose own function as magic function for IPython.
440
440
441 Example::
441 Example::
442
442
443 def foo_impl(self, parameter_s=''):
443 def foo_impl(self, parameter_s=''):
444 'My very own magic!. (Use docstrings, IPython reads them).'
444 'My very own magic!. (Use docstrings, IPython reads them).'
445 print 'Magic function. Passed parameter is between < >:'
445 print 'Magic function. Passed parameter is between < >:'
446 print '<%s>' % parameter_s
446 print '<%s>' % parameter_s
447 print 'The self object is:', self
447 print 'The self object is:', self
448
448
449 ip.define_magic('foo',foo_impl)
449 ip.define_magic('foo',foo_impl)
450 """
450 """
451 meth = types.MethodType(func, self.user_magics)
451 meth = types.MethodType(func, self.user_magics)
452 setattr(self.user_magics, name, meth)
452 setattr(self.user_magics, name, meth)
453 record_magic(self.magics, 'line', name, meth)
453 record_magic(self.magics, 'line', name, meth)
454
454
455 # Key base class that provides the central functionality for magics.
455 # Key base class that provides the central functionality for magics.
456
456
457 class Magics(object):
457 class Magics(object):
458 """Base class for implementing magic functions.
458 """Base class for implementing magic functions.
459
459
460 Shell functions which can be reached as %function_name. All magic
460 Shell functions which can be reached as %function_name. All magic
461 functions should accept a string, which they can parse for their own
461 functions should accept a string, which they can parse for their own
462 needs. This can make some functions easier to type, eg `%cd ../`
462 needs. This can make some functions easier to type, eg `%cd ../`
463 vs. `%cd("../")`
463 vs. `%cd("../")`
464
464
465 Classes providing magic functions need to subclass this class, and they
465 Classes providing magic functions need to subclass this class, and they
466 MUST:
466 MUST:
467
467
468 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
468 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
469 individual methods as magic functions, AND
469 individual methods as magic functions, AND
470
470
471 - Use the class decorator `@magics_class` to ensure that the magic
471 - Use the class decorator `@magics_class` to ensure that the magic
472 methods are properly registered at the instance level upon instance
472 methods are properly registered at the instance level upon instance
473 initialization.
473 initialization.
474
474
475 See :mod:`magic_functions` for examples of actual implementation classes.
475 See :mod:`magic_functions` for examples of actual implementation classes.
476 """
476 """
477 # Dict holding all command-line options for each magic.
477 # Dict holding all command-line options for each magic.
478 options_table = None
478 options_table = None
479 # Dict for the mapping of magic names to methods, set by class decorator
479 # Dict for the mapping of magic names to methods, set by class decorator
480 magics = None
480 magics = None
481 # Flag to check that the class decorator was properly applied
481 # Flag to check that the class decorator was properly applied
482 registered = False
482 registered = False
483 # Instance of IPython shell
483 # Instance of IPython shell
484 shell = None
484 shell = None
485
485
486 def __init__(self, shell):
486 def __init__(self, shell):
487 if not(self.__class__.registered):
487 if not(self.__class__.registered):
488 raise ValueError('Magics subclass without registration - '
488 raise ValueError('Magics subclass without registration - '
489 'did you forget to apply @magics_class?')
489 'did you forget to apply @magics_class?')
490 self.shell = shell
490 self.shell = shell
491 self.options_table = {}
491 self.options_table = {}
492 # The method decorators are run when the instance doesn't exist yet, so
492 # The method decorators are run when the instance doesn't exist yet, so
493 # they can only record the names of the methods they are supposed to
493 # they can only record the names of the methods they are supposed to
494 # grab. Only now, that the instance exists, can we create the proper
494 # grab. Only now, that the instance exists, can we create the proper
495 # mapping to bound methods. So we read the info off the original names
495 # mapping to bound methods. So we read the info off the original names
496 # table and replace each method name by the actual bound method.
496 # table and replace each method name by the actual bound method.
497 # But we mustn't clobber the *class* mapping, in case of multiple instances.
497 # But we mustn't clobber the *class* mapping, in case of multiple instances.
498 class_magics = self.magics
498 class_magics = self.magics
499 self.magics = {}
499 self.magics = {}
500 for mtype in magic_kinds:
500 for mtype in magic_kinds:
501 tab = self.magics[mtype] = {}
501 tab = self.magics[mtype] = {}
502 cls_tab = class_magics[mtype]
502 cls_tab = class_magics[mtype]
503 for magic_name, meth_name in cls_tab.iteritems():
503 for magic_name, meth_name in cls_tab.iteritems():
504 if isinstance(meth_name, basestring):
504 if isinstance(meth_name, basestring):
505 # it's a method name, grab it
505 # it's a method name, grab it
506 tab[magic_name] = getattr(self, meth_name)
506 tab[magic_name] = getattr(self, meth_name)
507 else:
507 else:
508 # it's the real thing
508 # it's the real thing
509 tab[magic_name] = meth_name
509 tab[magic_name] = meth_name
510
510
511 def arg_err(self,func):
511 def arg_err(self,func):
512 """Print docstring if incorrect arguments were passed"""
512 """Print docstring if incorrect arguments were passed"""
513 print 'Error in arguments:'
513 print 'Error in arguments:'
514 print oinspect.getdoc(func)
514 print oinspect.getdoc(func)
515
515
516 def format_latex(self, strng):
516 def format_latex(self, strng):
517 """Format a string for latex inclusion."""
517 """Format a string for latex inclusion."""
518
518
519 # Characters that need to be escaped for latex:
519 # Characters that need to be escaped for latex:
520 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
520 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
521 # Magic command names as headers:
521 # Magic command names as headers:
522 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
522 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
523 re.MULTILINE)
523 re.MULTILINE)
524 # Magic commands
524 # Magic commands
525 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
525 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
526 re.MULTILINE)
526 re.MULTILINE)
527 # Paragraph continue
527 # Paragraph continue
528 par_re = re.compile(r'\\$',re.MULTILINE)
528 par_re = re.compile(r'\\$',re.MULTILINE)
529
529
530 # The "\n" symbol
530 # The "\n" symbol
531 newline_re = re.compile(r'\\n')
531 newline_re = re.compile(r'\\n')
532
532
533 # Now build the string for output:
533 # Now build the string for output:
534 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
534 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
535 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
535 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
536 strng)
536 strng)
537 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
537 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
538 strng = par_re.sub(r'\\\\',strng)
538 strng = par_re.sub(r'\\\\',strng)
539 strng = escape_re.sub(r'\\\1',strng)
539 strng = escape_re.sub(r'\\\1',strng)
540 strng = newline_re.sub(r'\\textbackslash{}n',strng)
540 strng = newline_re.sub(r'\\textbackslash{}n',strng)
541 return strng
541 return strng
542
542
543 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
543 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
544 """Parse options passed to an argument string.
544 """Parse options passed to an argument string.
545
545
546 The interface is similar to that of getopt(), but it returns back a
546 The interface is similar to that of getopt(), but it returns back a
547 Struct with the options as keys and the stripped argument string still
547 Struct with the options as keys and the stripped argument string still
548 as a string.
548 as a string.
549
549
550 arg_str is quoted as a true sys.argv vector by using shlex.split.
550 arg_str is quoted as a true sys.argv vector by using shlex.split.
551 This allows us to easily expand variables, glob files, quote
551 This allows us to easily expand variables, glob files, quote
552 arguments, etc.
552 arguments, etc.
553
553
554 Options:
554 Options:
555 -mode: default 'string'. If given as 'list', the argument string is
555 -mode: default 'string'. If given as 'list', the argument string is
556 returned as a list (split on whitespace) instead of a string.
556 returned as a list (split on whitespace) instead of a string.
557
557
558 -list_all: put all option values in lists. Normally only options
558 -list_all: put all option values in lists. Normally only options
559 appearing more than once are put in a list.
559 appearing more than once are put in a list.
560
560
561 -posix (True): whether to split the input line in POSIX mode or not,
561 -posix (True): whether to split the input line in POSIX mode or not,
562 as per the conventions outlined in the shlex module from the
562 as per the conventions outlined in the shlex module from the
563 standard library."""
563 standard library."""
564
564
565 # inject default options at the beginning of the input line
565 # inject default options at the beginning of the input line
566 caller = sys._getframe(1).f_code.co_name
566 caller = sys._getframe(1).f_code.co_name
567 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
567 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
568
568
569 mode = kw.get('mode','string')
569 mode = kw.get('mode','string')
570 if mode not in ['string','list']:
570 if mode not in ['string','list']:
571 raise ValueError,'incorrect mode given: %s' % mode
571 raise ValueError('incorrect mode given: %s' % mode)
572 # Get options
572 # Get options
573 list_all = kw.get('list_all',0)
573 list_all = kw.get('list_all',0)
574 posix = kw.get('posix', os.name == 'posix')
574 posix = kw.get('posix', os.name == 'posix')
575 strict = kw.get('strict', True)
575 strict = kw.get('strict', True)
576
576
577 # Check if we have more than one argument to warrant extra processing:
577 # Check if we have more than one argument to warrant extra processing:
578 odict = {} # Dictionary with options
578 odict = {} # Dictionary with options
579 args = arg_str.split()
579 args = arg_str.split()
580 if len(args) >= 1:
580 if len(args) >= 1:
581 # If the list of inputs only has 0 or 1 thing in it, there's no
581 # If the list of inputs only has 0 or 1 thing in it, there's no
582 # need to look for options
582 # need to look for options
583 argv = arg_split(arg_str, posix, strict)
583 argv = arg_split(arg_str, posix, strict)
584 # Do regular option processing
584 # Do regular option processing
585 try:
585 try:
586 opts,args = getopt(argv, opt_str, long_opts)
586 opts,args = getopt(argv, opt_str, long_opts)
587 except GetoptError as e:
587 except GetoptError as e:
588 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
588 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
589 " ".join(long_opts)))
589 " ".join(long_opts)))
590 for o,a in opts:
590 for o,a in opts:
591 if o.startswith('--'):
591 if o.startswith('--'):
592 o = o[2:]
592 o = o[2:]
593 else:
593 else:
594 o = o[1:]
594 o = o[1:]
595 try:
595 try:
596 odict[o].append(a)
596 odict[o].append(a)
597 except AttributeError:
597 except AttributeError:
598 odict[o] = [odict[o],a]
598 odict[o] = [odict[o],a]
599 except KeyError:
599 except KeyError:
600 if list_all:
600 if list_all:
601 odict[o] = [a]
601 odict[o] = [a]
602 else:
602 else:
603 odict[o] = a
603 odict[o] = a
604
604
605 # Prepare opts,args for return
605 # Prepare opts,args for return
606 opts = Struct(odict)
606 opts = Struct(odict)
607 if mode == 'string':
607 if mode == 'string':
608 args = ' '.join(args)
608 args = ' '.join(args)
609
609
610 return opts,args
610 return opts,args
611
611
612 def default_option(self, fn, optstr):
612 def default_option(self, fn, optstr):
613 """Make an entry in the options_table for fn, with value optstr"""
613 """Make an entry in the options_table for fn, with value optstr"""
614
614
615 if fn not in self.lsmagic():
615 if fn not in self.lsmagic():
616 error("%s is not a magic function" % fn)
616 error("%s is not a magic function" % fn)
617 self.options_table[fn] = optstr
617 self.options_table[fn] = optstr
@@ -1,1022 +1,1022 b''
1 """Implementation of execution-related magic functions.
1 """Implementation of execution-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import __builtin__ as builtin_mod
16 import __builtin__ as builtin_mod
17 import bdb
17 import bdb
18 import os
18 import os
19 import sys
19 import sys
20 import time
20 import time
21 from StringIO import StringIO
21 from StringIO import StringIO
22
22
23 # cProfile was added in Python2.5
23 # cProfile was added in Python2.5
24 try:
24 try:
25 import cProfile as profile
25 import cProfile as profile
26 import pstats
26 import pstats
27 except ImportError:
27 except ImportError:
28 # profile isn't bundled by default in Debian for license reasons
28 # profile isn't bundled by default in Debian for license reasons
29 try:
29 try:
30 import profile, pstats
30 import profile, pstats
31 except ImportError:
31 except ImportError:
32 profile = pstats = None
32 profile = pstats = None
33
33
34 # Our own packages
34 # Our own packages
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import magic_arguments
36 from IPython.core import magic_arguments
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core.error import UsageError
38 from IPython.core.error import UsageError
39 from IPython.core.macro import Macro
39 from IPython.core.macro import Macro
40 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
40 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
41 line_cell_magic, on_off, needs_local_scope)
41 line_cell_magic, on_off, needs_local_scope)
42 from IPython.testing.skipdoctest import skip_doctest
42 from IPython.testing.skipdoctest import skip_doctest
43 from IPython.utils import py3compat
43 from IPython.utils import py3compat
44 from IPython.utils.io import capture_output
44 from IPython.utils.io import capture_output
45 from IPython.utils.ipstruct import Struct
45 from IPython.utils.ipstruct import Struct
46 from IPython.utils.module_paths import find_mod
46 from IPython.utils.module_paths import find_mod
47 from IPython.utils.path import get_py_filename, unquote_filename
47 from IPython.utils.path import get_py_filename, unquote_filename
48 from IPython.utils.timing import clock, clock2
48 from IPython.utils.timing import clock, clock2
49 from IPython.utils.warn import warn, error
49 from IPython.utils.warn import warn, error
50
50
51 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
52 # Magic implementation classes
52 # Magic implementation classes
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54
54
55 @magics_class
55 @magics_class
56 class ExecutionMagics(Magics):
56 class ExecutionMagics(Magics):
57 """Magics related to code execution, debugging, profiling, etc.
57 """Magics related to code execution, debugging, profiling, etc.
58
58
59 """
59 """
60
60
61 def __init__(self, shell):
61 def __init__(self, shell):
62 super(ExecutionMagics, self).__init__(shell)
62 super(ExecutionMagics, self).__init__(shell)
63 if profile is None:
63 if profile is None:
64 self.prun = self.profile_missing_notice
64 self.prun = self.profile_missing_notice
65 # Default execution function used to actually run user code.
65 # Default execution function used to actually run user code.
66 self.default_runner = None
66 self.default_runner = None
67
67
68 def profile_missing_notice(self, *args, **kwargs):
68 def profile_missing_notice(self, *args, **kwargs):
69 error("""\
69 error("""\
70 The profile module could not be found. It has been removed from the standard
70 The profile module could not be found. It has been removed from the standard
71 python packages because of its non-free license. To use profiling, install the
71 python packages because of its non-free license. To use profiling, install the
72 python-profiler package from non-free.""")
72 python-profiler package from non-free.""")
73
73
74 @skip_doctest
74 @skip_doctest
75 @line_cell_magic
75 @line_cell_magic
76 def prun(self, parameter_s='', cell=None, user_mode=True,
76 def prun(self, parameter_s='', cell=None, user_mode=True,
77 opts=None,arg_lst=None,prog_ns=None):
77 opts=None,arg_lst=None,prog_ns=None):
78
78
79 """Run a statement through the python code profiler.
79 """Run a statement through the python code profiler.
80
80
81 Usage, in line mode:
81 Usage, in line mode:
82 %prun [options] statement
82 %prun [options] statement
83
83
84 Usage, in cell mode:
84 Usage, in cell mode:
85 %%prun [options] [statement]
85 %%prun [options] [statement]
86 code...
86 code...
87 code...
87 code...
88
88
89 In cell mode, the additional code lines are appended to the (possibly
89 In cell mode, the additional code lines are appended to the (possibly
90 empty) statement in the first line. Cell mode allows you to easily
90 empty) statement in the first line. Cell mode allows you to easily
91 profile multiline blocks without having to put them in a separate
91 profile multiline blocks without having to put them in a separate
92 function.
92 function.
93
93
94 The given statement (which doesn't require quote marks) is run via the
94 The given statement (which doesn't require quote marks) is run via the
95 python profiler in a manner similar to the profile.run() function.
95 python profiler in a manner similar to the profile.run() function.
96 Namespaces are internally managed to work correctly; profile.run
96 Namespaces are internally managed to work correctly; profile.run
97 cannot be used in IPython because it makes certain assumptions about
97 cannot be used in IPython because it makes certain assumptions about
98 namespaces which do not hold under IPython.
98 namespaces which do not hold under IPython.
99
99
100 Options:
100 Options:
101
101
102 -l <limit>: you can place restrictions on what or how much of the
102 -l <limit>: you can place restrictions on what or how much of the
103 profile gets printed. The limit value can be:
103 profile gets printed. The limit value can be:
104
104
105 * A string: only information for function names containing this string
105 * A string: only information for function names containing this string
106 is printed.
106 is printed.
107
107
108 * An integer: only these many lines are printed.
108 * An integer: only these many lines are printed.
109
109
110 * A float (between 0 and 1): this fraction of the report is printed
110 * A float (between 0 and 1): this fraction of the report is printed
111 (for example, use a limit of 0.4 to see the topmost 40% only).
111 (for example, use a limit of 0.4 to see the topmost 40% only).
112
112
113 You can combine several limits with repeated use of the option. For
113 You can combine several limits with repeated use of the option. For
114 example, '-l __init__ -l 5' will print only the topmost 5 lines of
114 example, '-l __init__ -l 5' will print only the topmost 5 lines of
115 information about class constructors.
115 information about class constructors.
116
116
117 -r: return the pstats.Stats object generated by the profiling. This
117 -r: return the pstats.Stats object generated by the profiling. This
118 object has all the information about the profile in it, and you can
118 object has all the information about the profile in it, and you can
119 later use it for further analysis or in other functions.
119 later use it for further analysis or in other functions.
120
120
121 -s <key>: sort profile by given key. You can provide more than one key
121 -s <key>: sort profile by given key. You can provide more than one key
122 by using the option several times: '-s key1 -s key2 -s key3...'. The
122 by using the option several times: '-s key1 -s key2 -s key3...'. The
123 default sorting key is 'time'.
123 default sorting key is 'time'.
124
124
125 The following is copied verbatim from the profile documentation
125 The following is copied verbatim from the profile documentation
126 referenced below:
126 referenced below:
127
127
128 When more than one key is provided, additional keys are used as
128 When more than one key is provided, additional keys are used as
129 secondary criteria when the there is equality in all keys selected
129 secondary criteria when the there is equality in all keys selected
130 before them.
130 before them.
131
131
132 Abbreviations can be used for any key names, as long as the
132 Abbreviations can be used for any key names, as long as the
133 abbreviation is unambiguous. The following are the keys currently
133 abbreviation is unambiguous. The following are the keys currently
134 defined:
134 defined:
135
135
136 Valid Arg Meaning
136 Valid Arg Meaning
137 "calls" call count
137 "calls" call count
138 "cumulative" cumulative time
138 "cumulative" cumulative time
139 "file" file name
139 "file" file name
140 "module" file name
140 "module" file name
141 "pcalls" primitive call count
141 "pcalls" primitive call count
142 "line" line number
142 "line" line number
143 "name" function name
143 "name" function name
144 "nfl" name/file/line
144 "nfl" name/file/line
145 "stdname" standard name
145 "stdname" standard name
146 "time" internal time
146 "time" internal time
147
147
148 Note that all sorts on statistics are in descending order (placing
148 Note that all sorts on statistics are in descending order (placing
149 most time consuming items first), where as name, file, and line number
149 most time consuming items first), where as name, file, and line number
150 searches are in ascending order (i.e., alphabetical). The subtle
150 searches are in ascending order (i.e., alphabetical). The subtle
151 distinction between "nfl" and "stdname" is that the standard name is a
151 distinction between "nfl" and "stdname" is that the standard name is a
152 sort of the name as printed, which means that the embedded line
152 sort of the name as printed, which means that the embedded line
153 numbers get compared in an odd way. For example, lines 3, 20, and 40
153 numbers get compared in an odd way. For example, lines 3, 20, and 40
154 would (if the file names were the same) appear in the string order
154 would (if the file names were the same) appear in the string order
155 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
155 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
156 line numbers. In fact, sort_stats("nfl") is the same as
156 line numbers. In fact, sort_stats("nfl") is the same as
157 sort_stats("name", "file", "line").
157 sort_stats("name", "file", "line").
158
158
159 -T <filename>: save profile results as shown on screen to a text
159 -T <filename>: save profile results as shown on screen to a text
160 file. The profile is still shown on screen.
160 file. The profile is still shown on screen.
161
161
162 -D <filename>: save (via dump_stats) profile statistics to given
162 -D <filename>: save (via dump_stats) profile statistics to given
163 filename. This data is in a format understood by the pstats module, and
163 filename. This data is in a format understood by the pstats module, and
164 is generated by a call to the dump_stats() method of profile
164 is generated by a call to the dump_stats() method of profile
165 objects. The profile is still shown on screen.
165 objects. The profile is still shown on screen.
166
166
167 -q: suppress output to the pager. Best used with -T and/or -D above.
167 -q: suppress output to the pager. Best used with -T and/or -D above.
168
168
169 If you want to run complete programs under the profiler's control, use
169 If you want to run complete programs under the profiler's control, use
170 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
170 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
171 contains profiler specific options as described here.
171 contains profiler specific options as described here.
172
172
173 You can read the complete documentation for the profile module with::
173 You can read the complete documentation for the profile module with::
174
174
175 In [1]: import profile; profile.help()
175 In [1]: import profile; profile.help()
176 """
176 """
177
177
178 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
178 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
179
179
180 if user_mode: # regular user call
180 if user_mode: # regular user call
181 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
181 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
182 list_all=True, posix=False)
182 list_all=True, posix=False)
183 namespace = self.shell.user_ns
183 namespace = self.shell.user_ns
184 if cell is not None:
184 if cell is not None:
185 arg_str += '\n' + cell
185 arg_str += '\n' + cell
186 else: # called to run a program by %run -p
186 else: # called to run a program by %run -p
187 try:
187 try:
188 filename = get_py_filename(arg_lst[0])
188 filename = get_py_filename(arg_lst[0])
189 except IOError as e:
189 except IOError as e:
190 try:
190 try:
191 msg = str(e)
191 msg = str(e)
192 except UnicodeError:
192 except UnicodeError:
193 msg = e.message
193 msg = e.message
194 error(msg)
194 error(msg)
195 return
195 return
196
196
197 arg_str = 'execfile(filename,prog_ns)'
197 arg_str = 'execfile(filename,prog_ns)'
198 namespace = {
198 namespace = {
199 'execfile': self.shell.safe_execfile,
199 'execfile': self.shell.safe_execfile,
200 'prog_ns': prog_ns,
200 'prog_ns': prog_ns,
201 'filename': filename
201 'filename': filename
202 }
202 }
203
203
204 opts.merge(opts_def)
204 opts.merge(opts_def)
205
205
206 prof = profile.Profile()
206 prof = profile.Profile()
207 try:
207 try:
208 prof = prof.runctx(arg_str,namespace,namespace)
208 prof = prof.runctx(arg_str,namespace,namespace)
209 sys_exit = ''
209 sys_exit = ''
210 except SystemExit:
210 except SystemExit:
211 sys_exit = """*** SystemExit exception caught in code being profiled."""
211 sys_exit = """*** SystemExit exception caught in code being profiled."""
212
212
213 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
213 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
214
214
215 lims = opts.l
215 lims = opts.l
216 if lims:
216 if lims:
217 lims = [] # rebuild lims with ints/floats/strings
217 lims = [] # rebuild lims with ints/floats/strings
218 for lim in opts.l:
218 for lim in opts.l:
219 try:
219 try:
220 lims.append(int(lim))
220 lims.append(int(lim))
221 except ValueError:
221 except ValueError:
222 try:
222 try:
223 lims.append(float(lim))
223 lims.append(float(lim))
224 except ValueError:
224 except ValueError:
225 lims.append(lim)
225 lims.append(lim)
226
226
227 # Trap output.
227 # Trap output.
228 stdout_trap = StringIO()
228 stdout_trap = StringIO()
229
229
230 if hasattr(stats,'stream'):
230 if hasattr(stats,'stream'):
231 # In newer versions of python, the stats object has a 'stream'
231 # In newer versions of python, the stats object has a 'stream'
232 # attribute to write into.
232 # attribute to write into.
233 stats.stream = stdout_trap
233 stats.stream = stdout_trap
234 stats.print_stats(*lims)
234 stats.print_stats(*lims)
235 else:
235 else:
236 # For older versions, we manually redirect stdout during printing
236 # For older versions, we manually redirect stdout during printing
237 sys_stdout = sys.stdout
237 sys_stdout = sys.stdout
238 try:
238 try:
239 sys.stdout = stdout_trap
239 sys.stdout = stdout_trap
240 stats.print_stats(*lims)
240 stats.print_stats(*lims)
241 finally:
241 finally:
242 sys.stdout = sys_stdout
242 sys.stdout = sys_stdout
243
243
244 output = stdout_trap.getvalue()
244 output = stdout_trap.getvalue()
245 output = output.rstrip()
245 output = output.rstrip()
246
246
247 if 'q' not in opts:
247 if 'q' not in opts:
248 page.page(output)
248 page.page(output)
249 print sys_exit,
249 print sys_exit,
250
250
251 dump_file = opts.D[0]
251 dump_file = opts.D[0]
252 text_file = opts.T[0]
252 text_file = opts.T[0]
253 if dump_file:
253 if dump_file:
254 dump_file = unquote_filename(dump_file)
254 dump_file = unquote_filename(dump_file)
255 prof.dump_stats(dump_file)
255 prof.dump_stats(dump_file)
256 print '\n*** Profile stats marshalled to file',\
256 print '\n*** Profile stats marshalled to file',\
257 `dump_file`+'.',sys_exit
257 repr(dump_file)+'.',sys_exit
258 if text_file:
258 if text_file:
259 text_file = unquote_filename(text_file)
259 text_file = unquote_filename(text_file)
260 pfile = open(text_file,'w')
260 pfile = open(text_file,'w')
261 pfile.write(output)
261 pfile.write(output)
262 pfile.close()
262 pfile.close()
263 print '\n*** Profile printout saved to text file',\
263 print '\n*** Profile printout saved to text file',\
264 `text_file`+'.',sys_exit
264 repr(text_file)+'.',sys_exit
265
265
266 if opts.has_key('r'):
266 if opts.has_key('r'):
267 return stats
267 return stats
268 else:
268 else:
269 return None
269 return None
270
270
271 @line_magic
271 @line_magic
272 def pdb(self, parameter_s=''):
272 def pdb(self, parameter_s=''):
273 """Control the automatic calling of the pdb interactive debugger.
273 """Control the automatic calling of the pdb interactive debugger.
274
274
275 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
275 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
276 argument it works as a toggle.
276 argument it works as a toggle.
277
277
278 When an exception is triggered, IPython can optionally call the
278 When an exception is triggered, IPython can optionally call the
279 interactive pdb debugger after the traceback printout. %pdb toggles
279 interactive pdb debugger after the traceback printout. %pdb toggles
280 this feature on and off.
280 this feature on and off.
281
281
282 The initial state of this feature is set in your configuration
282 The initial state of this feature is set in your configuration
283 file (the option is ``InteractiveShell.pdb``).
283 file (the option is ``InteractiveShell.pdb``).
284
284
285 If you want to just activate the debugger AFTER an exception has fired,
285 If you want to just activate the debugger AFTER an exception has fired,
286 without having to type '%pdb on' and rerunning your code, you can use
286 without having to type '%pdb on' and rerunning your code, you can use
287 the %debug magic."""
287 the %debug magic."""
288
288
289 par = parameter_s.strip().lower()
289 par = parameter_s.strip().lower()
290
290
291 if par:
291 if par:
292 try:
292 try:
293 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
293 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
294 except KeyError:
294 except KeyError:
295 print ('Incorrect argument. Use on/1, off/0, '
295 print ('Incorrect argument. Use on/1, off/0, '
296 'or nothing for a toggle.')
296 'or nothing for a toggle.')
297 return
297 return
298 else:
298 else:
299 # toggle
299 # toggle
300 new_pdb = not self.shell.call_pdb
300 new_pdb = not self.shell.call_pdb
301
301
302 # set on the shell
302 # set on the shell
303 self.shell.call_pdb = new_pdb
303 self.shell.call_pdb = new_pdb
304 print 'Automatic pdb calling has been turned',on_off(new_pdb)
304 print 'Automatic pdb calling has been turned',on_off(new_pdb)
305
305
306 @line_magic
306 @line_magic
307 def debug(self, parameter_s=''):
307 def debug(self, parameter_s=''):
308 """Activate the interactive debugger in post-mortem mode.
308 """Activate the interactive debugger in post-mortem mode.
309
309
310 If an exception has just occurred, this lets you inspect its stack
310 If an exception has just occurred, this lets you inspect its stack
311 frames interactively. Note that this will always work only on the last
311 frames interactively. Note that this will always work only on the last
312 traceback that occurred, so you must call this quickly after an
312 traceback that occurred, so you must call this quickly after an
313 exception that you wish to inspect has fired, because if another one
313 exception that you wish to inspect has fired, because if another one
314 occurs, it clobbers the previous one.
314 occurs, it clobbers the previous one.
315
315
316 If you want IPython to automatically do this on every exception, see
316 If you want IPython to automatically do this on every exception, see
317 the %pdb magic for more details.
317 the %pdb magic for more details.
318 """
318 """
319 self.shell.debugger(force=True)
319 self.shell.debugger(force=True)
320
320
321 @line_magic
321 @line_magic
322 def tb(self, s):
322 def tb(self, s):
323 """Print the last traceback with the currently active exception mode.
323 """Print the last traceback with the currently active exception mode.
324
324
325 See %xmode for changing exception reporting modes."""
325 See %xmode for changing exception reporting modes."""
326 self.shell.showtraceback()
326 self.shell.showtraceback()
327
327
328 @skip_doctest
328 @skip_doctest
329 @line_magic
329 @line_magic
330 def run(self, parameter_s='', runner=None,
330 def run(self, parameter_s='', runner=None,
331 file_finder=get_py_filename):
331 file_finder=get_py_filename):
332 """Run the named file inside IPython as a program.
332 """Run the named file inside IPython as a program.
333
333
334 Usage:\\
334 Usage:\\
335 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
335 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
336
336
337 Parameters after the filename are passed as command-line arguments to
337 Parameters after the filename are passed as command-line arguments to
338 the program (put in sys.argv). Then, control returns to IPython's
338 the program (put in sys.argv). Then, control returns to IPython's
339 prompt.
339 prompt.
340
340
341 This is similar to running at a system prompt:\\
341 This is similar to running at a system prompt:\\
342 $ python file args\\
342 $ python file args\\
343 but with the advantage of giving you IPython's tracebacks, and of
343 but with the advantage of giving you IPython's tracebacks, and of
344 loading all variables into your interactive namespace for further use
344 loading all variables into your interactive namespace for further use
345 (unless -p is used, see below).
345 (unless -p is used, see below).
346
346
347 The file is executed in a namespace initially consisting only of
347 The file is executed in a namespace initially consisting only of
348 __name__=='__main__' and sys.argv constructed as indicated. It thus
348 __name__=='__main__' and sys.argv constructed as indicated. It thus
349 sees its environment as if it were being run as a stand-alone program
349 sees its environment as if it were being run as a stand-alone program
350 (except for sharing global objects such as previously imported
350 (except for sharing global objects such as previously imported
351 modules). But after execution, the IPython interactive namespace gets
351 modules). But after execution, the IPython interactive namespace gets
352 updated with all variables defined in the program (except for __name__
352 updated with all variables defined in the program (except for __name__
353 and sys.argv). This allows for very convenient loading of code for
353 and sys.argv). This allows for very convenient loading of code for
354 interactive work, while giving each program a 'clean sheet' to run in.
354 interactive work, while giving each program a 'clean sheet' to run in.
355
355
356 Options:
356 Options:
357
357
358 -n: __name__ is NOT set to '__main__', but to the running file's name
358 -n: __name__ is NOT set to '__main__', but to the running file's name
359 without extension (as python does under import). This allows running
359 without extension (as python does under import). This allows running
360 scripts and reloading the definitions in them without calling code
360 scripts and reloading the definitions in them without calling code
361 protected by an ' if __name__ == "__main__" ' clause.
361 protected by an ' if __name__ == "__main__" ' clause.
362
362
363 -i: run the file in IPython's namespace instead of an empty one. This
363 -i: run the file in IPython's namespace instead of an empty one. This
364 is useful if you are experimenting with code written in a text editor
364 is useful if you are experimenting with code written in a text editor
365 which depends on variables defined interactively.
365 which depends on variables defined interactively.
366
366
367 -e: ignore sys.exit() calls or SystemExit exceptions in the script
367 -e: ignore sys.exit() calls or SystemExit exceptions in the script
368 being run. This is particularly useful if IPython is being used to
368 being run. This is particularly useful if IPython is being used to
369 run unittests, which always exit with a sys.exit() call. In such
369 run unittests, which always exit with a sys.exit() call. In such
370 cases you are interested in the output of the test results, not in
370 cases you are interested in the output of the test results, not in
371 seeing a traceback of the unittest module.
371 seeing a traceback of the unittest module.
372
372
373 -t: print timing information at the end of the run. IPython will give
373 -t: print timing information at the end of the run. IPython will give
374 you an estimated CPU time consumption for your script, which under
374 you an estimated CPU time consumption for your script, which under
375 Unix uses the resource module to avoid the wraparound problems of
375 Unix uses the resource module to avoid the wraparound problems of
376 time.clock(). Under Unix, an estimate of time spent on system tasks
376 time.clock(). Under Unix, an estimate of time spent on system tasks
377 is also given (for Windows platforms this is reported as 0.0).
377 is also given (for Windows platforms this is reported as 0.0).
378
378
379 If -t is given, an additional -N<N> option can be given, where <N>
379 If -t is given, an additional -N<N> option can be given, where <N>
380 must be an integer indicating how many times you want the script to
380 must be an integer indicating how many times you want the script to
381 run. The final timing report will include total and per run results.
381 run. The final timing report will include total and per run results.
382
382
383 For example (testing the script uniq_stable.py)::
383 For example (testing the script uniq_stable.py)::
384
384
385 In [1]: run -t uniq_stable
385 In [1]: run -t uniq_stable
386
386
387 IPython CPU timings (estimated):\\
387 IPython CPU timings (estimated):\\
388 User : 0.19597 s.\\
388 User : 0.19597 s.\\
389 System: 0.0 s.\\
389 System: 0.0 s.\\
390
390
391 In [2]: run -t -N5 uniq_stable
391 In [2]: run -t -N5 uniq_stable
392
392
393 IPython CPU timings (estimated):\\
393 IPython CPU timings (estimated):\\
394 Total runs performed: 5\\
394 Total runs performed: 5\\
395 Times : Total Per run\\
395 Times : Total Per run\\
396 User : 0.910862 s, 0.1821724 s.\\
396 User : 0.910862 s, 0.1821724 s.\\
397 System: 0.0 s, 0.0 s.
397 System: 0.0 s, 0.0 s.
398
398
399 -d: run your program under the control of pdb, the Python debugger.
399 -d: run your program under the control of pdb, the Python debugger.
400 This allows you to execute your program step by step, watch variables,
400 This allows you to execute your program step by step, watch variables,
401 etc. Internally, what IPython does is similar to calling:
401 etc. Internally, what IPython does is similar to calling:
402
402
403 pdb.run('execfile("YOURFILENAME")')
403 pdb.run('execfile("YOURFILENAME")')
404
404
405 with a breakpoint set on line 1 of your file. You can change the line
405 with a breakpoint set on line 1 of your file. You can change the line
406 number for this automatic breakpoint to be <N> by using the -bN option
406 number for this automatic breakpoint to be <N> by using the -bN option
407 (where N must be an integer). For example::
407 (where N must be an integer). For example::
408
408
409 %run -d -b40 myscript
409 %run -d -b40 myscript
410
410
411 will set the first breakpoint at line 40 in myscript.py. Note that
411 will set the first breakpoint at line 40 in myscript.py. Note that
412 the first breakpoint must be set on a line which actually does
412 the first breakpoint must be set on a line which actually does
413 something (not a comment or docstring) for it to stop execution.
413 something (not a comment or docstring) for it to stop execution.
414
414
415 When the pdb debugger starts, you will see a (Pdb) prompt. You must
415 When the pdb debugger starts, you will see a (Pdb) prompt. You must
416 first enter 'c' (without quotes) to start execution up to the first
416 first enter 'c' (without quotes) to start execution up to the first
417 breakpoint.
417 breakpoint.
418
418
419 Entering 'help' gives information about the use of the debugger. You
419 Entering 'help' gives information about the use of the debugger. You
420 can easily see pdb's full documentation with "import pdb;pdb.help()"
420 can easily see pdb's full documentation with "import pdb;pdb.help()"
421 at a prompt.
421 at a prompt.
422
422
423 -p: run program under the control of the Python profiler module (which
423 -p: run program under the control of the Python profiler module (which
424 prints a detailed report of execution times, function calls, etc).
424 prints a detailed report of execution times, function calls, etc).
425
425
426 You can pass other options after -p which affect the behavior of the
426 You can pass other options after -p which affect the behavior of the
427 profiler itself. See the docs for %prun for details.
427 profiler itself. See the docs for %prun for details.
428
428
429 In this mode, the program's variables do NOT propagate back to the
429 In this mode, the program's variables do NOT propagate back to the
430 IPython interactive namespace (because they remain in the namespace
430 IPython interactive namespace (because they remain in the namespace
431 where the profiler executes them).
431 where the profiler executes them).
432
432
433 Internally this triggers a call to %prun, see its documentation for
433 Internally this triggers a call to %prun, see its documentation for
434 details on the options available specifically for profiling.
434 details on the options available specifically for profiling.
435
435
436 There is one special usage for which the text above doesn't apply:
436 There is one special usage for which the text above doesn't apply:
437 if the filename ends with .ipy, the file is run as ipython script,
437 if the filename ends with .ipy, the file is run as ipython script,
438 just as if the commands were written on IPython prompt.
438 just as if the commands were written on IPython prompt.
439
439
440 -m: specify module name to load instead of script path. Similar to
440 -m: specify module name to load instead of script path. Similar to
441 the -m option for the python interpreter. Use this option last if you
441 the -m option for the python interpreter. Use this option last if you
442 want to combine with other %run options. Unlike the python interpreter
442 want to combine with other %run options. Unlike the python interpreter
443 only source modules are allowed no .pyc or .pyo files.
443 only source modules are allowed no .pyc or .pyo files.
444 For example::
444 For example::
445
445
446 %run -m example
446 %run -m example
447
447
448 will run the example module.
448 will run the example module.
449
449
450 """
450 """
451
451
452 # get arguments and set sys.argv for program to be run.
452 # get arguments and set sys.argv for program to be run.
453 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
453 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
454 mode='list', list_all=1)
454 mode='list', list_all=1)
455 if "m" in opts:
455 if "m" in opts:
456 modulename = opts["m"][0]
456 modulename = opts["m"][0]
457 modpath = find_mod(modulename)
457 modpath = find_mod(modulename)
458 if modpath is None:
458 if modpath is None:
459 warn('%r is not a valid modulename on sys.path'%modulename)
459 warn('%r is not a valid modulename on sys.path'%modulename)
460 return
460 return
461 arg_lst = [modpath] + arg_lst
461 arg_lst = [modpath] + arg_lst
462 try:
462 try:
463 filename = file_finder(arg_lst[0])
463 filename = file_finder(arg_lst[0])
464 except IndexError:
464 except IndexError:
465 warn('you must provide at least a filename.')
465 warn('you must provide at least a filename.')
466 print '\n%run:\n', oinspect.getdoc(self.run)
466 print '\n%run:\n', oinspect.getdoc(self.run)
467 return
467 return
468 except IOError as e:
468 except IOError as e:
469 try:
469 try:
470 msg = str(e)
470 msg = str(e)
471 except UnicodeError:
471 except UnicodeError:
472 msg = e.message
472 msg = e.message
473 error(msg)
473 error(msg)
474 return
474 return
475
475
476 if filename.lower().endswith('.ipy'):
476 if filename.lower().endswith('.ipy'):
477 self.shell.safe_execfile_ipy(filename)
477 self.shell.safe_execfile_ipy(filename)
478 return
478 return
479
479
480 # Control the response to exit() calls made by the script being run
480 # Control the response to exit() calls made by the script being run
481 exit_ignore = 'e' in opts
481 exit_ignore = 'e' in opts
482
482
483 # Make sure that the running script gets a proper sys.argv as if it
483 # Make sure that the running script gets a proper sys.argv as if it
484 # were run from a system shell.
484 # were run from a system shell.
485 save_argv = sys.argv # save it for later restoring
485 save_argv = sys.argv # save it for later restoring
486
486
487 # simulate shell expansion on arguments, at least tilde expansion
487 # simulate shell expansion on arguments, at least tilde expansion
488 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
488 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
489
489
490 sys.argv = [filename] + args # put in the proper filename
490 sys.argv = [filename] + args # put in the proper filename
491 # protect sys.argv from potential unicode strings on Python 2:
491 # protect sys.argv from potential unicode strings on Python 2:
492 if not py3compat.PY3:
492 if not py3compat.PY3:
493 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
493 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
494
494
495 if 'i' in opts:
495 if 'i' in opts:
496 # Run in user's interactive namespace
496 # Run in user's interactive namespace
497 prog_ns = self.shell.user_ns
497 prog_ns = self.shell.user_ns
498 __name__save = self.shell.user_ns['__name__']
498 __name__save = self.shell.user_ns['__name__']
499 prog_ns['__name__'] = '__main__'
499 prog_ns['__name__'] = '__main__'
500 main_mod = self.shell.new_main_mod(prog_ns)
500 main_mod = self.shell.new_main_mod(prog_ns)
501 else:
501 else:
502 # Run in a fresh, empty namespace
502 # Run in a fresh, empty namespace
503 if 'n' in opts:
503 if 'n' in opts:
504 name = os.path.splitext(os.path.basename(filename))[0]
504 name = os.path.splitext(os.path.basename(filename))[0]
505 else:
505 else:
506 name = '__main__'
506 name = '__main__'
507
507
508 main_mod = self.shell.new_main_mod()
508 main_mod = self.shell.new_main_mod()
509 prog_ns = main_mod.__dict__
509 prog_ns = main_mod.__dict__
510 prog_ns['__name__'] = name
510 prog_ns['__name__'] = name
511
511
512 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
512 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
513 # set the __file__ global in the script's namespace
513 # set the __file__ global in the script's namespace
514 prog_ns['__file__'] = filename
514 prog_ns['__file__'] = filename
515
515
516 # pickle fix. See interactiveshell for an explanation. But we need to
516 # pickle fix. See interactiveshell for an explanation. But we need to
517 # make sure that, if we overwrite __main__, we replace it at the end
517 # make sure that, if we overwrite __main__, we replace it at the end
518 main_mod_name = prog_ns['__name__']
518 main_mod_name = prog_ns['__name__']
519
519
520 if main_mod_name == '__main__':
520 if main_mod_name == '__main__':
521 restore_main = sys.modules['__main__']
521 restore_main = sys.modules['__main__']
522 else:
522 else:
523 restore_main = False
523 restore_main = False
524
524
525 # This needs to be undone at the end to prevent holding references to
525 # This needs to be undone at the end to prevent holding references to
526 # every single object ever created.
526 # every single object ever created.
527 sys.modules[main_mod_name] = main_mod
527 sys.modules[main_mod_name] = main_mod
528
528
529 try:
529 try:
530 stats = None
530 stats = None
531 with self.shell.readline_no_record:
531 with self.shell.readline_no_record:
532 if 'p' in opts:
532 if 'p' in opts:
533 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
533 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
534 else:
534 else:
535 if 'd' in opts:
535 if 'd' in opts:
536 deb = debugger.Pdb(self.shell.colors)
536 deb = debugger.Pdb(self.shell.colors)
537 # reset Breakpoint state, which is moronically kept
537 # reset Breakpoint state, which is moronically kept
538 # in a class
538 # in a class
539 bdb.Breakpoint.next = 1
539 bdb.Breakpoint.next = 1
540 bdb.Breakpoint.bplist = {}
540 bdb.Breakpoint.bplist = {}
541 bdb.Breakpoint.bpbynumber = [None]
541 bdb.Breakpoint.bpbynumber = [None]
542 # Set an initial breakpoint to stop execution
542 # Set an initial breakpoint to stop execution
543 maxtries = 10
543 maxtries = 10
544 bp = int(opts.get('b', [1])[0])
544 bp = int(opts.get('b', [1])[0])
545 checkline = deb.checkline(filename, bp)
545 checkline = deb.checkline(filename, bp)
546 if not checkline:
546 if not checkline:
547 for bp in range(bp + 1, bp + maxtries + 1):
547 for bp in range(bp + 1, bp + maxtries + 1):
548 if deb.checkline(filename, bp):
548 if deb.checkline(filename, bp):
549 break
549 break
550 else:
550 else:
551 msg = ("\nI failed to find a valid line to set "
551 msg = ("\nI failed to find a valid line to set "
552 "a breakpoint\n"
552 "a breakpoint\n"
553 "after trying up to line: %s.\n"
553 "after trying up to line: %s.\n"
554 "Please set a valid breakpoint manually "
554 "Please set a valid breakpoint manually "
555 "with the -b option." % bp)
555 "with the -b option." % bp)
556 error(msg)
556 error(msg)
557 return
557 return
558 # if we find a good linenumber, set the breakpoint
558 # if we find a good linenumber, set the breakpoint
559 deb.do_break('%s:%s' % (filename, bp))
559 deb.do_break('%s:%s' % (filename, bp))
560 # Start file run
560 # Start file run
561 print "NOTE: Enter 'c' at the",
561 print "NOTE: Enter 'c' at the",
562 print "%s prompt to start your script." % deb.prompt
562 print "%s prompt to start your script." % deb.prompt
563 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
563 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
564 try:
564 try:
565 deb.run('execfile("%s", prog_ns)' % filename, ns)
565 deb.run('execfile("%s", prog_ns)' % filename, ns)
566
566
567 except:
567 except:
568 etype, value, tb = sys.exc_info()
568 etype, value, tb = sys.exc_info()
569 # Skip three frames in the traceback: the %run one,
569 # Skip three frames in the traceback: the %run one,
570 # one inside bdb.py, and the command-line typed by the
570 # one inside bdb.py, and the command-line typed by the
571 # user (run by exec in pdb itself).
571 # user (run by exec in pdb itself).
572 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
572 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
573 else:
573 else:
574 if runner is None:
574 if runner is None:
575 runner = self.default_runner
575 runner = self.default_runner
576 if runner is None:
576 if runner is None:
577 runner = self.shell.safe_execfile
577 runner = self.shell.safe_execfile
578 if 't' in opts:
578 if 't' in opts:
579 # timed execution
579 # timed execution
580 try:
580 try:
581 nruns = int(opts['N'][0])
581 nruns = int(opts['N'][0])
582 if nruns < 1:
582 if nruns < 1:
583 error('Number of runs must be >=1')
583 error('Number of runs must be >=1')
584 return
584 return
585 except (KeyError):
585 except (KeyError):
586 nruns = 1
586 nruns = 1
587 twall0 = time.time()
587 twall0 = time.time()
588 if nruns == 1:
588 if nruns == 1:
589 t0 = clock2()
589 t0 = clock2()
590 runner(filename, prog_ns, prog_ns,
590 runner(filename, prog_ns, prog_ns,
591 exit_ignore=exit_ignore)
591 exit_ignore=exit_ignore)
592 t1 = clock2()
592 t1 = clock2()
593 t_usr = t1[0] - t0[0]
593 t_usr = t1[0] - t0[0]
594 t_sys = t1[1] - t0[1]
594 t_sys = t1[1] - t0[1]
595 print "\nIPython CPU timings (estimated):"
595 print "\nIPython CPU timings (estimated):"
596 print " User : %10.2f s." % t_usr
596 print " User : %10.2f s." % t_usr
597 print " System : %10.2f s." % t_sys
597 print " System : %10.2f s." % t_sys
598 else:
598 else:
599 runs = range(nruns)
599 runs = range(nruns)
600 t0 = clock2()
600 t0 = clock2()
601 for nr in runs:
601 for nr in runs:
602 runner(filename, prog_ns, prog_ns,
602 runner(filename, prog_ns, prog_ns,
603 exit_ignore=exit_ignore)
603 exit_ignore=exit_ignore)
604 t1 = clock2()
604 t1 = clock2()
605 t_usr = t1[0] - t0[0]
605 t_usr = t1[0] - t0[0]
606 t_sys = t1[1] - t0[1]
606 t_sys = t1[1] - t0[1]
607 print "\nIPython CPU timings (estimated):"
607 print "\nIPython CPU timings (estimated):"
608 print "Total runs performed:", nruns
608 print "Total runs performed:", nruns
609 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
609 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
610 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
610 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
611 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
611 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
612 twall1 = time.time()
612 twall1 = time.time()
613 print "Wall time: %10.2f s." % (twall1 - twall0)
613 print "Wall time: %10.2f s." % (twall1 - twall0)
614
614
615 else:
615 else:
616 # regular execution
616 # regular execution
617 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
617 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
618
618
619 if 'i' in opts:
619 if 'i' in opts:
620 self.shell.user_ns['__name__'] = __name__save
620 self.shell.user_ns['__name__'] = __name__save
621 else:
621 else:
622 # The shell MUST hold a reference to prog_ns so after %run
622 # The shell MUST hold a reference to prog_ns so after %run
623 # exits, the python deletion mechanism doesn't zero it out
623 # exits, the python deletion mechanism doesn't zero it out
624 # (leaving dangling references).
624 # (leaving dangling references).
625 self.shell.cache_main_mod(prog_ns, filename)
625 self.shell.cache_main_mod(prog_ns, filename)
626 # update IPython interactive namespace
626 # update IPython interactive namespace
627
627
628 # Some forms of read errors on the file may mean the
628 # Some forms of read errors on the file may mean the
629 # __name__ key was never set; using pop we don't have to
629 # __name__ key was never set; using pop we don't have to
630 # worry about a possible KeyError.
630 # worry about a possible KeyError.
631 prog_ns.pop('__name__', None)
631 prog_ns.pop('__name__', None)
632
632
633 self.shell.user_ns.update(prog_ns)
633 self.shell.user_ns.update(prog_ns)
634 finally:
634 finally:
635 # It's a bit of a mystery why, but __builtins__ can change from
635 # It's a bit of a mystery why, but __builtins__ can change from
636 # being a module to becoming a dict missing some key data after
636 # being a module to becoming a dict missing some key data after
637 # %run. As best I can see, this is NOT something IPython is doing
637 # %run. As best I can see, this is NOT something IPython is doing
638 # at all, and similar problems have been reported before:
638 # at all, and similar problems have been reported before:
639 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
639 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
640 # Since this seems to be done by the interpreter itself, the best
640 # Since this seems to be done by the interpreter itself, the best
641 # we can do is to at least restore __builtins__ for the user on
641 # we can do is to at least restore __builtins__ for the user on
642 # exit.
642 # exit.
643 self.shell.user_ns['__builtins__'] = builtin_mod
643 self.shell.user_ns['__builtins__'] = builtin_mod
644
644
645 # Ensure key global structures are restored
645 # Ensure key global structures are restored
646 sys.argv = save_argv
646 sys.argv = save_argv
647 if restore_main:
647 if restore_main:
648 sys.modules['__main__'] = restore_main
648 sys.modules['__main__'] = restore_main
649 else:
649 else:
650 # Remove from sys.modules the reference to main_mod we'd
650 # Remove from sys.modules the reference to main_mod we'd
651 # added. Otherwise it will trap references to objects
651 # added. Otherwise it will trap references to objects
652 # contained therein.
652 # contained therein.
653 del sys.modules[main_mod_name]
653 del sys.modules[main_mod_name]
654
654
655 return stats
655 return stats
656
656
657 @skip_doctest
657 @skip_doctest
658 @line_cell_magic
658 @line_cell_magic
659 def timeit(self, line='', cell=None):
659 def timeit(self, line='', cell=None):
660 """Time execution of a Python statement or expression
660 """Time execution of a Python statement or expression
661
661
662 Usage, in line mode:
662 Usage, in line mode:
663 %timeit [-n<N> -r<R> [-t|-c]] statement
663 %timeit [-n<N> -r<R> [-t|-c]] statement
664 or in cell mode:
664 or in cell mode:
665 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
665 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
666 code
666 code
667 code...
667 code...
668
668
669 Time execution of a Python statement or expression using the timeit
669 Time execution of a Python statement or expression using the timeit
670 module. This function can be used both as a line and cell magic:
670 module. This function can be used both as a line and cell magic:
671
671
672 - In line mode you can time a single-line statement (though multiple
672 - In line mode you can time a single-line statement (though multiple
673 ones can be chained with using semicolons).
673 ones can be chained with using semicolons).
674
674
675 - In cell mode, the statement in the first line is used as setup code
675 - In cell mode, the statement in the first line is used as setup code
676 (executed but not timed) and the body of the cell is timed. The cell
676 (executed but not timed) and the body of the cell is timed. The cell
677 body has access to any variables created in the setup code.
677 body has access to any variables created in the setup code.
678
678
679 Options:
679 Options:
680 -n<N>: execute the given statement <N> times in a loop. If this value
680 -n<N>: execute the given statement <N> times in a loop. If this value
681 is not given, a fitting value is chosen.
681 is not given, a fitting value is chosen.
682
682
683 -r<R>: repeat the loop iteration <R> times and take the best result.
683 -r<R>: repeat the loop iteration <R> times and take the best result.
684 Default: 3
684 Default: 3
685
685
686 -t: use time.time to measure the time, which is the default on Unix.
686 -t: use time.time to measure the time, which is the default on Unix.
687 This function measures wall time.
687 This function measures wall time.
688
688
689 -c: use time.clock to measure the time, which is the default on
689 -c: use time.clock to measure the time, which is the default on
690 Windows and measures wall time. On Unix, resource.getrusage is used
690 Windows and measures wall time. On Unix, resource.getrusage is used
691 instead and returns the CPU user time.
691 instead and returns the CPU user time.
692
692
693 -p<P>: use a precision of <P> digits to display the timing result.
693 -p<P>: use a precision of <P> digits to display the timing result.
694 Default: 3
694 Default: 3
695
695
696
696
697 Examples
697 Examples
698 --------
698 --------
699 ::
699 ::
700
700
701 In [1]: %timeit pass
701 In [1]: %timeit pass
702 10000000 loops, best of 3: 53.3 ns per loop
702 10000000 loops, best of 3: 53.3 ns per loop
703
703
704 In [2]: u = None
704 In [2]: u = None
705
705
706 In [3]: %timeit u is None
706 In [3]: %timeit u is None
707 10000000 loops, best of 3: 184 ns per loop
707 10000000 loops, best of 3: 184 ns per loop
708
708
709 In [4]: %timeit -r 4 u == None
709 In [4]: %timeit -r 4 u == None
710 1000000 loops, best of 4: 242 ns per loop
710 1000000 loops, best of 4: 242 ns per loop
711
711
712 In [5]: import time
712 In [5]: import time
713
713
714 In [6]: %timeit -n1 time.sleep(2)
714 In [6]: %timeit -n1 time.sleep(2)
715 1 loops, best of 3: 2 s per loop
715 1 loops, best of 3: 2 s per loop
716
716
717
717
718 The times reported by %timeit will be slightly higher than those
718 The times reported by %timeit will be slightly higher than those
719 reported by the timeit.py script when variables are accessed. This is
719 reported by the timeit.py script when variables are accessed. This is
720 due to the fact that %timeit executes the statement in the namespace
720 due to the fact that %timeit executes the statement in the namespace
721 of the shell, compared with timeit.py, which uses a single setup
721 of the shell, compared with timeit.py, which uses a single setup
722 statement to import function or create variables. Generally, the bias
722 statement to import function or create variables. Generally, the bias
723 does not matter as long as results from timeit.py are not mixed with
723 does not matter as long as results from timeit.py are not mixed with
724 those from %timeit."""
724 those from %timeit."""
725
725
726 import timeit
726 import timeit
727 import math
727 import math
728
728
729 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
729 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
730 # certain terminals. Until we figure out a robust way of
730 # certain terminals. Until we figure out a robust way of
731 # auto-detecting if the terminal can deal with it, use plain 'us' for
731 # auto-detecting if the terminal can deal with it, use plain 'us' for
732 # microseconds. I am really NOT happy about disabling the proper
732 # microseconds. I am really NOT happy about disabling the proper
733 # 'micro' prefix, but crashing is worse... If anyone knows what the
733 # 'micro' prefix, but crashing is worse... If anyone knows what the
734 # right solution for this is, I'm all ears...
734 # right solution for this is, I'm all ears...
735 #
735 #
736 # Note: using
736 # Note: using
737 #
737 #
738 # s = u'\xb5'
738 # s = u'\xb5'
739 # s.encode(sys.getdefaultencoding())
739 # s.encode(sys.getdefaultencoding())
740 #
740 #
741 # is not sufficient, as I've seen terminals where that fails but
741 # is not sufficient, as I've seen terminals where that fails but
742 # print s
742 # print s
743 #
743 #
744 # succeeds
744 # succeeds
745 #
745 #
746 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
746 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
747
747
748 #units = [u"s", u"ms",u'\xb5',"ns"]
748 #units = [u"s", u"ms",u'\xb5',"ns"]
749 units = [u"s", u"ms",u'us',"ns"]
749 units = [u"s", u"ms",u'us',"ns"]
750
750
751 scaling = [1, 1e3, 1e6, 1e9]
751 scaling = [1, 1e3, 1e6, 1e9]
752
752
753 opts, stmt = self.parse_options(line,'n:r:tcp:',
753 opts, stmt = self.parse_options(line,'n:r:tcp:',
754 posix=False, strict=False)
754 posix=False, strict=False)
755 if stmt == "" and cell is None:
755 if stmt == "" and cell is None:
756 return
756 return
757 timefunc = timeit.default_timer
757 timefunc = timeit.default_timer
758 number = int(getattr(opts, "n", 0))
758 number = int(getattr(opts, "n", 0))
759 repeat = int(getattr(opts, "r", timeit.default_repeat))
759 repeat = int(getattr(opts, "r", timeit.default_repeat))
760 precision = int(getattr(opts, "p", 3))
760 precision = int(getattr(opts, "p", 3))
761 if hasattr(opts, "t"):
761 if hasattr(opts, "t"):
762 timefunc = time.time
762 timefunc = time.time
763 if hasattr(opts, "c"):
763 if hasattr(opts, "c"):
764 timefunc = clock
764 timefunc = clock
765
765
766 timer = timeit.Timer(timer=timefunc)
766 timer = timeit.Timer(timer=timefunc)
767 # this code has tight coupling to the inner workings of timeit.Timer,
767 # this code has tight coupling to the inner workings of timeit.Timer,
768 # but is there a better way to achieve that the code stmt has access
768 # but is there a better way to achieve that the code stmt has access
769 # to the shell namespace?
769 # to the shell namespace?
770 transform = self.shell.input_splitter.transform_cell
770 transform = self.shell.input_splitter.transform_cell
771 if cell is None:
771 if cell is None:
772 # called as line magic
772 # called as line magic
773 setup = 'pass'
773 setup = 'pass'
774 stmt = timeit.reindent(transform(stmt), 8)
774 stmt = timeit.reindent(transform(stmt), 8)
775 else:
775 else:
776 setup = timeit.reindent(transform(stmt), 4)
776 setup = timeit.reindent(transform(stmt), 4)
777 stmt = timeit.reindent(transform(cell), 8)
777 stmt = timeit.reindent(transform(cell), 8)
778
778
779 # From Python 3.3, this template uses new-style string formatting.
779 # From Python 3.3, this template uses new-style string formatting.
780 if sys.version_info >= (3, 3):
780 if sys.version_info >= (3, 3):
781 src = timeit.template.format(stmt=stmt, setup=setup)
781 src = timeit.template.format(stmt=stmt, setup=setup)
782 else:
782 else:
783 src = timeit.template % dict(stmt=stmt, setup=setup)
783 src = timeit.template % dict(stmt=stmt, setup=setup)
784
784
785 # Track compilation time so it can be reported if too long
785 # Track compilation time so it can be reported if too long
786 # Minimum time above which compilation time will be reported
786 # Minimum time above which compilation time will be reported
787 tc_min = 0.1
787 tc_min = 0.1
788
788
789 t0 = clock()
789 t0 = clock()
790 code = compile(src, "<magic-timeit>", "exec")
790 code = compile(src, "<magic-timeit>", "exec")
791 tc = clock()-t0
791 tc = clock()-t0
792
792
793 ns = {}
793 ns = {}
794 exec code in self.shell.user_ns, ns
794 exec code in self.shell.user_ns, ns
795 timer.inner = ns["inner"]
795 timer.inner = ns["inner"]
796
796
797 if number == 0:
797 if number == 0:
798 # determine number so that 0.2 <= total time < 2.0
798 # determine number so that 0.2 <= total time < 2.0
799 number = 1
799 number = 1
800 for i in range(1, 10):
800 for i in range(1, 10):
801 if timer.timeit(number) >= 0.2:
801 if timer.timeit(number) >= 0.2:
802 break
802 break
803 number *= 10
803 number *= 10
804
804
805 best = min(timer.repeat(repeat, number)) / number
805 best = min(timer.repeat(repeat, number)) / number
806
806
807 if best > 0.0 and best < 1000.0:
807 if best > 0.0 and best < 1000.0:
808 order = min(-int(math.floor(math.log10(best)) // 3), 3)
808 order = min(-int(math.floor(math.log10(best)) // 3), 3)
809 elif best >= 1000.0:
809 elif best >= 1000.0:
810 order = 0
810 order = 0
811 else:
811 else:
812 order = 3
812 order = 3
813 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
813 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
814 precision,
814 precision,
815 best * scaling[order],
815 best * scaling[order],
816 units[order])
816 units[order])
817 if tc > tc_min:
817 if tc > tc_min:
818 print "Compiler time: %.2f s" % tc
818 print "Compiler time: %.2f s" % tc
819
819
820 @skip_doctest
820 @skip_doctest
821 @needs_local_scope
821 @needs_local_scope
822 @line_magic
822 @line_magic
823 def time(self,parameter_s, user_locals):
823 def time(self,parameter_s, user_locals):
824 """Time execution of a Python statement or expression.
824 """Time execution of a Python statement or expression.
825
825
826 The CPU and wall clock times are printed, and the value of the
826 The CPU and wall clock times are printed, and the value of the
827 expression (if any) is returned. Note that under Win32, system time
827 expression (if any) is returned. Note that under Win32, system time
828 is always reported as 0, since it can not be measured.
828 is always reported as 0, since it can not be measured.
829
829
830 This function provides very basic timing functionality. In Python
830 This function provides very basic timing functionality. In Python
831 2.3, the timeit module offers more control and sophistication, so this
831 2.3, the timeit module offers more control and sophistication, so this
832 could be rewritten to use it (patches welcome).
832 could be rewritten to use it (patches welcome).
833
833
834 Examples
834 Examples
835 --------
835 --------
836 ::
836 ::
837
837
838 In [1]: time 2**128
838 In [1]: time 2**128
839 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
839 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
840 Wall time: 0.00
840 Wall time: 0.00
841 Out[1]: 340282366920938463463374607431768211456L
841 Out[1]: 340282366920938463463374607431768211456L
842
842
843 In [2]: n = 1000000
843 In [2]: n = 1000000
844
844
845 In [3]: time sum(range(n))
845 In [3]: time sum(range(n))
846 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
846 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
847 Wall time: 1.37
847 Wall time: 1.37
848 Out[3]: 499999500000L
848 Out[3]: 499999500000L
849
849
850 In [4]: time print 'hello world'
850 In [4]: time print 'hello world'
851 hello world
851 hello world
852 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
852 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
853 Wall time: 0.00
853 Wall time: 0.00
854
854
855 Note that the time needed by Python to compile the given expression
855 Note that the time needed by Python to compile the given expression
856 will be reported if it is more than 0.1s. In this example, the
856 will be reported if it is more than 0.1s. In this example, the
857 actual exponentiation is done by Python at compilation time, so while
857 actual exponentiation is done by Python at compilation time, so while
858 the expression can take a noticeable amount of time to compute, that
858 the expression can take a noticeable amount of time to compute, that
859 time is purely due to the compilation:
859 time is purely due to the compilation:
860
860
861 In [5]: time 3**9999;
861 In [5]: time 3**9999;
862 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
862 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
863 Wall time: 0.00 s
863 Wall time: 0.00 s
864
864
865 In [6]: time 3**999999;
865 In [6]: time 3**999999;
866 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
866 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
867 Wall time: 0.00 s
867 Wall time: 0.00 s
868 Compiler : 0.78 s
868 Compiler : 0.78 s
869 """
869 """
870
870
871 # fail immediately if the given expression can't be compiled
871 # fail immediately if the given expression can't be compiled
872
872
873 expr = self.shell.prefilter(parameter_s,False)
873 expr = self.shell.prefilter(parameter_s,False)
874
874
875 # Minimum time above which compilation time will be reported
875 # Minimum time above which compilation time will be reported
876 tc_min = 0.1
876 tc_min = 0.1
877
877
878 try:
878 try:
879 mode = 'eval'
879 mode = 'eval'
880 t0 = clock()
880 t0 = clock()
881 code = compile(expr,'<timed eval>',mode)
881 code = compile(expr,'<timed eval>',mode)
882 tc = clock()-t0
882 tc = clock()-t0
883 except SyntaxError:
883 except SyntaxError:
884 mode = 'exec'
884 mode = 'exec'
885 t0 = clock()
885 t0 = clock()
886 code = compile(expr,'<timed exec>',mode)
886 code = compile(expr,'<timed exec>',mode)
887 tc = clock()-t0
887 tc = clock()-t0
888 # skew measurement as little as possible
888 # skew measurement as little as possible
889 glob = self.shell.user_ns
889 glob = self.shell.user_ns
890 wtime = time.time
890 wtime = time.time
891 # time execution
891 # time execution
892 wall_st = wtime()
892 wall_st = wtime()
893 if mode=='eval':
893 if mode=='eval':
894 st = clock2()
894 st = clock2()
895 out = eval(code, glob, user_locals)
895 out = eval(code, glob, user_locals)
896 end = clock2()
896 end = clock2()
897 else:
897 else:
898 st = clock2()
898 st = clock2()
899 exec code in glob, user_locals
899 exec code in glob, user_locals
900 end = clock2()
900 end = clock2()
901 out = None
901 out = None
902 wall_end = wtime()
902 wall_end = wtime()
903 # Compute actual times and report
903 # Compute actual times and report
904 wall_time = wall_end-wall_st
904 wall_time = wall_end-wall_st
905 cpu_user = end[0]-st[0]
905 cpu_user = end[0]-st[0]
906 cpu_sys = end[1]-st[1]
906 cpu_sys = end[1]-st[1]
907 cpu_tot = cpu_user+cpu_sys
907 cpu_tot = cpu_user+cpu_sys
908 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
908 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
909 (cpu_user,cpu_sys,cpu_tot)
909 (cpu_user,cpu_sys,cpu_tot)
910 print "Wall time: %.2f s" % wall_time
910 print "Wall time: %.2f s" % wall_time
911 if tc > tc_min:
911 if tc > tc_min:
912 print "Compiler : %.2f s" % tc
912 print "Compiler : %.2f s" % tc
913 return out
913 return out
914
914
915 @skip_doctest
915 @skip_doctest
916 @line_magic
916 @line_magic
917 def macro(self, parameter_s=''):
917 def macro(self, parameter_s=''):
918 """Define a macro for future re-execution. It accepts ranges of history,
918 """Define a macro for future re-execution. It accepts ranges of history,
919 filenames or string objects.
919 filenames or string objects.
920
920
921 Usage:\\
921 Usage:\\
922 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
922 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
923
923
924 Options:
924 Options:
925
925
926 -r: use 'raw' input. By default, the 'processed' history is used,
926 -r: use 'raw' input. By default, the 'processed' history is used,
927 so that magics are loaded in their transformed version to valid
927 so that magics are loaded in their transformed version to valid
928 Python. If this option is given, the raw input as typed as the
928 Python. If this option is given, the raw input as typed as the
929 command line is used instead.
929 command line is used instead.
930
930
931 This will define a global variable called `name` which is a string
931 This will define a global variable called `name` which is a string
932 made of joining the slices and lines you specify (n1,n2,... numbers
932 made of joining the slices and lines you specify (n1,n2,... numbers
933 above) from your input history into a single string. This variable
933 above) from your input history into a single string. This variable
934 acts like an automatic function which re-executes those lines as if
934 acts like an automatic function which re-executes those lines as if
935 you had typed them. You just type 'name' at the prompt and the code
935 you had typed them. You just type 'name' at the prompt and the code
936 executes.
936 executes.
937
937
938 The syntax for indicating input ranges is described in %history.
938 The syntax for indicating input ranges is described in %history.
939
939
940 Note: as a 'hidden' feature, you can also use traditional python slice
940 Note: as a 'hidden' feature, you can also use traditional python slice
941 notation, where N:M means numbers N through M-1.
941 notation, where N:M means numbers N through M-1.
942
942
943 For example, if your history contains (%hist prints it)::
943 For example, if your history contains (%hist prints it)::
944
944
945 44: x=1
945 44: x=1
946 45: y=3
946 45: y=3
947 46: z=x+y
947 46: z=x+y
948 47: print x
948 47: print x
949 48: a=5
949 48: a=5
950 49: print 'x',x,'y',y
950 49: print 'x',x,'y',y
951
951
952 you can create a macro with lines 44 through 47 (included) and line 49
952 you can create a macro with lines 44 through 47 (included) and line 49
953 called my_macro with::
953 called my_macro with::
954
954
955 In [55]: %macro my_macro 44-47 49
955 In [55]: %macro my_macro 44-47 49
956
956
957 Now, typing `my_macro` (without quotes) will re-execute all this code
957 Now, typing `my_macro` (without quotes) will re-execute all this code
958 in one pass.
958 in one pass.
959
959
960 You don't need to give the line-numbers in order, and any given line
960 You don't need to give the line-numbers in order, and any given line
961 number can appear multiple times. You can assemble macros with any
961 number can appear multiple times. You can assemble macros with any
962 lines from your input history in any order.
962 lines from your input history in any order.
963
963
964 The macro is a simple object which holds its value in an attribute,
964 The macro is a simple object which holds its value in an attribute,
965 but IPython's display system checks for macros and executes them as
965 but IPython's display system checks for macros and executes them as
966 code instead of printing them when you type their name.
966 code instead of printing them when you type their name.
967
967
968 You can view a macro's contents by explicitly printing it with::
968 You can view a macro's contents by explicitly printing it with::
969
969
970 print macro_name
970 print macro_name
971
971
972 """
972 """
973 opts,args = self.parse_options(parameter_s,'r',mode='list')
973 opts,args = self.parse_options(parameter_s,'r',mode='list')
974 if not args: # List existing macros
974 if not args: # List existing macros
975 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
975 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
976 isinstance(v, Macro))
976 isinstance(v, Macro))
977 if len(args) == 1:
977 if len(args) == 1:
978 raise UsageError(
978 raise UsageError(
979 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
979 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
980 name, codefrom = args[0], " ".join(args[1:])
980 name, codefrom = args[0], " ".join(args[1:])
981
981
982 #print 'rng',ranges # dbg
982 #print 'rng',ranges # dbg
983 try:
983 try:
984 lines = self.shell.find_user_code(codefrom, 'r' in opts)
984 lines = self.shell.find_user_code(codefrom, 'r' in opts)
985 except (ValueError, TypeError) as e:
985 except (ValueError, TypeError) as e:
986 print e.args[0]
986 print e.args[0]
987 return
987 return
988 macro = Macro(lines)
988 macro = Macro(lines)
989 self.shell.define_macro(name, macro)
989 self.shell.define_macro(name, macro)
990 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
990 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
991 print '=== Macro contents: ==='
991 print '=== Macro contents: ==='
992 print macro,
992 print macro,
993
993
994 @magic_arguments.magic_arguments()
994 @magic_arguments.magic_arguments()
995 @magic_arguments.argument('output', type=str, default='', nargs='?',
995 @magic_arguments.argument('output', type=str, default='', nargs='?',
996 help="""The name of the variable in which to store output.
996 help="""The name of the variable in which to store output.
997 This is a utils.io.CapturedIO object with stdout/err attributes
997 This is a utils.io.CapturedIO object with stdout/err attributes
998 for the text of the captured output.
998 for the text of the captured output.
999
999
1000 CapturedOutput also has a show() method for displaying the output,
1000 CapturedOutput also has a show() method for displaying the output,
1001 and __call__ as well, so you can use that to quickly display the
1001 and __call__ as well, so you can use that to quickly display the
1002 output.
1002 output.
1003
1003
1004 If unspecified, captured output is discarded.
1004 If unspecified, captured output is discarded.
1005 """
1005 """
1006 )
1006 )
1007 @magic_arguments.argument('--no-stderr', action="store_true",
1007 @magic_arguments.argument('--no-stderr', action="store_true",
1008 help="""Don't capture stderr."""
1008 help="""Don't capture stderr."""
1009 )
1009 )
1010 @magic_arguments.argument('--no-stdout', action="store_true",
1010 @magic_arguments.argument('--no-stdout', action="store_true",
1011 help="""Don't capture stdout."""
1011 help="""Don't capture stdout."""
1012 )
1012 )
1013 @cell_magic
1013 @cell_magic
1014 def capture(self, line, cell):
1014 def capture(self, line, cell):
1015 """run the cell, capturing stdout/err"""
1015 """run the cell, capturing stdout/err"""
1016 args = magic_arguments.parse_argstring(self.capture, line)
1016 args = magic_arguments.parse_argstring(self.capture, line)
1017 out = not args.no_stdout
1017 out = not args.no_stdout
1018 err = not args.no_stderr
1018 err = not args.no_stderr
1019 with capture_output(out, err) as io:
1019 with capture_output(out, err) as io:
1020 self.shell.run_cell(cell)
1020 self.shell.run_cell(cell)
1021 if args.output:
1021 if args.output:
1022 self.shell.user_ns[args.output] = io
1022 self.shell.user_ns[args.output] = io
@@ -1,841 +1,842 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16 from __future__ import print_function
16
17
17 __all__ = ['Inspector','InspectColors']
18 __all__ = ['Inspector','InspectColors']
18
19
19 # stdlib modules
20 # stdlib modules
20 import __builtin__
21 import __builtin__
21 import inspect
22 import inspect
22 import linecache
23 import linecache
23 import os
24 import os
24 import sys
25 import sys
25 import types
26 import types
26 from collections import namedtuple
27 from collections import namedtuple
27 try:
28 try:
28 from itertools import izip_longest
29 from itertools import izip_longest
29 except ImportError:
30 except ImportError:
30 from itertools import zip_longest as izip_longest
31 from itertools import zip_longest as izip_longest
31
32
32 # IPython's own
33 # IPython's own
33 from IPython.core import page
34 from IPython.core import page
34 from IPython.testing.skipdoctest import skip_doctest_py3
35 from IPython.testing.skipdoctest import skip_doctest_py3
35 from IPython.utils import PyColorize
36 from IPython.utils import PyColorize
36 from IPython.utils import io
37 from IPython.utils import io
37 from IPython.utils import py3compat
38 from IPython.utils import py3compat
38 from IPython.utils.text import indent
39 from IPython.utils.text import indent
39 from IPython.utils.wildcard import list_namespace
40 from IPython.utils.wildcard import list_namespace
40 from IPython.utils.coloransi import *
41 from IPython.utils.coloransi import *
41
42
42 #****************************************************************************
43 #****************************************************************************
43 # Builtin color schemes
44 # Builtin color schemes
44
45
45 Colors = TermColors # just a shorthand
46 Colors = TermColors # just a shorthand
46
47
47 # Build a few color schemes
48 # Build a few color schemes
48 NoColor = ColorScheme(
49 NoColor = ColorScheme(
49 'NoColor',{
50 'NoColor',{
50 'header' : Colors.NoColor,
51 'header' : Colors.NoColor,
51 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
52 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
52 } )
53 } )
53
54
54 LinuxColors = ColorScheme(
55 LinuxColors = ColorScheme(
55 'Linux',{
56 'Linux',{
56 'header' : Colors.LightRed,
57 'header' : Colors.LightRed,
57 'normal' : Colors.Normal # color off (usu. Colors.Normal)
58 'normal' : Colors.Normal # color off (usu. Colors.Normal)
58 } )
59 } )
59
60
60 LightBGColors = ColorScheme(
61 LightBGColors = ColorScheme(
61 'LightBG',{
62 'LightBG',{
62 'header' : Colors.Red,
63 'header' : Colors.Red,
63 'normal' : Colors.Normal # color off (usu. Colors.Normal)
64 'normal' : Colors.Normal # color off (usu. Colors.Normal)
64 } )
65 } )
65
66
66 # Build table of color schemes (needed by the parser)
67 # Build table of color schemes (needed by the parser)
67 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
68 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
68 'Linux')
69 'Linux')
69
70
70 #****************************************************************************
71 #****************************************************************************
71 # Auxiliary functions and objects
72 # Auxiliary functions and objects
72
73
73 # See the messaging spec for the definition of all these fields. This list
74 # See the messaging spec for the definition of all these fields. This list
74 # effectively defines the order of display
75 # effectively defines the order of display
75 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
76 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
76 'length', 'file', 'definition', 'docstring', 'source',
77 'length', 'file', 'definition', 'docstring', 'source',
77 'init_definition', 'class_docstring', 'init_docstring',
78 'init_definition', 'class_docstring', 'init_docstring',
78 'call_def', 'call_docstring',
79 'call_def', 'call_docstring',
79 # These won't be printed but will be used to determine how to
80 # These won't be printed but will be used to determine how to
80 # format the object
81 # format the object
81 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
82 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
82 ]
83 ]
83
84
84
85
85 def object_info(**kw):
86 def object_info(**kw):
86 """Make an object info dict with all fields present."""
87 """Make an object info dict with all fields present."""
87 infodict = dict(izip_longest(info_fields, [None]))
88 infodict = dict(izip_longest(info_fields, [None]))
88 infodict.update(kw)
89 infodict.update(kw)
89 return infodict
90 return infodict
90
91
91
92
92 def getdoc(obj):
93 def getdoc(obj):
93 """Stable wrapper around inspect.getdoc.
94 """Stable wrapper around inspect.getdoc.
94
95
95 This can't crash because of attribute problems.
96 This can't crash because of attribute problems.
96
97
97 It also attempts to call a getdoc() method on the given object. This
98 It also attempts to call a getdoc() method on the given object. This
98 allows objects which provide their docstrings via non-standard mechanisms
99 allows objects which provide their docstrings via non-standard mechanisms
99 (like Pyro proxies) to still be inspected by ipython's ? system."""
100 (like Pyro proxies) to still be inspected by ipython's ? system."""
100 # Allow objects to offer customized documentation via a getdoc method:
101 # Allow objects to offer customized documentation via a getdoc method:
101 try:
102 try:
102 ds = obj.getdoc()
103 ds = obj.getdoc()
103 except Exception:
104 except Exception:
104 pass
105 pass
105 else:
106 else:
106 # if we get extra info, we add it to the normal docstring.
107 # if we get extra info, we add it to the normal docstring.
107 if isinstance(ds, basestring):
108 if isinstance(ds, basestring):
108 return inspect.cleandoc(ds)
109 return inspect.cleandoc(ds)
109
110
110 try:
111 try:
111 return inspect.getdoc(obj)
112 return inspect.getdoc(obj)
112 except Exception:
113 except Exception:
113 # Harden against an inspect failure, which can occur with
114 # Harden against an inspect failure, which can occur with
114 # SWIG-wrapped extensions.
115 # SWIG-wrapped extensions.
115 return None
116 return None
116
117
117
118
118 def getsource(obj,is_binary=False):
119 def getsource(obj,is_binary=False):
119 """Wrapper around inspect.getsource.
120 """Wrapper around inspect.getsource.
120
121
121 This can be modified by other projects to provide customized source
122 This can be modified by other projects to provide customized source
122 extraction.
123 extraction.
123
124
124 Inputs:
125 Inputs:
125
126
126 - obj: an object whose source code we will attempt to extract.
127 - obj: an object whose source code we will attempt to extract.
127
128
128 Optional inputs:
129 Optional inputs:
129
130
130 - is_binary: whether the object is known to come from a binary source.
131 - is_binary: whether the object is known to come from a binary source.
131 This implementation will skip returning any output for binary objects, but
132 This implementation will skip returning any output for binary objects, but
132 custom extractors may know how to meaningfully process them."""
133 custom extractors may know how to meaningfully process them."""
133
134
134 if is_binary:
135 if is_binary:
135 return None
136 return None
136 else:
137 else:
137 # get source if obj was decorated with @decorator
138 # get source if obj was decorated with @decorator
138 if hasattr(obj,"__wrapped__"):
139 if hasattr(obj,"__wrapped__"):
139 obj = obj.__wrapped__
140 obj = obj.__wrapped__
140 try:
141 try:
141 src = inspect.getsource(obj)
142 src = inspect.getsource(obj)
142 except TypeError:
143 except TypeError:
143 if hasattr(obj,'__class__'):
144 if hasattr(obj,'__class__'):
144 src = inspect.getsource(obj.__class__)
145 src = inspect.getsource(obj.__class__)
145 return src
146 return src
146
147
147 def getargspec(obj):
148 def getargspec(obj):
148 """Get the names and default values of a function's arguments.
149 """Get the names and default values of a function's arguments.
149
150
150 A tuple of four things is returned: (args, varargs, varkw, defaults).
151 A tuple of four things is returned: (args, varargs, varkw, defaults).
151 'args' is a list of the argument names (it may contain nested lists).
152 'args' is a list of the argument names (it may contain nested lists).
152 'varargs' and 'varkw' are the names of the * and ** arguments or None.
153 'varargs' and 'varkw' are the names of the * and ** arguments or None.
153 'defaults' is an n-tuple of the default values of the last n arguments.
154 'defaults' is an n-tuple of the default values of the last n arguments.
154
155
155 Modified version of inspect.getargspec from the Python Standard
156 Modified version of inspect.getargspec from the Python Standard
156 Library."""
157 Library."""
157
158
158 if inspect.isfunction(obj):
159 if inspect.isfunction(obj):
159 func_obj = obj
160 func_obj = obj
160 elif inspect.ismethod(obj):
161 elif inspect.ismethod(obj):
161 func_obj = obj.im_func
162 func_obj = obj.im_func
162 elif hasattr(obj, '__call__'):
163 elif hasattr(obj, '__call__'):
163 func_obj = obj.__call__
164 func_obj = obj.__call__
164 else:
165 else:
165 raise TypeError('arg is not a Python function')
166 raise TypeError('arg is not a Python function')
166 args, varargs, varkw = inspect.getargs(func_obj.func_code)
167 args, varargs, varkw = inspect.getargs(func_obj.func_code)
167 return args, varargs, varkw, func_obj.func_defaults
168 return args, varargs, varkw, func_obj.func_defaults
168
169
169
170
170 def format_argspec(argspec):
171 def format_argspec(argspec):
171 """Format argspect, convenience wrapper around inspect's.
172 """Format argspect, convenience wrapper around inspect's.
172
173
173 This takes a dict instead of ordered arguments and calls
174 This takes a dict instead of ordered arguments and calls
174 inspect.format_argspec with the arguments in the necessary order.
175 inspect.format_argspec with the arguments in the necessary order.
175 """
176 """
176 return inspect.formatargspec(argspec['args'], argspec['varargs'],
177 return inspect.formatargspec(argspec['args'], argspec['varargs'],
177 argspec['varkw'], argspec['defaults'])
178 argspec['varkw'], argspec['defaults'])
178
179
179
180
180 def call_tip(oinfo, format_call=True):
181 def call_tip(oinfo, format_call=True):
181 """Extract call tip data from an oinfo dict.
182 """Extract call tip data from an oinfo dict.
182
183
183 Parameters
184 Parameters
184 ----------
185 ----------
185 oinfo : dict
186 oinfo : dict
186
187
187 format_call : bool, optional
188 format_call : bool, optional
188 If True, the call line is formatted and returned as a string. If not, a
189 If True, the call line is formatted and returned as a string. If not, a
189 tuple of (name, argspec) is returned.
190 tuple of (name, argspec) is returned.
190
191
191 Returns
192 Returns
192 -------
193 -------
193 call_info : None, str or (str, dict) tuple.
194 call_info : None, str or (str, dict) tuple.
194 When format_call is True, the whole call information is formattted as a
195 When format_call is True, the whole call information is formattted as a
195 single string. Otherwise, the object's name and its argspec dict are
196 single string. Otherwise, the object's name and its argspec dict are
196 returned. If no call information is available, None is returned.
197 returned. If no call information is available, None is returned.
197
198
198 docstring : str or None
199 docstring : str or None
199 The most relevant docstring for calling purposes is returned, if
200 The most relevant docstring for calling purposes is returned, if
200 available. The priority is: call docstring for callable instances, then
201 available. The priority is: call docstring for callable instances, then
201 constructor docstring for classes, then main object's docstring otherwise
202 constructor docstring for classes, then main object's docstring otherwise
202 (regular functions).
203 (regular functions).
203 """
204 """
204 # Get call definition
205 # Get call definition
205 argspec = oinfo.get('argspec')
206 argspec = oinfo.get('argspec')
206 if argspec is None:
207 if argspec is None:
207 call_line = None
208 call_line = None
208 else:
209 else:
209 # Callable objects will have 'self' as their first argument, prune
210 # Callable objects will have 'self' as their first argument, prune
210 # it out if it's there for clarity (since users do *not* pass an
211 # it out if it's there for clarity (since users do *not* pass an
211 # extra first argument explicitly).
212 # extra first argument explicitly).
212 try:
213 try:
213 has_self = argspec['args'][0] == 'self'
214 has_self = argspec['args'][0] == 'self'
214 except (KeyError, IndexError):
215 except (KeyError, IndexError):
215 pass
216 pass
216 else:
217 else:
217 if has_self:
218 if has_self:
218 argspec['args'] = argspec['args'][1:]
219 argspec['args'] = argspec['args'][1:]
219
220
220 call_line = oinfo['name']+format_argspec(argspec)
221 call_line = oinfo['name']+format_argspec(argspec)
221
222
222 # Now get docstring.
223 # Now get docstring.
223 # The priority is: call docstring, constructor docstring, main one.
224 # The priority is: call docstring, constructor docstring, main one.
224 doc = oinfo.get('call_docstring')
225 doc = oinfo.get('call_docstring')
225 if doc is None:
226 if doc is None:
226 doc = oinfo.get('init_docstring')
227 doc = oinfo.get('init_docstring')
227 if doc is None:
228 if doc is None:
228 doc = oinfo.get('docstring','')
229 doc = oinfo.get('docstring','')
229
230
230 return call_line, doc
231 return call_line, doc
231
232
232
233
233 def find_file(obj):
234 def find_file(obj):
234 """Find the absolute path to the file where an object was defined.
235 """Find the absolute path to the file where an object was defined.
235
236
236 This is essentially a robust wrapper around `inspect.getabsfile`.
237 This is essentially a robust wrapper around `inspect.getabsfile`.
237
238
238 Returns None if no file can be found.
239 Returns None if no file can be found.
239
240
240 Parameters
241 Parameters
241 ----------
242 ----------
242 obj : any Python object
243 obj : any Python object
243
244
244 Returns
245 Returns
245 -------
246 -------
246 fname : str
247 fname : str
247 The absolute path to the file where the object was defined.
248 The absolute path to the file where the object was defined.
248 """
249 """
249 # get source if obj was decorated with @decorator
250 # get source if obj was decorated with @decorator
250 if hasattr(obj, '__wrapped__'):
251 if hasattr(obj, '__wrapped__'):
251 obj = obj.__wrapped__
252 obj = obj.__wrapped__
252
253
253 fname = None
254 fname = None
254 try:
255 try:
255 fname = inspect.getabsfile(obj)
256 fname = inspect.getabsfile(obj)
256 except TypeError:
257 except TypeError:
257 # For an instance, the file that matters is where its class was
258 # For an instance, the file that matters is where its class was
258 # declared.
259 # declared.
259 if hasattr(obj, '__class__'):
260 if hasattr(obj, '__class__'):
260 try:
261 try:
261 fname = inspect.getabsfile(obj.__class__)
262 fname = inspect.getabsfile(obj.__class__)
262 except TypeError:
263 except TypeError:
263 # Can happen for builtins
264 # Can happen for builtins
264 pass
265 pass
265 except:
266 except:
266 pass
267 pass
267 return fname
268 return fname
268
269
269
270
270 def find_source_lines(obj):
271 def find_source_lines(obj):
271 """Find the line number in a file where an object was defined.
272 """Find the line number in a file where an object was defined.
272
273
273 This is essentially a robust wrapper around `inspect.getsourcelines`.
274 This is essentially a robust wrapper around `inspect.getsourcelines`.
274
275
275 Returns None if no file can be found.
276 Returns None if no file can be found.
276
277
277 Parameters
278 Parameters
278 ----------
279 ----------
279 obj : any Python object
280 obj : any Python object
280
281
281 Returns
282 Returns
282 -------
283 -------
283 lineno : int
284 lineno : int
284 The line number where the object definition starts.
285 The line number where the object definition starts.
285 """
286 """
286 # get source if obj was decorated with @decorator
287 # get source if obj was decorated with @decorator
287 if hasattr(obj, '__wrapped__'):
288 if hasattr(obj, '__wrapped__'):
288 obj = obj.__wrapped__
289 obj = obj.__wrapped__
289
290
290 try:
291 try:
291 try:
292 try:
292 lineno = inspect.getsourcelines(obj)[1]
293 lineno = inspect.getsourcelines(obj)[1]
293 except TypeError:
294 except TypeError:
294 # For instances, try the class object like getsource() does
295 # For instances, try the class object like getsource() does
295 if hasattr(obj, '__class__'):
296 if hasattr(obj, '__class__'):
296 lineno = inspect.getsourcelines(obj.__class__)[1]
297 lineno = inspect.getsourcelines(obj.__class__)[1]
297 except:
298 except:
298 return None
299 return None
299
300
300 return lineno
301 return lineno
301
302
302
303
303 class Inspector:
304 class Inspector:
304 def __init__(self, color_table=InspectColors,
305 def __init__(self, color_table=InspectColors,
305 code_color_table=PyColorize.ANSICodeColors,
306 code_color_table=PyColorize.ANSICodeColors,
306 scheme='NoColor',
307 scheme='NoColor',
307 str_detail_level=0):
308 str_detail_level=0):
308 self.color_table = color_table
309 self.color_table = color_table
309 self.parser = PyColorize.Parser(code_color_table,out='str')
310 self.parser = PyColorize.Parser(code_color_table,out='str')
310 self.format = self.parser.format
311 self.format = self.parser.format
311 self.str_detail_level = str_detail_level
312 self.str_detail_level = str_detail_level
312 self.set_active_scheme(scheme)
313 self.set_active_scheme(scheme)
313
314
314 def _getdef(self,obj,oname=''):
315 def _getdef(self,obj,oname=''):
315 """Return the definition header for any callable object.
316 """Return the definition header for any callable object.
316
317
317 If any exception is generated, None is returned instead and the
318 If any exception is generated, None is returned instead and the
318 exception is suppressed."""
319 exception is suppressed."""
319
320
320 try:
321 try:
321 # We need a plain string here, NOT unicode!
322 # We need a plain string here, NOT unicode!
322 hdef = oname + inspect.formatargspec(*getargspec(obj))
323 hdef = oname + inspect.formatargspec(*getargspec(obj))
323 return py3compat.unicode_to_str(hdef, 'ascii')
324 return py3compat.unicode_to_str(hdef, 'ascii')
324 except:
325 except:
325 return None
326 return None
326
327
327 def __head(self,h):
328 def __head(self,h):
328 """Return a header string with proper colors."""
329 """Return a header string with proper colors."""
329 return '%s%s%s' % (self.color_table.active_colors.header,h,
330 return '%s%s%s' % (self.color_table.active_colors.header,h,
330 self.color_table.active_colors.normal)
331 self.color_table.active_colors.normal)
331
332
332 def set_active_scheme(self, scheme):
333 def set_active_scheme(self, scheme):
333 self.color_table.set_active_scheme(scheme)
334 self.color_table.set_active_scheme(scheme)
334 self.parser.color_table.set_active_scheme(scheme)
335 self.parser.color_table.set_active_scheme(scheme)
335
336
336 def noinfo(self, msg, oname):
337 def noinfo(self, msg, oname):
337 """Generic message when no information is found."""
338 """Generic message when no information is found."""
338 print 'No %s found' % msg,
339 print('No %s found' % msg, end=' ')
339 if oname:
340 if oname:
340 print 'for %s' % oname
341 print('for %s' % oname)
341 else:
342 else:
342 print
343 print()
343
344
344 def pdef(self, obj, oname=''):
345 def pdef(self, obj, oname=''):
345 """Print the definition header for any callable object.
346 """Print the definition header for any callable object.
346
347
347 If the object is a class, print the constructor information."""
348 If the object is a class, print the constructor information."""
348
349
349 if not callable(obj):
350 if not callable(obj):
350 print 'Object is not callable.'
351 print('Object is not callable.')
351 return
352 return
352
353
353 header = ''
354 header = ''
354
355
355 if inspect.isclass(obj):
356 if inspect.isclass(obj):
356 header = self.__head('Class constructor information:\n')
357 header = self.__head('Class constructor information:\n')
357 obj = obj.__init__
358 obj = obj.__init__
358 elif (not py3compat.PY3) and type(obj) is types.InstanceType:
359 elif (not py3compat.PY3) and type(obj) is types.InstanceType:
359 obj = obj.__call__
360 obj = obj.__call__
360
361
361 output = self._getdef(obj,oname)
362 output = self._getdef(obj,oname)
362 if output is None:
363 if output is None:
363 self.noinfo('definition header',oname)
364 self.noinfo('definition header',oname)
364 else:
365 else:
365 print >>io.stdout, header,self.format(output),
366 print(header,self.format(output), end=' ', file=io.stdout)
366
367
367 # In Python 3, all classes are new-style, so they all have __init__.
368 # In Python 3, all classes are new-style, so they all have __init__.
368 @skip_doctest_py3
369 @skip_doctest_py3
369 def pdoc(self,obj,oname='',formatter = None):
370 def pdoc(self,obj,oname='',formatter = None):
370 """Print the docstring for any object.
371 """Print the docstring for any object.
371
372
372 Optional:
373 Optional:
373 -formatter: a function to run the docstring through for specially
374 -formatter: a function to run the docstring through for specially
374 formatted docstrings.
375 formatted docstrings.
375
376
376 Examples
377 Examples
377 --------
378 --------
378
379
379 In [1]: class NoInit:
380 In [1]: class NoInit:
380 ...: pass
381 ...: pass
381
382
382 In [2]: class NoDoc:
383 In [2]: class NoDoc:
383 ...: def __init__(self):
384 ...: def __init__(self):
384 ...: pass
385 ...: pass
385
386
386 In [3]: %pdoc NoDoc
387 In [3]: %pdoc NoDoc
387 No documentation found for NoDoc
388 No documentation found for NoDoc
388
389
389 In [4]: %pdoc NoInit
390 In [4]: %pdoc NoInit
390 No documentation found for NoInit
391 No documentation found for NoInit
391
392
392 In [5]: obj = NoInit()
393 In [5]: obj = NoInit()
393
394
394 In [6]: %pdoc obj
395 In [6]: %pdoc obj
395 No documentation found for obj
396 No documentation found for obj
396
397
397 In [5]: obj2 = NoDoc()
398 In [5]: obj2 = NoDoc()
398
399
399 In [6]: %pdoc obj2
400 In [6]: %pdoc obj2
400 No documentation found for obj2
401 No documentation found for obj2
401 """
402 """
402
403
403 head = self.__head # For convenience
404 head = self.__head # For convenience
404 lines = []
405 lines = []
405 ds = getdoc(obj)
406 ds = getdoc(obj)
406 if formatter:
407 if formatter:
407 ds = formatter(ds)
408 ds = formatter(ds)
408 if ds:
409 if ds:
409 lines.append(head("Class Docstring:"))
410 lines.append(head("Class Docstring:"))
410 lines.append(indent(ds))
411 lines.append(indent(ds))
411 if inspect.isclass(obj) and hasattr(obj, '__init__'):
412 if inspect.isclass(obj) and hasattr(obj, '__init__'):
412 init_ds = getdoc(obj.__init__)
413 init_ds = getdoc(obj.__init__)
413 if init_ds is not None:
414 if init_ds is not None:
414 lines.append(head("Constructor Docstring:"))
415 lines.append(head("Constructor Docstring:"))
415 lines.append(indent(init_ds))
416 lines.append(indent(init_ds))
416 elif hasattr(obj,'__call__'):
417 elif hasattr(obj,'__call__'):
417 call_ds = getdoc(obj.__call__)
418 call_ds = getdoc(obj.__call__)
418 if call_ds:
419 if call_ds:
419 lines.append(head("Calling Docstring:"))
420 lines.append(head("Calling Docstring:"))
420 lines.append(indent(call_ds))
421 lines.append(indent(call_ds))
421
422
422 if not lines:
423 if not lines:
423 self.noinfo('documentation',oname)
424 self.noinfo('documentation',oname)
424 else:
425 else:
425 page.page('\n'.join(lines))
426 page.page('\n'.join(lines))
426
427
427 def psource(self,obj,oname=''):
428 def psource(self,obj,oname=''):
428 """Print the source code for an object."""
429 """Print the source code for an object."""
429
430
430 # Flush the source cache because inspect can return out-of-date source
431 # Flush the source cache because inspect can return out-of-date source
431 linecache.checkcache()
432 linecache.checkcache()
432 try:
433 try:
433 src = getsource(obj)
434 src = getsource(obj)
434 except:
435 except:
435 self.noinfo('source',oname)
436 self.noinfo('source',oname)
436 else:
437 else:
437 page.page(self.format(py3compat.unicode_to_str(src)))
438 page.page(self.format(py3compat.unicode_to_str(src)))
438
439
439 def pfile(self, obj, oname=''):
440 def pfile(self, obj, oname=''):
440 """Show the whole file where an object was defined."""
441 """Show the whole file where an object was defined."""
441
442
442 lineno = find_source_lines(obj)
443 lineno = find_source_lines(obj)
443 if lineno is None:
444 if lineno is None:
444 self.noinfo('file', oname)
445 self.noinfo('file', oname)
445 return
446 return
446
447
447 ofile = find_file(obj)
448 ofile = find_file(obj)
448 # run contents of file through pager starting at line where the object
449 # run contents of file through pager starting at line where the object
449 # is defined, as long as the file isn't binary and is actually on the
450 # is defined, as long as the file isn't binary and is actually on the
450 # filesystem.
451 # filesystem.
451 if ofile.endswith(('.so', '.dll', '.pyd')):
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 elif not os.path.isfile(ofile):
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 else:
456 else:
456 # Print only text files, not extension binaries. Note that
457 # Print only text files, not extension binaries. Note that
457 # getsourcelines returns lineno with 1-offset and page() uses
458 # getsourcelines returns lineno with 1-offset and page() uses
458 # 0-offset, so we must adjust.
459 # 0-offset, so we must adjust.
459 page.page(self.format(open(ofile).read()), lineno-1)
460 page.page(self.format(open(ofile).read()), lineno-1)
460
461
461 def _format_fields(self, fields, title_width=12):
462 def _format_fields(self, fields, title_width=12):
462 """Formats a list of fields for display.
463 """Formats a list of fields for display.
463
464
464 Parameters
465 Parameters
465 ----------
466 ----------
466 fields : list
467 fields : list
467 A list of 2-tuples: (field_title, field_content)
468 A list of 2-tuples: (field_title, field_content)
468 title_width : int
469 title_width : int
469 How many characters to pad titles to. Default 12.
470 How many characters to pad titles to. Default 12.
470 """
471 """
471 out = []
472 out = []
472 header = self.__head
473 header = self.__head
473 for title, content in fields:
474 for title, content in fields:
474 if len(content.splitlines()) > 1:
475 if len(content.splitlines()) > 1:
475 title = header(title + ":") + "\n"
476 title = header(title + ":") + "\n"
476 else:
477 else:
477 title = header((title+":").ljust(title_width))
478 title = header((title+":").ljust(title_width))
478 out.append(title + content)
479 out.append(title + content)
479 return "\n".join(out)
480 return "\n".join(out)
480
481
481 # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict)
482 # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict)
482 pinfo_fields1 = [("Type", "type_name"),
483 pinfo_fields1 = [("Type", "type_name"),
483 ]
484 ]
484
485
485 pinfo_fields2 = [("String Form", "string_form"),
486 pinfo_fields2 = [("String Form", "string_form"),
486 ]
487 ]
487
488
488 pinfo_fields3 = [("Length", "length"),
489 pinfo_fields3 = [("Length", "length"),
489 ("File", "file"),
490 ("File", "file"),
490 ("Definition", "definition"),
491 ("Definition", "definition"),
491 ]
492 ]
492
493
493 pinfo_fields_obj = [("Class Docstring", "class_docstring"),
494 pinfo_fields_obj = [("Class Docstring", "class_docstring"),
494 ("Constructor Docstring","init_docstring"),
495 ("Constructor Docstring","init_docstring"),
495 ("Call def", "call_def"),
496 ("Call def", "call_def"),
496 ("Call docstring", "call_docstring")]
497 ("Call docstring", "call_docstring")]
497
498
498 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
499 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
499 """Show detailed information about an object.
500 """Show detailed information about an object.
500
501
501 Optional arguments:
502 Optional arguments:
502
503
503 - oname: name of the variable pointing to the object.
504 - oname: name of the variable pointing to the object.
504
505
505 - formatter: special formatter for docstrings (see pdoc)
506 - formatter: special formatter for docstrings (see pdoc)
506
507
507 - info: a structure with some information fields which may have been
508 - info: a structure with some information fields which may have been
508 precomputed already.
509 precomputed already.
509
510
510 - detail_level: if set to 1, more information is given.
511 - detail_level: if set to 1, more information is given.
511 """
512 """
512 info = self.info(obj, oname=oname, formatter=formatter,
513 info = self.info(obj, oname=oname, formatter=formatter,
513 info=info, detail_level=detail_level)
514 info=info, detail_level=detail_level)
514 displayfields = []
515 displayfields = []
515 def add_fields(fields):
516 def add_fields(fields):
516 for title, key in fields:
517 for title, key in fields:
517 field = info[key]
518 field = info[key]
518 if field is not None:
519 if field is not None:
519 displayfields.append((title, field.rstrip()))
520 displayfields.append((title, field.rstrip()))
520
521
521 add_fields(self.pinfo_fields1)
522 add_fields(self.pinfo_fields1)
522
523
523 # Base class for old-style instances
524 # Base class for old-style instances
524 if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
525 if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
525 displayfields.append(("Base Class", info['base_class'].rstrip()))
526 displayfields.append(("Base Class", info['base_class'].rstrip()))
526
527
527 add_fields(self.pinfo_fields2)
528 add_fields(self.pinfo_fields2)
528
529
529 # Namespace
530 # Namespace
530 if info['namespace'] != 'Interactive':
531 if info['namespace'] != 'Interactive':
531 displayfields.append(("Namespace", info['namespace'].rstrip()))
532 displayfields.append(("Namespace", info['namespace'].rstrip()))
532
533
533 add_fields(self.pinfo_fields3)
534 add_fields(self.pinfo_fields3)
534
535
535 # Source or docstring, depending on detail level and whether
536 # Source or docstring, depending on detail level and whether
536 # source found.
537 # source found.
537 if detail_level > 0 and info['source'] is not None:
538 if detail_level > 0 and info['source'] is not None:
538 displayfields.append(("Source", self.format(py3compat.cast_bytes_py2(info['source']))))
539 displayfields.append(("Source", self.format(py3compat.cast_bytes_py2(info['source']))))
539 elif info['docstring'] is not None:
540 elif info['docstring'] is not None:
540 displayfields.append(("Docstring", info["docstring"]))
541 displayfields.append(("Docstring", info["docstring"]))
541
542
542 # Constructor info for classes
543 # Constructor info for classes
543 if info['isclass']:
544 if info['isclass']:
544 if info['init_definition'] or info['init_docstring']:
545 if info['init_definition'] or info['init_docstring']:
545 displayfields.append(("Constructor information", ""))
546 displayfields.append(("Constructor information", ""))
546 if info['init_definition'] is not None:
547 if info['init_definition'] is not None:
547 displayfields.append((" Definition",
548 displayfields.append((" Definition",
548 info['init_definition'].rstrip()))
549 info['init_definition'].rstrip()))
549 if info['init_docstring'] is not None:
550 if info['init_docstring'] is not None:
550 displayfields.append((" Docstring",
551 displayfields.append((" Docstring",
551 indent(info['init_docstring'])))
552 indent(info['init_docstring'])))
552
553
553 # Info for objects:
554 # Info for objects:
554 else:
555 else:
555 add_fields(self.pinfo_fields_obj)
556 add_fields(self.pinfo_fields_obj)
556
557
557 # Finally send to printer/pager:
558 # Finally send to printer/pager:
558 if displayfields:
559 if displayfields:
559 page.page(self._format_fields(displayfields))
560 page.page(self._format_fields(displayfields))
560
561
561 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
562 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
562 """Compute a dict with detailed information about an object.
563 """Compute a dict with detailed information about an object.
563
564
564 Optional arguments:
565 Optional arguments:
565
566
566 - oname: name of the variable pointing to the object.
567 - oname: name of the variable pointing to the object.
567
568
568 - formatter: special formatter for docstrings (see pdoc)
569 - formatter: special formatter for docstrings (see pdoc)
569
570
570 - info: a structure with some information fields which may have been
571 - info: a structure with some information fields which may have been
571 precomputed already.
572 precomputed already.
572
573
573 - detail_level: if set to 1, more information is given.
574 - detail_level: if set to 1, more information is given.
574 """
575 """
575
576
576 obj_type = type(obj)
577 obj_type = type(obj)
577
578
578 header = self.__head
579 header = self.__head
579 if info is None:
580 if info is None:
580 ismagic = 0
581 ismagic = 0
581 isalias = 0
582 isalias = 0
582 ospace = ''
583 ospace = ''
583 else:
584 else:
584 ismagic = info.ismagic
585 ismagic = info.ismagic
585 isalias = info.isalias
586 isalias = info.isalias
586 ospace = info.namespace
587 ospace = info.namespace
587
588
588 # Get docstring, special-casing aliases:
589 # Get docstring, special-casing aliases:
589 if isalias:
590 if isalias:
590 if not callable(obj):
591 if not callable(obj):
591 try:
592 try:
592 ds = "Alias to the system command:\n %s" % obj[1]
593 ds = "Alias to the system command:\n %s" % obj[1]
593 except:
594 except:
594 ds = "Alias: " + str(obj)
595 ds = "Alias: " + str(obj)
595 else:
596 else:
596 ds = "Alias to " + str(obj)
597 ds = "Alias to " + str(obj)
597 if obj.__doc__:
598 if obj.__doc__:
598 ds += "\nDocstring:\n" + obj.__doc__
599 ds += "\nDocstring:\n" + obj.__doc__
599 else:
600 else:
600 ds = getdoc(obj)
601 ds = getdoc(obj)
601 if ds is None:
602 if ds is None:
602 ds = '<no docstring>'
603 ds = '<no docstring>'
603 if formatter is not None:
604 if formatter is not None:
604 ds = formatter(ds)
605 ds = formatter(ds)
605
606
606 # store output in a dict, we initialize it here and fill it as we go
607 # store output in a dict, we initialize it here and fill it as we go
607 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
608 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
608
609
609 string_max = 200 # max size of strings to show (snipped if longer)
610 string_max = 200 # max size of strings to show (snipped if longer)
610 shalf = int((string_max -5)/2)
611 shalf = int((string_max -5)/2)
611
612
612 if ismagic:
613 if ismagic:
613 obj_type_name = 'Magic function'
614 obj_type_name = 'Magic function'
614 elif isalias:
615 elif isalias:
615 obj_type_name = 'System alias'
616 obj_type_name = 'System alias'
616 else:
617 else:
617 obj_type_name = obj_type.__name__
618 obj_type_name = obj_type.__name__
618 out['type_name'] = obj_type_name
619 out['type_name'] = obj_type_name
619
620
620 try:
621 try:
621 bclass = obj.__class__
622 bclass = obj.__class__
622 out['base_class'] = str(bclass)
623 out['base_class'] = str(bclass)
623 except: pass
624 except: pass
624
625
625 # String form, but snip if too long in ? form (full in ??)
626 # String form, but snip if too long in ? form (full in ??)
626 if detail_level >= self.str_detail_level:
627 if detail_level >= self.str_detail_level:
627 try:
628 try:
628 ostr = str(obj)
629 ostr = str(obj)
629 str_head = 'string_form'
630 str_head = 'string_form'
630 if not detail_level and len(ostr)>string_max:
631 if not detail_level and len(ostr)>string_max:
631 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
632 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
632 ostr = ("\n" + " " * len(str_head.expandtabs())).\
633 ostr = ("\n" + " " * len(str_head.expandtabs())).\
633 join(q.strip() for q in ostr.split("\n"))
634 join(q.strip() for q in ostr.split("\n"))
634 out[str_head] = ostr
635 out[str_head] = ostr
635 except:
636 except:
636 pass
637 pass
637
638
638 if ospace:
639 if ospace:
639 out['namespace'] = ospace
640 out['namespace'] = ospace
640
641
641 # Length (for strings and lists)
642 # Length (for strings and lists)
642 try:
643 try:
643 out['length'] = str(len(obj))
644 out['length'] = str(len(obj))
644 except: pass
645 except: pass
645
646
646 # Filename where object was defined
647 # Filename where object was defined
647 binary_file = False
648 binary_file = False
648 fname = find_file(obj)
649 fname = find_file(obj)
649 if fname is None:
650 if fname is None:
650 # if anything goes wrong, we don't want to show source, so it's as
651 # if anything goes wrong, we don't want to show source, so it's as
651 # if the file was binary
652 # if the file was binary
652 binary_file = True
653 binary_file = True
653 else:
654 else:
654 if fname.endswith(('.so', '.dll', '.pyd')):
655 if fname.endswith(('.so', '.dll', '.pyd')):
655 binary_file = True
656 binary_file = True
656 elif fname.endswith('<string>'):
657 elif fname.endswith('<string>'):
657 fname = 'Dynamically generated function. No source code available.'
658 fname = 'Dynamically generated function. No source code available.'
658 out['file'] = fname
659 out['file'] = fname
659
660
660 # reconstruct the function definition and print it:
661 # reconstruct the function definition and print it:
661 defln = self._getdef(obj, oname)
662 defln = self._getdef(obj, oname)
662 if defln:
663 if defln:
663 out['definition'] = self.format(defln)
664 out['definition'] = self.format(defln)
664
665
665 # Docstrings only in detail 0 mode, since source contains them (we
666 # Docstrings only in detail 0 mode, since source contains them (we
666 # avoid repetitions). If source fails, we add them back, see below.
667 # avoid repetitions). If source fails, we add them back, see below.
667 if ds and detail_level == 0:
668 if ds and detail_level == 0:
668 out['docstring'] = ds
669 out['docstring'] = ds
669
670
670 # Original source code for any callable
671 # Original source code for any callable
671 if detail_level:
672 if detail_level:
672 # Flush the source cache because inspect can return out-of-date
673 # Flush the source cache because inspect can return out-of-date
673 # source
674 # source
674 linecache.checkcache()
675 linecache.checkcache()
675 source = None
676 source = None
676 try:
677 try:
677 try:
678 try:
678 source = getsource(obj, binary_file)
679 source = getsource(obj, binary_file)
679 except TypeError:
680 except TypeError:
680 if hasattr(obj, '__class__'):
681 if hasattr(obj, '__class__'):
681 source = getsource(obj.__class__, binary_file)
682 source = getsource(obj.__class__, binary_file)
682 if source is not None:
683 if source is not None:
683 out['source'] = source.rstrip()
684 out['source'] = source.rstrip()
684 except Exception:
685 except Exception:
685 pass
686 pass
686
687
687 if ds and source is None:
688 if ds and source is None:
688 out['docstring'] = ds
689 out['docstring'] = ds
689
690
690
691
691 # Constructor docstring for classes
692 # Constructor docstring for classes
692 if inspect.isclass(obj):
693 if inspect.isclass(obj):
693 out['isclass'] = True
694 out['isclass'] = True
694 # reconstruct the function definition and print it:
695 # reconstruct the function definition and print it:
695 try:
696 try:
696 obj_init = obj.__init__
697 obj_init = obj.__init__
697 except AttributeError:
698 except AttributeError:
698 init_def = init_ds = None
699 init_def = init_ds = None
699 else:
700 else:
700 init_def = self._getdef(obj_init,oname)
701 init_def = self._getdef(obj_init,oname)
701 init_ds = getdoc(obj_init)
702 init_ds = getdoc(obj_init)
702 # Skip Python's auto-generated docstrings
703 # Skip Python's auto-generated docstrings
703 if init_ds and \
704 if init_ds and \
704 init_ds.startswith('x.__init__(...) initializes'):
705 init_ds.startswith('x.__init__(...) initializes'):
705 init_ds = None
706 init_ds = None
706
707
707 if init_def or init_ds:
708 if init_def or init_ds:
708 if init_def:
709 if init_def:
709 out['init_definition'] = self.format(init_def)
710 out['init_definition'] = self.format(init_def)
710 if init_ds:
711 if init_ds:
711 out['init_docstring'] = init_ds
712 out['init_docstring'] = init_ds
712
713
713 # and class docstring for instances:
714 # and class docstring for instances:
714 else:
715 else:
715 # First, check whether the instance docstring is identical to the
716 # First, check whether the instance docstring is identical to the
716 # class one, and print it separately if they don't coincide. In
717 # class one, and print it separately if they don't coincide. In
717 # most cases they will, but it's nice to print all the info for
718 # most cases they will, but it's nice to print all the info for
718 # objects which use instance-customized docstrings.
719 # objects which use instance-customized docstrings.
719 if ds:
720 if ds:
720 try:
721 try:
721 cls = getattr(obj,'__class__')
722 cls = getattr(obj,'__class__')
722 except:
723 except:
723 class_ds = None
724 class_ds = None
724 else:
725 else:
725 class_ds = getdoc(cls)
726 class_ds = getdoc(cls)
726 # Skip Python's auto-generated docstrings
727 # Skip Python's auto-generated docstrings
727 if class_ds and \
728 if class_ds and \
728 (class_ds.startswith('function(code, globals[,') or \
729 (class_ds.startswith('function(code, globals[,') or \
729 class_ds.startswith('instancemethod(function, instance,') or \
730 class_ds.startswith('instancemethod(function, instance,') or \
730 class_ds.startswith('module(name[,') ):
731 class_ds.startswith('module(name[,') ):
731 class_ds = None
732 class_ds = None
732 if class_ds and ds != class_ds:
733 if class_ds and ds != class_ds:
733 out['class_docstring'] = class_ds
734 out['class_docstring'] = class_ds
734
735
735 # Next, try to show constructor docstrings
736 # Next, try to show constructor docstrings
736 try:
737 try:
737 init_ds = getdoc(obj.__init__)
738 init_ds = getdoc(obj.__init__)
738 # Skip Python's auto-generated docstrings
739 # Skip Python's auto-generated docstrings
739 if init_ds and \
740 if init_ds and \
740 init_ds.startswith('x.__init__(...) initializes'):
741 init_ds.startswith('x.__init__(...) initializes'):
741 init_ds = None
742 init_ds = None
742 except AttributeError:
743 except AttributeError:
743 init_ds = None
744 init_ds = None
744 if init_ds:
745 if init_ds:
745 out['init_docstring'] = init_ds
746 out['init_docstring'] = init_ds
746
747
747 # Call form docstring for callable instances
748 # Call form docstring for callable instances
748 if hasattr(obj, '__call__'):
749 if hasattr(obj, '__call__'):
749 call_def = self._getdef(obj.__call__, oname)
750 call_def = self._getdef(obj.__call__, oname)
750 if call_def is not None:
751 if call_def is not None:
751 out['call_def'] = self.format(call_def)
752 out['call_def'] = self.format(call_def)
752 call_ds = getdoc(obj.__call__)
753 call_ds = getdoc(obj.__call__)
753 # Skip Python's auto-generated docstrings
754 # Skip Python's auto-generated docstrings
754 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
755 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
755 call_ds = None
756 call_ds = None
756 if call_ds:
757 if call_ds:
757 out['call_docstring'] = call_ds
758 out['call_docstring'] = call_ds
758
759
759 # Compute the object's argspec as a callable. The key is to decide
760 # Compute the object's argspec as a callable. The key is to decide
760 # whether to pull it from the object itself, from its __init__ or
761 # whether to pull it from the object itself, from its __init__ or
761 # from its __call__ method.
762 # from its __call__ method.
762
763
763 if inspect.isclass(obj):
764 if inspect.isclass(obj):
764 # Old-style classes need not have an __init__
765 # Old-style classes need not have an __init__
765 callable_obj = getattr(obj, "__init__", None)
766 callable_obj = getattr(obj, "__init__", None)
766 elif callable(obj):
767 elif callable(obj):
767 callable_obj = obj
768 callable_obj = obj
768 else:
769 else:
769 callable_obj = None
770 callable_obj = None
770
771
771 if callable_obj:
772 if callable_obj:
772 try:
773 try:
773 args, varargs, varkw, defaults = getargspec(callable_obj)
774 args, varargs, varkw, defaults = getargspec(callable_obj)
774 except (TypeError, AttributeError):
775 except (TypeError, AttributeError):
775 # For extensions/builtins we can't retrieve the argspec
776 # For extensions/builtins we can't retrieve the argspec
776 pass
777 pass
777 else:
778 else:
778 out['argspec'] = dict(args=args, varargs=varargs,
779 out['argspec'] = dict(args=args, varargs=varargs,
779 varkw=varkw, defaults=defaults)
780 varkw=varkw, defaults=defaults)
780
781
781 return object_info(**out)
782 return object_info(**out)
782
783
783
784
784 def psearch(self,pattern,ns_table,ns_search=[],
785 def psearch(self,pattern,ns_table,ns_search=[],
785 ignore_case=False,show_all=False):
786 ignore_case=False,show_all=False):
786 """Search namespaces with wildcards for objects.
787 """Search namespaces with wildcards for objects.
787
788
788 Arguments:
789 Arguments:
789
790
790 - pattern: string containing shell-like wildcards to use in namespace
791 - pattern: string containing shell-like wildcards to use in namespace
791 searches and optionally a type specification to narrow the search to
792 searches and optionally a type specification to narrow the search to
792 objects of that type.
793 objects of that type.
793
794
794 - ns_table: dict of name->namespaces for search.
795 - ns_table: dict of name->namespaces for search.
795
796
796 Optional arguments:
797 Optional arguments:
797
798
798 - ns_search: list of namespace names to include in search.
799 - ns_search: list of namespace names to include in search.
799
800
800 - ignore_case(False): make the search case-insensitive.
801 - ignore_case(False): make the search case-insensitive.
801
802
802 - show_all(False): show all names, including those starting with
803 - show_all(False): show all names, including those starting with
803 underscores.
804 underscores.
804 """
805 """
805 #print 'ps pattern:<%r>' % pattern # dbg
806 #print 'ps pattern:<%r>' % pattern # dbg
806
807
807 # defaults
808 # defaults
808 type_pattern = 'all'
809 type_pattern = 'all'
809 filter = ''
810 filter = ''
810
811
811 cmds = pattern.split()
812 cmds = pattern.split()
812 len_cmds = len(cmds)
813 len_cmds = len(cmds)
813 if len_cmds == 1:
814 if len_cmds == 1:
814 # Only filter pattern given
815 # Only filter pattern given
815 filter = cmds[0]
816 filter = cmds[0]
816 elif len_cmds == 2:
817 elif len_cmds == 2:
817 # Both filter and type specified
818 # Both filter and type specified
818 filter,type_pattern = cmds
819 filter,type_pattern = cmds
819 else:
820 else:
820 raise ValueError('invalid argument string for psearch: <%s>' %
821 raise ValueError('invalid argument string for psearch: <%s>' %
821 pattern)
822 pattern)
822
823
823 # filter search namespaces
824 # filter search namespaces
824 for name in ns_search:
825 for name in ns_search:
825 if name not in ns_table:
826 if name not in ns_table:
826 raise ValueError('invalid namespace <%s>. Valid names: %s' %
827 raise ValueError('invalid namespace <%s>. Valid names: %s' %
827 (name,ns_table.keys()))
828 (name,ns_table.keys()))
828
829
829 #print 'type_pattern:',type_pattern # dbg
830 #print 'type_pattern:',type_pattern # dbg
830 search_result, namespaces_seen = set(), set()
831 search_result, namespaces_seen = set(), set()
831 for ns_name in ns_search:
832 for ns_name in ns_search:
832 ns = ns_table[ns_name]
833 ns = ns_table[ns_name]
833 # Normally, locals and globals are the same, so we just check one.
834 # Normally, locals and globals are the same, so we just check one.
834 if id(ns) in namespaces_seen:
835 if id(ns) in namespaces_seen:
835 continue
836 continue
836 namespaces_seen.add(id(ns))
837 namespaces_seen.add(id(ns))
837 tmp_res = list_namespace(ns, type_pattern, filter,
838 tmp_res = list_namespace(ns, type_pattern, filter,
838 ignore_case=ignore_case, show_all=show_all)
839 ignore_case=ignore_case, show_all=show_all)
839 search_result.update(tmp_res)
840 search_result.update(tmp_res)
840
841
841 page.page('\n'.join(sorted(search_result)))
842 page.page('\n'.join(sorted(search_result)))
@@ -1,340 +1,341 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Paging capabilities for IPython.core
3 Paging capabilities for IPython.core
4
4
5 Authors:
5 Authors:
6
6
7 * Brian Granger
7 * Brian Granger
8 * Fernando Perez
8 * Fernando Perez
9
9
10 Notes
10 Notes
11 -----
11 -----
12
12
13 For now this uses ipapi, so it can't be in IPython.utils. If we can get
13 For now this uses ipapi, so it can't be in IPython.utils. If we can get
14 rid of that dependency, we could move it there.
14 rid of that dependency, we could move it there.
15 -----
15 -----
16 """
16 """
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Copyright (C) 2008-2011 The IPython Development Team
19 # Copyright (C) 2008-2011 The IPython Development Team
20 #
20 #
21 # Distributed under the terms of the BSD License. The full license is in
21 # Distributed under the terms of the BSD License. The full license is in
22 # the file COPYING, distributed as part of this software.
22 # the file COPYING, distributed as part of this software.
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Imports
26 # Imports
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 from __future__ import print_function
28
29
29 import os
30 import os
30 import re
31 import re
31 import sys
32 import sys
32 import tempfile
33 import tempfile
33
34
34 from io import UnsupportedOperation
35 from io import UnsupportedOperation
35
36
36 from IPython.core import ipapi
37 from IPython.core import ipapi
37 from IPython.core.error import TryNext
38 from IPython.core.error import TryNext
38 from IPython.utils.cursesimport import use_curses
39 from IPython.utils.cursesimport import use_curses
39 from IPython.utils.data import chop
40 from IPython.utils.data import chop
40 from IPython.utils import io
41 from IPython.utils import io
41 from IPython.utils.process import system
42 from IPython.utils.process import system
42 from IPython.utils.terminal import get_terminal_size
43 from IPython.utils.terminal import get_terminal_size
43
44
44
45
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46 # Classes and functions
47 # Classes and functions
47 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
48
49
49 esc_re = re.compile(r"(\x1b[^m]+m)")
50 esc_re = re.compile(r"(\x1b[^m]+m)")
50
51
51 def page_dumb(strng, start=0, screen_lines=25):
52 def page_dumb(strng, start=0, screen_lines=25):
52 """Very dumb 'pager' in Python, for when nothing else works.
53 """Very dumb 'pager' in Python, for when nothing else works.
53
54
54 Only moves forward, same interface as page(), except for pager_cmd and
55 Only moves forward, same interface as page(), except for pager_cmd and
55 mode."""
56 mode."""
56
57
57 out_ln = strng.splitlines()[start:]
58 out_ln = strng.splitlines()[start:]
58 screens = chop(out_ln,screen_lines-1)
59 screens = chop(out_ln,screen_lines-1)
59 if len(screens) == 1:
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 else:
62 else:
62 last_escape = ""
63 last_escape = ""
63 for scr in screens[0:-1]:
64 for scr in screens[0:-1]:
64 hunk = os.linesep.join(scr)
65 hunk = os.linesep.join(scr)
65 print >>io.stdout, last_escape + hunk
66 print(last_escape + hunk, file=io.stdout)
66 if not page_more():
67 if not page_more():
67 return
68 return
68 esc_list = esc_re.findall(hunk)
69 esc_list = esc_re.findall(hunk)
69 if len(esc_list) > 0:
70 if len(esc_list) > 0:
70 last_escape = esc_list[-1]
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 def _detect_screen_size(use_curses, screen_lines_def):
74 def _detect_screen_size(use_curses, screen_lines_def):
74 """Attempt to work out the number of lines on the screen.
75 """Attempt to work out the number of lines on the screen.
75
76
76 This is called by page(). It can raise an error (e.g. when run in the
77 This is called by page(). It can raise an error (e.g. when run in the
77 test suite), so it's separated out so it can easily be called in a try block.
78 test suite), so it's separated out so it can easily be called in a try block.
78 """
79 """
79 TERM = os.environ.get('TERM',None)
80 TERM = os.environ.get('TERM',None)
80 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
81 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
81 local_use_curses = use_curses
82 local_use_curses = use_curses
82 else:
83 else:
83 # curses causes problems on many terminals other than xterm, and
84 # curses causes problems on many terminals other than xterm, and
84 # some termios calls lock up on Sun OS5.
85 # some termios calls lock up on Sun OS5.
85 local_use_curses = False
86 local_use_curses = False
86 if local_use_curses:
87 if local_use_curses:
87 import termios
88 import termios
88 import curses
89 import curses
89 # There is a bug in curses, where *sometimes* it fails to properly
90 # There is a bug in curses, where *sometimes* it fails to properly
90 # initialize, and then after the endwin() call is made, the
91 # initialize, and then after the endwin() call is made, the
91 # terminal is left in an unusable state. Rather than trying to
92 # terminal is left in an unusable state. Rather than trying to
92 # check everytime for this (by requesting and comparing termios
93 # check everytime for this (by requesting and comparing termios
93 # flags each time), we just save the initial terminal state and
94 # flags each time), we just save the initial terminal state and
94 # unconditionally reset it every time. It's cheaper than making
95 # unconditionally reset it every time. It's cheaper than making
95 # the checks.
96 # the checks.
96 term_flags = termios.tcgetattr(sys.stdout)
97 term_flags = termios.tcgetattr(sys.stdout)
97
98
98 # Curses modifies the stdout buffer size by default, which messes
99 # Curses modifies the stdout buffer size by default, which messes
99 # up Python's normal stdout buffering. This would manifest itself
100 # up Python's normal stdout buffering. This would manifest itself
100 # to IPython users as delayed printing on stdout after having used
101 # to IPython users as delayed printing on stdout after having used
101 # the pager.
102 # the pager.
102 #
103 #
103 # We can prevent this by manually setting the NCURSES_NO_SETBUF
104 # We can prevent this by manually setting the NCURSES_NO_SETBUF
104 # environment variable. For more details, see:
105 # environment variable. For more details, see:
105 # http://bugs.python.org/issue10144
106 # http://bugs.python.org/issue10144
106 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
107 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
107 os.environ['NCURSES_NO_SETBUF'] = ''
108 os.environ['NCURSES_NO_SETBUF'] = ''
108
109
109 # Proceed with curses initialization
110 # Proceed with curses initialization
110 scr = curses.initscr()
111 scr = curses.initscr()
111 screen_lines_real,screen_cols = scr.getmaxyx()
112 screen_lines_real,screen_cols = scr.getmaxyx()
112 curses.endwin()
113 curses.endwin()
113
114
114 # Restore environment
115 # Restore environment
115 if NCURSES_NO_SETBUF is None:
116 if NCURSES_NO_SETBUF is None:
116 del os.environ['NCURSES_NO_SETBUF']
117 del os.environ['NCURSES_NO_SETBUF']
117 else:
118 else:
118 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
119 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
119
120
120 # Restore terminal state in case endwin() didn't.
121 # Restore terminal state in case endwin() didn't.
121 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
122 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
122 # Now we have what we needed: the screen size in rows/columns
123 # Now we have what we needed: the screen size in rows/columns
123 return screen_lines_real
124 return screen_lines_real
124 #print '***Screen size:',screen_lines_real,'lines x',\
125 #print '***Screen size:',screen_lines_real,'lines x',\
125 #screen_cols,'columns.' # dbg
126 #screen_cols,'columns.' # dbg
126 else:
127 else:
127 return screen_lines_def
128 return screen_lines_def
128
129
129 def page(strng, start=0, screen_lines=0, pager_cmd=None):
130 def page(strng, start=0, screen_lines=0, pager_cmd=None):
130 """Print a string, piping through a pager after a certain length.
131 """Print a string, piping through a pager after a certain length.
131
132
132 The screen_lines parameter specifies the number of *usable* lines of your
133 The screen_lines parameter specifies the number of *usable* lines of your
133 terminal screen (total lines minus lines you need to reserve to show other
134 terminal screen (total lines minus lines you need to reserve to show other
134 information).
135 information).
135
136
136 If you set screen_lines to a number <=0, page() will try to auto-determine
137 If you set screen_lines to a number <=0, page() will try to auto-determine
137 your screen size and will only use up to (screen_size+screen_lines) for
138 your screen size and will only use up to (screen_size+screen_lines) for
138 printing, paging after that. That is, if you want auto-detection but need
139 printing, paging after that. That is, if you want auto-detection but need
139 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
140 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
140 auto-detection without any lines reserved simply use screen_lines = 0.
141 auto-detection without any lines reserved simply use screen_lines = 0.
141
142
142 If a string won't fit in the allowed lines, it is sent through the
143 If a string won't fit in the allowed lines, it is sent through the
143 specified pager command. If none given, look for PAGER in the environment,
144 specified pager command. If none given, look for PAGER in the environment,
144 and ultimately default to less.
145 and ultimately default to less.
145
146
146 If no system pager works, the string is sent through a 'dumb pager'
147 If no system pager works, the string is sent through a 'dumb pager'
147 written in python, very simplistic.
148 written in python, very simplistic.
148 """
149 """
149
150
150 # Some routines may auto-compute start offsets incorrectly and pass a
151 # Some routines may auto-compute start offsets incorrectly and pass a
151 # negative value. Offset to 0 for robustness.
152 # negative value. Offset to 0 for robustness.
152 start = max(0, start)
153 start = max(0, start)
153
154
154 # first, try the hook
155 # first, try the hook
155 ip = ipapi.get()
156 ip = ipapi.get()
156 if ip:
157 if ip:
157 try:
158 try:
158 ip.hooks.show_in_pager(strng)
159 ip.hooks.show_in_pager(strng)
159 return
160 return
160 except TryNext:
161 except TryNext:
161 pass
162 pass
162
163
163 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
164 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
164 TERM = os.environ.get('TERM','dumb')
165 TERM = os.environ.get('TERM','dumb')
165 if TERM in ['dumb','emacs'] and os.name != 'nt':
166 if TERM in ['dumb','emacs'] and os.name != 'nt':
166 print strng
167 print(strng)
167 return
168 return
168 # chop off the topmost part of the string we don't want to see
169 # chop off the topmost part of the string we don't want to see
169 str_lines = strng.splitlines()[start:]
170 str_lines = strng.splitlines()[start:]
170 str_toprint = os.linesep.join(str_lines)
171 str_toprint = os.linesep.join(str_lines)
171 num_newlines = len(str_lines)
172 num_newlines = len(str_lines)
172 len_str = len(str_toprint)
173 len_str = len(str_toprint)
173
174
174 # Dumb heuristics to guesstimate number of on-screen lines the string
175 # Dumb heuristics to guesstimate number of on-screen lines the string
175 # takes. Very basic, but good enough for docstrings in reasonable
176 # takes. Very basic, but good enough for docstrings in reasonable
176 # terminals. If someone later feels like refining it, it's not hard.
177 # terminals. If someone later feels like refining it, it's not hard.
177 numlines = max(num_newlines,int(len_str/80)+1)
178 numlines = max(num_newlines,int(len_str/80)+1)
178
179
179 screen_lines_def = get_terminal_size()[1]
180 screen_lines_def = get_terminal_size()[1]
180
181
181 # auto-determine screen size
182 # auto-determine screen size
182 if screen_lines <= 0:
183 if screen_lines <= 0:
183 try:
184 try:
184 screen_lines += _detect_screen_size(use_curses, screen_lines_def)
185 screen_lines += _detect_screen_size(use_curses, screen_lines_def)
185 except (TypeError, UnsupportedOperation):
186 except (TypeError, UnsupportedOperation):
186 print >>io.stdout, str_toprint
187 print(str_toprint, file=io.stdout)
187 return
188 return
188
189
189 #print 'numlines',numlines,'screenlines',screen_lines # dbg
190 #print 'numlines',numlines,'screenlines',screen_lines # dbg
190 if numlines <= screen_lines :
191 if numlines <= screen_lines :
191 #print '*** normal print' # dbg
192 #print '*** normal print' # dbg
192 print >>io.stdout, str_toprint
193 print(str_toprint, file=io.stdout)
193 else:
194 else:
194 # Try to open pager and default to internal one if that fails.
195 # Try to open pager and default to internal one if that fails.
195 # All failure modes are tagged as 'retval=1', to match the return
196 # All failure modes are tagged as 'retval=1', to match the return
196 # value of a failed system command. If any intermediate attempt
197 # value of a failed system command. If any intermediate attempt
197 # sets retval to 1, at the end we resort to our own page_dumb() pager.
198 # sets retval to 1, at the end we resort to our own page_dumb() pager.
198 pager_cmd = get_pager_cmd(pager_cmd)
199 pager_cmd = get_pager_cmd(pager_cmd)
199 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
200 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
200 if os.name == 'nt':
201 if os.name == 'nt':
201 if pager_cmd.startswith('type'):
202 if pager_cmd.startswith('type'):
202 # The default WinXP 'type' command is failing on complex strings.
203 # The default WinXP 'type' command is failing on complex strings.
203 retval = 1
204 retval = 1
204 else:
205 else:
205 tmpname = tempfile.mktemp('.txt')
206 tmpname = tempfile.mktemp('.txt')
206 tmpfile = open(tmpname,'wt')
207 tmpfile = open(tmpname,'wt')
207 tmpfile.write(strng)
208 tmpfile.write(strng)
208 tmpfile.close()
209 tmpfile.close()
209 cmd = "%s < %s" % (pager_cmd,tmpname)
210 cmd = "%s < %s" % (pager_cmd,tmpname)
210 if os.system(cmd):
211 if os.system(cmd):
211 retval = 1
212 retval = 1
212 else:
213 else:
213 retval = None
214 retval = None
214 os.remove(tmpname)
215 os.remove(tmpname)
215 else:
216 else:
216 try:
217 try:
217 retval = None
218 retval = None
218 # if I use popen4, things hang. No idea why.
219 # if I use popen4, things hang. No idea why.
219 #pager,shell_out = os.popen4(pager_cmd)
220 #pager,shell_out = os.popen4(pager_cmd)
220 pager = os.popen(pager_cmd,'w')
221 pager = os.popen(pager_cmd,'w')
221 pager.write(strng)
222 pager.write(strng)
222 pager.close()
223 pager.close()
223 retval = pager.close() # success returns None
224 retval = pager.close() # success returns None
224 except IOError as msg: # broken pipe when user quits
225 except IOError as msg: # broken pipe when user quits
225 if msg.args == (32,'Broken pipe'):
226 if msg.args == (32,'Broken pipe'):
226 retval = None
227 retval = None
227 else:
228 else:
228 retval = 1
229 retval = 1
229 except OSError:
230 except OSError:
230 # Other strange problems, sometimes seen in Win2k/cygwin
231 # Other strange problems, sometimes seen in Win2k/cygwin
231 retval = 1
232 retval = 1
232 if retval is not None:
233 if retval is not None:
233 page_dumb(strng,screen_lines=screen_lines)
234 page_dumb(strng,screen_lines=screen_lines)
234
235
235
236
236 def page_file(fname, start=0, pager_cmd=None):
237 def page_file(fname, start=0, pager_cmd=None):
237 """Page a file, using an optional pager command and starting line.
238 """Page a file, using an optional pager command and starting line.
238 """
239 """
239
240
240 pager_cmd = get_pager_cmd(pager_cmd)
241 pager_cmd = get_pager_cmd(pager_cmd)
241 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
242 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
242
243
243 try:
244 try:
244 if os.environ['TERM'] in ['emacs','dumb']:
245 if os.environ['TERM'] in ['emacs','dumb']:
245 raise EnvironmentError
246 raise EnvironmentError
246 system(pager_cmd + ' ' + fname)
247 system(pager_cmd + ' ' + fname)
247 except:
248 except:
248 try:
249 try:
249 if start > 0:
250 if start > 0:
250 start -= 1
251 start -= 1
251 page(open(fname).read(),start)
252 page(open(fname).read(),start)
252 except:
253 except:
253 print 'Unable to show file',`fname`
254 print('Unable to show file',repr(fname))
254
255
255
256
256 def get_pager_cmd(pager_cmd=None):
257 def get_pager_cmd(pager_cmd=None):
257 """Return a pager command.
258 """Return a pager command.
258
259
259 Makes some attempts at finding an OS-correct one.
260 Makes some attempts at finding an OS-correct one.
260 """
261 """
261 if os.name == 'posix':
262 if os.name == 'posix':
262 default_pager_cmd = 'less -r' # -r for color control sequences
263 default_pager_cmd = 'less -r' # -r for color control sequences
263 elif os.name in ['nt','dos']:
264 elif os.name in ['nt','dos']:
264 default_pager_cmd = 'type'
265 default_pager_cmd = 'type'
265
266
266 if pager_cmd is None:
267 if pager_cmd is None:
267 try:
268 try:
268 pager_cmd = os.environ['PAGER']
269 pager_cmd = os.environ['PAGER']
269 except:
270 except:
270 pager_cmd = default_pager_cmd
271 pager_cmd = default_pager_cmd
271 return pager_cmd
272 return pager_cmd
272
273
273
274
274 def get_pager_start(pager, start):
275 def get_pager_start(pager, start):
275 """Return the string for paging files with an offset.
276 """Return the string for paging files with an offset.
276
277
277 This is the '+N' argument which less and more (under Unix) accept.
278 This is the '+N' argument which less and more (under Unix) accept.
278 """
279 """
279
280
280 if pager in ['less','more']:
281 if pager in ['less','more']:
281 if start:
282 if start:
282 start_string = '+' + str(start)
283 start_string = '+' + str(start)
283 else:
284 else:
284 start_string = ''
285 start_string = ''
285 else:
286 else:
286 start_string = ''
287 start_string = ''
287 return start_string
288 return start_string
288
289
289
290
290 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
291 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
291 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
292 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
292 import msvcrt
293 import msvcrt
293 def page_more():
294 def page_more():
294 """ Smart pausing between pages
295 """ Smart pausing between pages
295
296
296 @return: True if need print more lines, False if quit
297 @return: True if need print more lines, False if quit
297 """
298 """
298 io.stdout.write('---Return to continue, q to quit--- ')
299 io.stdout.write('---Return to continue, q to quit--- ')
299 ans = msvcrt.getch()
300 ans = msvcrt.getch()
300 if ans in ("q", "Q"):
301 if ans in ("q", "Q"):
301 result = False
302 result = False
302 else:
303 else:
303 result = True
304 result = True
304 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
305 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
305 return result
306 return result
306 else:
307 else:
307 def page_more():
308 def page_more():
308 ans = raw_input('---Return to continue, q to quit--- ')
309 ans = raw_input('---Return to continue, q to quit--- ')
309 if ans.lower().startswith('q'):
310 if ans.lower().startswith('q'):
310 return False
311 return False
311 else:
312 else:
312 return True
313 return True
313
314
314
315
315 def snip_print(str,width = 75,print_full = 0,header = ''):
316 def snip_print(str,width = 75,print_full = 0,header = ''):
316 """Print a string snipping the midsection to fit in width.
317 """Print a string snipping the midsection to fit in width.
317
318
318 print_full: mode control:
319 print_full: mode control:
319 - 0: only snip long strings
320 - 0: only snip long strings
320 - 1: send to page() directly.
321 - 1: send to page() directly.
321 - 2: snip long strings and ask for full length viewing with page()
322 - 2: snip long strings and ask for full length viewing with page()
322 Return 1 if snipping was necessary, 0 otherwise."""
323 Return 1 if snipping was necessary, 0 otherwise."""
323
324
324 if print_full == 1:
325 if print_full == 1:
325 page(header+str)
326 page(header+str)
326 return 0
327 return 0
327
328
328 print header,
329 print(header, end=' ')
329 if len(str) < width:
330 if len(str) < width:
330 print str
331 print(str)
331 snip = 0
332 snip = 0
332 else:
333 else:
333 whalf = int((width -5)/2)
334 whalf = int((width -5)/2)
334 print str[:whalf] + ' <...> ' + str[-whalf:]
335 print(str[:whalf] + ' <...> ' + str[-whalf:])
335 snip = 1
336 snip = 1
336 if snip and print_full == 2:
337 if snip and print_full == 2:
337 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
338 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
338 page(str)
339 page(str)
339 return snip
340 return snip
340
341
@@ -1,1244 +1,1244 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultratb.py -- Spice up your tracebacks!
3 ultratb.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultratb
12 import sys,ultratb
13 sys.excepthook = ultratb.ColorTB()
13 sys.excepthook = ultratb.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultratb
40 import sys,ultratb
41 sys.excepthook = ultratb.VerboseTB()
41 sys.excepthook = ultratb.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62 """
62 """
63
63
64 #*****************************************************************************
64 #*****************************************************************************
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 #
67 #
68 # Distributed under the terms of the BSD License. The full license is in
68 # Distributed under the terms of the BSD License. The full license is in
69 # the file COPYING, distributed as part of this software.
69 # the file COPYING, distributed as part of this software.
70 #*****************************************************************************
70 #*****************************************************************************
71
71
72 from __future__ import with_statement
72 from __future__ import with_statement
73
73
74 import inspect
74 import inspect
75 import keyword
75 import keyword
76 import linecache
76 import linecache
77 import os
77 import os
78 import pydoc
78 import pydoc
79 import re
79 import re
80 import sys
80 import sys
81 import time
81 import time
82 import tokenize
82 import tokenize
83 import traceback
83 import traceback
84 import types
84 import types
85
85
86 try: # Python 2
86 try: # Python 2
87 generate_tokens = tokenize.generate_tokens
87 generate_tokens = tokenize.generate_tokens
88 except AttributeError: # Python 3
88 except AttributeError: # Python 3
89 generate_tokens = tokenize.tokenize
89 generate_tokens = tokenize.tokenize
90
90
91 # For purposes of monkeypatching inspect to fix a bug in it.
91 # For purposes of monkeypatching inspect to fix a bug in it.
92 from inspect import getsourcefile, getfile, getmodule,\
92 from inspect import getsourcefile, getfile, getmodule,\
93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
94
94
95 # IPython's own modules
95 # IPython's own modules
96 # Modified pdb which doesn't damage IPython's readline handling
96 # Modified pdb which doesn't damage IPython's readline handling
97 from IPython.core import debugger, ipapi
97 from IPython.core import debugger, ipapi
98 from IPython.core.display_trap import DisplayTrap
98 from IPython.core.display_trap import DisplayTrap
99 from IPython.core.excolors import exception_colors
99 from IPython.core.excolors import exception_colors
100 from IPython.utils import PyColorize
100 from IPython.utils import PyColorize
101 from IPython.utils import io
101 from IPython.utils import io
102 from IPython.utils import py3compat
102 from IPython.utils import py3compat
103 from IPython.utils import pyfile
103 from IPython.utils import pyfile
104 from IPython.utils.data import uniq_stable
104 from IPython.utils.data import uniq_stable
105 from IPython.utils.warn import info, error
105 from IPython.utils.warn import info, error
106
106
107 # Globals
107 # Globals
108 # amount of space to put line numbers before verbose tracebacks
108 # amount of space to put line numbers before verbose tracebacks
109 INDENT_SIZE = 8
109 INDENT_SIZE = 8
110
110
111 # Default color scheme. This is used, for example, by the traceback
111 # Default color scheme. This is used, for example, by the traceback
112 # formatter. When running in an actual IPython instance, the user's rc.colors
112 # formatter. When running in an actual IPython instance, the user's rc.colors
113 # value is used, but havinga module global makes this functionality available
113 # value is used, but havinga module global makes this functionality available
114 # to users of ultratb who are NOT running inside ipython.
114 # to users of ultratb who are NOT running inside ipython.
115 DEFAULT_SCHEME = 'NoColor'
115 DEFAULT_SCHEME = 'NoColor'
116
116
117 #---------------------------------------------------------------------------
117 #---------------------------------------------------------------------------
118 # Code begins
118 # Code begins
119
119
120 # Utility functions
120 # Utility functions
121 def inspect_error():
121 def inspect_error():
122 """Print a message about internal inspect errors.
122 """Print a message about internal inspect errors.
123
123
124 These are unfortunately quite common."""
124 These are unfortunately quite common."""
125
125
126 error('Internal Python error in the inspect module.\n'
126 error('Internal Python error in the inspect module.\n'
127 'Below is the traceback from this internal error.\n')
127 'Below is the traceback from this internal error.\n')
128
128
129
129
130 # N.B. This function is a monkeypatch we are currently not applying.
130 # N.B. This function is a monkeypatch we are currently not applying.
131 # It was written some time ago, to fix an apparent Python bug with
131 # It was written some time ago, to fix an apparent Python bug with
132 # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions
132 # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions
133 # the bug occurred, so we can't tell if it has been fixed. If it reappears, we
133 # the bug occurred, so we can't tell if it has been fixed. If it reappears, we
134 # will apply the monkeypatch again. Also, note that findsource() is not called
134 # will apply the monkeypatch again. Also, note that findsource() is not called
135 # by our code at this time - we don't know if it was when the monkeypatch was
135 # by our code at this time - we don't know if it was when the monkeypatch was
136 # written, or if the monkeypatch is needed for some other code (like a debugger).
136 # written, or if the monkeypatch is needed for some other code (like a debugger).
137 # For the discussion about not applying it, see gh-1229. TK, Jan 2011.
137 # For the discussion about not applying it, see gh-1229. TK, Jan 2011.
138 def findsource(object):
138 def findsource(object):
139 """Return the entire source file and starting line number for an object.
139 """Return the entire source file and starting line number for an object.
140
140
141 The argument may be a module, class, method, function, traceback, frame,
141 The argument may be a module, class, method, function, traceback, frame,
142 or code object. The source code is returned as a list of all the lines
142 or code object. The source code is returned as a list of all the lines
143 in the file and the line number indexes a line in that list. An IOError
143 in the file and the line number indexes a line in that list. An IOError
144 is raised if the source code cannot be retrieved.
144 is raised if the source code cannot be retrieved.
145
145
146 FIXED version with which we monkeypatch the stdlib to work around a bug."""
146 FIXED version with which we monkeypatch the stdlib to work around a bug."""
147
147
148 file = getsourcefile(object) or getfile(object)
148 file = getsourcefile(object) or getfile(object)
149 # If the object is a frame, then trying to get the globals dict from its
149 # If the object is a frame, then trying to get the globals dict from its
150 # module won't work. Instead, the frame object itself has the globals
150 # module won't work. Instead, the frame object itself has the globals
151 # dictionary.
151 # dictionary.
152 globals_dict = None
152 globals_dict = None
153 if inspect.isframe(object):
153 if inspect.isframe(object):
154 # XXX: can this ever be false?
154 # XXX: can this ever be false?
155 globals_dict = object.f_globals
155 globals_dict = object.f_globals
156 else:
156 else:
157 module = getmodule(object, file)
157 module = getmodule(object, file)
158 if module:
158 if module:
159 globals_dict = module.__dict__
159 globals_dict = module.__dict__
160 lines = linecache.getlines(file, globals_dict)
160 lines = linecache.getlines(file, globals_dict)
161 if not lines:
161 if not lines:
162 raise IOError('could not get source code')
162 raise IOError('could not get source code')
163
163
164 if ismodule(object):
164 if ismodule(object):
165 return lines, 0
165 return lines, 0
166
166
167 if isclass(object):
167 if isclass(object):
168 name = object.__name__
168 name = object.__name__
169 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
169 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
170 # make some effort to find the best matching class definition:
170 # make some effort to find the best matching class definition:
171 # use the one with the least indentation, which is the one
171 # use the one with the least indentation, which is the one
172 # that's most probably not inside a function definition.
172 # that's most probably not inside a function definition.
173 candidates = []
173 candidates = []
174 for i in range(len(lines)):
174 for i in range(len(lines)):
175 match = pat.match(lines[i])
175 match = pat.match(lines[i])
176 if match:
176 if match:
177 # if it's at toplevel, it's already the best one
177 # if it's at toplevel, it's already the best one
178 if lines[i][0] == 'c':
178 if lines[i][0] == 'c':
179 return lines, i
179 return lines, i
180 # else add whitespace to candidate list
180 # else add whitespace to candidate list
181 candidates.append((match.group(1), i))
181 candidates.append((match.group(1), i))
182 if candidates:
182 if candidates:
183 # this will sort by whitespace, and by line number,
183 # this will sort by whitespace, and by line number,
184 # less whitespace first
184 # less whitespace first
185 candidates.sort()
185 candidates.sort()
186 return lines, candidates[0][1]
186 return lines, candidates[0][1]
187 else:
187 else:
188 raise IOError('could not find class definition')
188 raise IOError('could not find class definition')
189
189
190 if ismethod(object):
190 if ismethod(object):
191 object = object.im_func
191 object = object.im_func
192 if isfunction(object):
192 if isfunction(object):
193 object = object.func_code
193 object = object.func_code
194 if istraceback(object):
194 if istraceback(object):
195 object = object.tb_frame
195 object = object.tb_frame
196 if isframe(object):
196 if isframe(object):
197 object = object.f_code
197 object = object.f_code
198 if iscode(object):
198 if iscode(object):
199 if not hasattr(object, 'co_firstlineno'):
199 if not hasattr(object, 'co_firstlineno'):
200 raise IOError('could not find function definition')
200 raise IOError('could not find function definition')
201 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
201 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
202 pmatch = pat.match
202 pmatch = pat.match
203 # fperez - fix: sometimes, co_firstlineno can give a number larger than
203 # fperez - fix: sometimes, co_firstlineno can give a number larger than
204 # the length of lines, which causes an error. Safeguard against that.
204 # the length of lines, which causes an error. Safeguard against that.
205 lnum = min(object.co_firstlineno,len(lines))-1
205 lnum = min(object.co_firstlineno,len(lines))-1
206 while lnum > 0:
206 while lnum > 0:
207 if pmatch(lines[lnum]): break
207 if pmatch(lines[lnum]): break
208 lnum -= 1
208 lnum -= 1
209
209
210 return lines, lnum
210 return lines, lnum
211 raise IOError('could not find code object')
211 raise IOError('could not find code object')
212
212
213 # Not applying the monkeypatch - see above the function for details. TK, Jan 2012
213 # Not applying the monkeypatch - see above the function for details. TK, Jan 2012
214 # Monkeypatch inspect to apply our bugfix. This code only works with py25
214 # Monkeypatch inspect to apply our bugfix. This code only works with py25
215 #if sys.version_info[:2] >= (2,5):
215 #if sys.version_info[:2] >= (2,5):
216 # inspect.findsource = findsource
216 # inspect.findsource = findsource
217
217
218 def fix_frame_records_filenames(records):
218 def fix_frame_records_filenames(records):
219 """Try to fix the filenames in each record from inspect.getinnerframes().
219 """Try to fix the filenames in each record from inspect.getinnerframes().
220
220
221 Particularly, modules loaded from within zip files have useless filenames
221 Particularly, modules loaded from within zip files have useless filenames
222 attached to their code object, and inspect.getinnerframes() just uses it.
222 attached to their code object, and inspect.getinnerframes() just uses it.
223 """
223 """
224 fixed_records = []
224 fixed_records = []
225 for frame, filename, line_no, func_name, lines, index in records:
225 for frame, filename, line_no, func_name, lines, index in records:
226 # Look inside the frame's globals dictionary for __file__, which should
226 # Look inside the frame's globals dictionary for __file__, which should
227 # be better.
227 # be better.
228 better_fn = frame.f_globals.get('__file__', None)
228 better_fn = frame.f_globals.get('__file__', None)
229 if isinstance(better_fn, str):
229 if isinstance(better_fn, str):
230 # Check the type just in case someone did something weird with
230 # Check the type just in case someone did something weird with
231 # __file__. It might also be None if the error occurred during
231 # __file__. It might also be None if the error occurred during
232 # import.
232 # import.
233 filename = better_fn
233 filename = better_fn
234 fixed_records.append((frame, filename, line_no, func_name, lines, index))
234 fixed_records.append((frame, filename, line_no, func_name, lines, index))
235 return fixed_records
235 return fixed_records
236
236
237
237
238 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
238 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
239 import linecache
239 import linecache
240 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
240 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
241
241
242 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
242 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
243
243
244 # If the error is at the console, don't build any context, since it would
244 # If the error is at the console, don't build any context, since it would
245 # otherwise produce 5 blank lines printed out (there is no file at the
245 # otherwise produce 5 blank lines printed out (there is no file at the
246 # console)
246 # console)
247 rec_check = records[tb_offset:]
247 rec_check = records[tb_offset:]
248 try:
248 try:
249 rname = rec_check[0][1]
249 rname = rec_check[0][1]
250 if rname == '<ipython console>' or rname.endswith('<string>'):
250 if rname == '<ipython console>' or rname.endswith('<string>'):
251 return rec_check
251 return rec_check
252 except IndexError:
252 except IndexError:
253 pass
253 pass
254
254
255 aux = traceback.extract_tb(etb)
255 aux = traceback.extract_tb(etb)
256 assert len(records) == len(aux)
256 assert len(records) == len(aux)
257 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
257 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
258 maybeStart = lnum-1 - context//2
258 maybeStart = lnum-1 - context//2
259 start = max(maybeStart, 0)
259 start = max(maybeStart, 0)
260 end = start + context
260 end = start + context
261 lines = linecache.getlines(file)[start:end]
261 lines = linecache.getlines(file)[start:end]
262 buf = list(records[i])
262 buf = list(records[i])
263 buf[LNUM_POS] = lnum
263 buf[LNUM_POS] = lnum
264 buf[INDEX_POS] = lnum - 1 - start
264 buf[INDEX_POS] = lnum - 1 - start
265 buf[LINES_POS] = lines
265 buf[LINES_POS] = lines
266 records[i] = tuple(buf)
266 records[i] = tuple(buf)
267 return records[tb_offset:]
267 return records[tb_offset:]
268
268
269 # Helper function -- largely belongs to VerboseTB, but we need the same
269 # Helper function -- largely belongs to VerboseTB, but we need the same
270 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
270 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
271 # can be recognized properly by ipython.el's py-traceback-line-re
271 # can be recognized properly by ipython.el's py-traceback-line-re
272 # (SyntaxErrors have to be treated specially because they have no traceback)
272 # (SyntaxErrors have to be treated specially because they have no traceback)
273
273
274 _parser = PyColorize.Parser()
274 _parser = PyColorize.Parser()
275
275
276 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
276 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
277 numbers_width = INDENT_SIZE - 1
277 numbers_width = INDENT_SIZE - 1
278 res = []
278 res = []
279 i = lnum - index
279 i = lnum - index
280
280
281 # This lets us get fully syntax-highlighted tracebacks.
281 # This lets us get fully syntax-highlighted tracebacks.
282 if scheme is None:
282 if scheme is None:
283 ipinst = ipapi.get()
283 ipinst = ipapi.get()
284 if ipinst is not None:
284 if ipinst is not None:
285 scheme = ipinst.colors
285 scheme = ipinst.colors
286 else:
286 else:
287 scheme = DEFAULT_SCHEME
287 scheme = DEFAULT_SCHEME
288
288
289 _line_format = _parser.format2
289 _line_format = _parser.format2
290
290
291 for line in lines:
291 for line in lines:
292 # FIXME: we need to ensure the source is a pure string at this point,
292 # FIXME: we need to ensure the source is a pure string at this point,
293 # else the coloring code makes a royal mess. This is in need of a
293 # else the coloring code makes a royal mess. This is in need of a
294 # serious refactoring, so that all of the ultratb and PyColorize code
294 # serious refactoring, so that all of the ultratb and PyColorize code
295 # is unicode-safe. So for now this is rather an ugly hack, but
295 # is unicode-safe. So for now this is rather an ugly hack, but
296 # necessary to at least have readable tracebacks. Improvements welcome!
296 # necessary to at least have readable tracebacks. Improvements welcome!
297 line = py3compat.cast_bytes_py2(line, 'utf-8')
297 line = py3compat.cast_bytes_py2(line, 'utf-8')
298
298
299 new_line, err = _line_format(line, 'str', scheme)
299 new_line, err = _line_format(line, 'str', scheme)
300 if not err: line = new_line
300 if not err: line = new_line
301
301
302 if i == lnum:
302 if i == lnum:
303 # This is the line with the error
303 # This is the line with the error
304 pad = numbers_width - len(str(i))
304 pad = numbers_width - len(str(i))
305 if pad >= 3:
305 if pad >= 3:
306 marker = '-'*(pad-3) + '-> '
306 marker = '-'*(pad-3) + '-> '
307 elif pad == 2:
307 elif pad == 2:
308 marker = '> '
308 marker = '> '
309 elif pad == 1:
309 elif pad == 1:
310 marker = '>'
310 marker = '>'
311 else:
311 else:
312 marker = ''
312 marker = ''
313 num = marker + str(i)
313 num = marker + str(i)
314 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
314 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
315 Colors.line, line, Colors.Normal)
315 Colors.line, line, Colors.Normal)
316 else:
316 else:
317 num = '%*s' % (numbers_width,i)
317 num = '%*s' % (numbers_width,i)
318 line = '%s%s%s %s' %(Colors.lineno, num,
318 line = '%s%s%s %s' %(Colors.lineno, num,
319 Colors.Normal, line)
319 Colors.Normal, line)
320
320
321 res.append(line)
321 res.append(line)
322 if lvals and i == lnum:
322 if lvals and i == lnum:
323 res.append(lvals + '\n')
323 res.append(lvals + '\n')
324 i = i + 1
324 i = i + 1
325 return res
325 return res
326
326
327
327
328 #---------------------------------------------------------------------------
328 #---------------------------------------------------------------------------
329 # Module classes
329 # Module classes
330 class TBTools(object):
330 class TBTools(object):
331 """Basic tools used by all traceback printer classes."""
331 """Basic tools used by all traceback printer classes."""
332
332
333 # Number of frames to skip when reporting tracebacks
333 # Number of frames to skip when reporting tracebacks
334 tb_offset = 0
334 tb_offset = 0
335
335
336 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
336 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
337 # Whether to call the interactive pdb debugger after printing
337 # Whether to call the interactive pdb debugger after printing
338 # tracebacks or not
338 # tracebacks or not
339 self.call_pdb = call_pdb
339 self.call_pdb = call_pdb
340
340
341 # Output stream to write to. Note that we store the original value in
341 # Output stream to write to. Note that we store the original value in
342 # a private attribute and then make the public ostream a property, so
342 # a private attribute and then make the public ostream a property, so
343 # that we can delay accessing io.stdout until runtime. The way
343 # that we can delay accessing io.stdout until runtime. The way
344 # things are written now, the io.stdout object is dynamically managed
344 # things are written now, the io.stdout object is dynamically managed
345 # so a reference to it should NEVER be stored statically. This
345 # so a reference to it should NEVER be stored statically. This
346 # property approach confines this detail to a single location, and all
346 # property approach confines this detail to a single location, and all
347 # subclasses can simply access self.ostream for writing.
347 # subclasses can simply access self.ostream for writing.
348 self._ostream = ostream
348 self._ostream = ostream
349
349
350 # Create color table
350 # Create color table
351 self.color_scheme_table = exception_colors()
351 self.color_scheme_table = exception_colors()
352
352
353 self.set_colors(color_scheme)
353 self.set_colors(color_scheme)
354 self.old_scheme = color_scheme # save initial value for toggles
354 self.old_scheme = color_scheme # save initial value for toggles
355
355
356 if call_pdb:
356 if call_pdb:
357 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
357 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
358 else:
358 else:
359 self.pdb = None
359 self.pdb = None
360
360
361 def _get_ostream(self):
361 def _get_ostream(self):
362 """Output stream that exceptions are written to.
362 """Output stream that exceptions are written to.
363
363
364 Valid values are:
364 Valid values are:
365
365
366 - None: the default, which means that IPython will dynamically resolve
366 - None: the default, which means that IPython will dynamically resolve
367 to io.stdout. This ensures compatibility with most tools, including
367 to io.stdout. This ensures compatibility with most tools, including
368 Windows (where plain stdout doesn't recognize ANSI escapes).
368 Windows (where plain stdout doesn't recognize ANSI escapes).
369
369
370 - Any object with 'write' and 'flush' attributes.
370 - Any object with 'write' and 'flush' attributes.
371 """
371 """
372 return io.stdout if self._ostream is None else self._ostream
372 return io.stdout if self._ostream is None else self._ostream
373
373
374 def _set_ostream(self, val):
374 def _set_ostream(self, val):
375 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
375 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
376 self._ostream = val
376 self._ostream = val
377
377
378 ostream = property(_get_ostream, _set_ostream)
378 ostream = property(_get_ostream, _set_ostream)
379
379
380 def set_colors(self,*args,**kw):
380 def set_colors(self,*args,**kw):
381 """Shorthand access to the color table scheme selector method."""
381 """Shorthand access to the color table scheme selector method."""
382
382
383 # Set own color table
383 # Set own color table
384 self.color_scheme_table.set_active_scheme(*args,**kw)
384 self.color_scheme_table.set_active_scheme(*args,**kw)
385 # for convenience, set Colors to the active scheme
385 # for convenience, set Colors to the active scheme
386 self.Colors = self.color_scheme_table.active_colors
386 self.Colors = self.color_scheme_table.active_colors
387 # Also set colors of debugger
387 # Also set colors of debugger
388 if hasattr(self,'pdb') and self.pdb is not None:
388 if hasattr(self,'pdb') and self.pdb is not None:
389 self.pdb.set_colors(*args,**kw)
389 self.pdb.set_colors(*args,**kw)
390
390
391 def color_toggle(self):
391 def color_toggle(self):
392 """Toggle between the currently active color scheme and NoColor."""
392 """Toggle between the currently active color scheme and NoColor."""
393
393
394 if self.color_scheme_table.active_scheme_name == 'NoColor':
394 if self.color_scheme_table.active_scheme_name == 'NoColor':
395 self.color_scheme_table.set_active_scheme(self.old_scheme)
395 self.color_scheme_table.set_active_scheme(self.old_scheme)
396 self.Colors = self.color_scheme_table.active_colors
396 self.Colors = self.color_scheme_table.active_colors
397 else:
397 else:
398 self.old_scheme = self.color_scheme_table.active_scheme_name
398 self.old_scheme = self.color_scheme_table.active_scheme_name
399 self.color_scheme_table.set_active_scheme('NoColor')
399 self.color_scheme_table.set_active_scheme('NoColor')
400 self.Colors = self.color_scheme_table.active_colors
400 self.Colors = self.color_scheme_table.active_colors
401
401
402 def stb2text(self, stb):
402 def stb2text(self, stb):
403 """Convert a structured traceback (a list) to a string."""
403 """Convert a structured traceback (a list) to a string."""
404 return '\n'.join(stb)
404 return '\n'.join(stb)
405
405
406 def text(self, etype, value, tb, tb_offset=None, context=5):
406 def text(self, etype, value, tb, tb_offset=None, context=5):
407 """Return formatted traceback.
407 """Return formatted traceback.
408
408
409 Subclasses may override this if they add extra arguments.
409 Subclasses may override this if they add extra arguments.
410 """
410 """
411 tb_list = self.structured_traceback(etype, value, tb,
411 tb_list = self.structured_traceback(etype, value, tb,
412 tb_offset, context)
412 tb_offset, context)
413 return self.stb2text(tb_list)
413 return self.stb2text(tb_list)
414
414
415 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
415 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
416 context=5, mode=None):
416 context=5, mode=None):
417 """Return a list of traceback frames.
417 """Return a list of traceback frames.
418
418
419 Must be implemented by each class.
419 Must be implemented by each class.
420 """
420 """
421 raise NotImplementedError()
421 raise NotImplementedError()
422
422
423
423
424 #---------------------------------------------------------------------------
424 #---------------------------------------------------------------------------
425 class ListTB(TBTools):
425 class ListTB(TBTools):
426 """Print traceback information from a traceback list, with optional color.
426 """Print traceback information from a traceback list, with optional color.
427
427
428 Calling: requires 3 arguments:
428 Calling: requires 3 arguments:
429 (etype, evalue, elist)
429 (etype, evalue, elist)
430 as would be obtained by:
430 as would be obtained by:
431 etype, evalue, tb = sys.exc_info()
431 etype, evalue, tb = sys.exc_info()
432 if tb:
432 if tb:
433 elist = traceback.extract_tb(tb)
433 elist = traceback.extract_tb(tb)
434 else:
434 else:
435 elist = None
435 elist = None
436
436
437 It can thus be used by programs which need to process the traceback before
437 It can thus be used by programs which need to process the traceback before
438 printing (such as console replacements based on the code module from the
438 printing (such as console replacements based on the code module from the
439 standard library).
439 standard library).
440
440
441 Because they are meant to be called without a full traceback (only a
441 Because they are meant to be called without a full traceback (only a
442 list), instances of this class can't call the interactive pdb debugger."""
442 list), instances of this class can't call the interactive pdb debugger."""
443
443
444 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
444 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
445 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
445 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
446 ostream=ostream)
446 ostream=ostream)
447
447
448 def __call__(self, etype, value, elist):
448 def __call__(self, etype, value, elist):
449 self.ostream.flush()
449 self.ostream.flush()
450 self.ostream.write(self.text(etype, value, elist))
450 self.ostream.write(self.text(etype, value, elist))
451 self.ostream.write('\n')
451 self.ostream.write('\n')
452
452
453 def structured_traceback(self, etype, value, elist, tb_offset=None,
453 def structured_traceback(self, etype, value, elist, tb_offset=None,
454 context=5):
454 context=5):
455 """Return a color formatted string with the traceback info.
455 """Return a color formatted string with the traceback info.
456
456
457 Parameters
457 Parameters
458 ----------
458 ----------
459 etype : exception type
459 etype : exception type
460 Type of the exception raised.
460 Type of the exception raised.
461
461
462 value : object
462 value : object
463 Data stored in the exception
463 Data stored in the exception
464
464
465 elist : list
465 elist : list
466 List of frames, see class docstring for details.
466 List of frames, see class docstring for details.
467
467
468 tb_offset : int, optional
468 tb_offset : int, optional
469 Number of frames in the traceback to skip. If not given, the
469 Number of frames in the traceback to skip. If not given, the
470 instance value is used (set in constructor).
470 instance value is used (set in constructor).
471
471
472 context : int, optional
472 context : int, optional
473 Number of lines of context information to print.
473 Number of lines of context information to print.
474
474
475 Returns
475 Returns
476 -------
476 -------
477 String with formatted exception.
477 String with formatted exception.
478 """
478 """
479 tb_offset = self.tb_offset if tb_offset is None else tb_offset
479 tb_offset = self.tb_offset if tb_offset is None else tb_offset
480 Colors = self.Colors
480 Colors = self.Colors
481 out_list = []
481 out_list = []
482 if elist:
482 if elist:
483
483
484 if tb_offset and len(elist) > tb_offset:
484 if tb_offset and len(elist) > tb_offset:
485 elist = elist[tb_offset:]
485 elist = elist[tb_offset:]
486
486
487 out_list.append('Traceback %s(most recent call last)%s:' %
487 out_list.append('Traceback %s(most recent call last)%s:' %
488 (Colors.normalEm, Colors.Normal) + '\n')
488 (Colors.normalEm, Colors.Normal) + '\n')
489 out_list.extend(self._format_list(elist))
489 out_list.extend(self._format_list(elist))
490 # The exception info should be a single entry in the list.
490 # The exception info should be a single entry in the list.
491 lines = ''.join(self._format_exception_only(etype, value))
491 lines = ''.join(self._format_exception_only(etype, value))
492 out_list.append(lines)
492 out_list.append(lines)
493
493
494 # Note: this code originally read:
494 # Note: this code originally read:
495
495
496 ## for line in lines[:-1]:
496 ## for line in lines[:-1]:
497 ## out_list.append(" "+line)
497 ## out_list.append(" "+line)
498 ## out_list.append(lines[-1])
498 ## out_list.append(lines[-1])
499
499
500 # This means it was indenting everything but the last line by a little
500 # This means it was indenting everything but the last line by a little
501 # bit. I've disabled this for now, but if we see ugliness somewhre we
501 # bit. I've disabled this for now, but if we see ugliness somewhre we
502 # can restore it.
502 # can restore it.
503
503
504 return out_list
504 return out_list
505
505
506 def _format_list(self, extracted_list):
506 def _format_list(self, extracted_list):
507 """Format a list of traceback entry tuples for printing.
507 """Format a list of traceback entry tuples for printing.
508
508
509 Given a list of tuples as returned by extract_tb() or
509 Given a list of tuples as returned by extract_tb() or
510 extract_stack(), return a list of strings ready for printing.
510 extract_stack(), return a list of strings ready for printing.
511 Each string in the resulting list corresponds to the item with the
511 Each string in the resulting list corresponds to the item with the
512 same index in the argument list. Each string ends in a newline;
512 same index in the argument list. Each string ends in a newline;
513 the strings may contain internal newlines as well, for those items
513 the strings may contain internal newlines as well, for those items
514 whose source text line is not None.
514 whose source text line is not None.
515
515
516 Lifted almost verbatim from traceback.py
516 Lifted almost verbatim from traceback.py
517 """
517 """
518
518
519 Colors = self.Colors
519 Colors = self.Colors
520 list = []
520 list = []
521 for filename, lineno, name, line in extracted_list[:-1]:
521 for filename, lineno, name, line in extracted_list[:-1]:
522 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
522 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
523 (Colors.filename, filename, Colors.Normal,
523 (Colors.filename, filename, Colors.Normal,
524 Colors.lineno, lineno, Colors.Normal,
524 Colors.lineno, lineno, Colors.Normal,
525 Colors.name, name, Colors.Normal)
525 Colors.name, name, Colors.Normal)
526 if line:
526 if line:
527 item += ' %s\n' % line.strip()
527 item += ' %s\n' % line.strip()
528 list.append(item)
528 list.append(item)
529 # Emphasize the last entry
529 # Emphasize the last entry
530 filename, lineno, name, line = extracted_list[-1]
530 filename, lineno, name, line = extracted_list[-1]
531 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
531 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
532 (Colors.normalEm,
532 (Colors.normalEm,
533 Colors.filenameEm, filename, Colors.normalEm,
533 Colors.filenameEm, filename, Colors.normalEm,
534 Colors.linenoEm, lineno, Colors.normalEm,
534 Colors.linenoEm, lineno, Colors.normalEm,
535 Colors.nameEm, name, Colors.normalEm,
535 Colors.nameEm, name, Colors.normalEm,
536 Colors.Normal)
536 Colors.Normal)
537 if line:
537 if line:
538 item += '%s %s%s\n' % (Colors.line, line.strip(),
538 item += '%s %s%s\n' % (Colors.line, line.strip(),
539 Colors.Normal)
539 Colors.Normal)
540 list.append(item)
540 list.append(item)
541 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
541 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
542 return list
542 return list
543
543
544 def _format_exception_only(self, etype, value):
544 def _format_exception_only(self, etype, value):
545 """Format the exception part of a traceback.
545 """Format the exception part of a traceback.
546
546
547 The arguments are the exception type and value such as given by
547 The arguments are the exception type and value such as given by
548 sys.exc_info()[:2]. The return value is a list of strings, each ending
548 sys.exc_info()[:2]. The return value is a list of strings, each ending
549 in a newline. Normally, the list contains a single string; however,
549 in a newline. Normally, the list contains a single string; however,
550 for SyntaxError exceptions, it contains several lines that (when
550 for SyntaxError exceptions, it contains several lines that (when
551 printed) display detailed information about where the syntax error
551 printed) display detailed information about where the syntax error
552 occurred. The message indicating which exception occurred is the
552 occurred. The message indicating which exception occurred is the
553 always last string in the list.
553 always last string in the list.
554
554
555 Also lifted nearly verbatim from traceback.py
555 Also lifted nearly verbatim from traceback.py
556 """
556 """
557
557
558 have_filedata = False
558 have_filedata = False
559 Colors = self.Colors
559 Colors = self.Colors
560 list = []
560 list = []
561 stype = Colors.excName + etype.__name__ + Colors.Normal
561 stype = Colors.excName + etype.__name__ + Colors.Normal
562 if value is None:
562 if value is None:
563 # Not sure if this can still happen in Python 2.6 and above
563 # Not sure if this can still happen in Python 2.6 and above
564 list.append( str(stype) + '\n')
564 list.append( str(stype) + '\n')
565 else:
565 else:
566 if etype is SyntaxError:
566 if etype is SyntaxError:
567 have_filedata = True
567 have_filedata = True
568 #print 'filename is',filename # dbg
568 #print 'filename is',filename # dbg
569 if not value.filename: value.filename = "<string>"
569 if not value.filename: value.filename = "<string>"
570 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
570 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
571 (Colors.normalEm,
571 (Colors.normalEm,
572 Colors.filenameEm, value.filename, Colors.normalEm,
572 Colors.filenameEm, value.filename, Colors.normalEm,
573 Colors.linenoEm, value.lineno, Colors.Normal ))
573 Colors.linenoEm, value.lineno, Colors.Normal ))
574 if value.text is not None:
574 if value.text is not None:
575 i = 0
575 i = 0
576 while i < len(value.text) and value.text[i].isspace():
576 while i < len(value.text) and value.text[i].isspace():
577 i += 1
577 i += 1
578 list.append('%s %s%s\n' % (Colors.line,
578 list.append('%s %s%s\n' % (Colors.line,
579 value.text.strip(),
579 value.text.strip(),
580 Colors.Normal))
580 Colors.Normal))
581 if value.offset is not None:
581 if value.offset is not None:
582 s = ' '
582 s = ' '
583 for c in value.text[i:value.offset-1]:
583 for c in value.text[i:value.offset-1]:
584 if c.isspace():
584 if c.isspace():
585 s += c
585 s += c
586 else:
586 else:
587 s += ' '
587 s += ' '
588 list.append('%s%s^%s\n' % (Colors.caret, s,
588 list.append('%s%s^%s\n' % (Colors.caret, s,
589 Colors.Normal) )
589 Colors.Normal) )
590
590
591 try:
591 try:
592 s = value.msg
592 s = value.msg
593 except Exception:
593 except Exception:
594 s = self._some_str(value)
594 s = self._some_str(value)
595 if s:
595 if s:
596 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
596 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
597 Colors.Normal, s))
597 Colors.Normal, s))
598 else:
598 else:
599 list.append('%s\n' % str(stype))
599 list.append('%s\n' % str(stype))
600
600
601 # sync with user hooks
601 # sync with user hooks
602 if have_filedata:
602 if have_filedata:
603 ipinst = ipapi.get()
603 ipinst = ipapi.get()
604 if ipinst is not None:
604 if ipinst is not None:
605 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
605 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
606
606
607 return list
607 return list
608
608
609 def get_exception_only(self, etype, value):
609 def get_exception_only(self, etype, value):
610 """Only print the exception type and message, without a traceback.
610 """Only print the exception type and message, without a traceback.
611
611
612 Parameters
612 Parameters
613 ----------
613 ----------
614 etype : exception type
614 etype : exception type
615 value : exception value
615 value : exception value
616 """
616 """
617 return ListTB.structured_traceback(self, etype, value, [])
617 return ListTB.structured_traceback(self, etype, value, [])
618
618
619
619
620 def show_exception_only(self, etype, evalue):
620 def show_exception_only(self, etype, evalue):
621 """Only print the exception type and message, without a traceback.
621 """Only print the exception type and message, without a traceback.
622
622
623 Parameters
623 Parameters
624 ----------
624 ----------
625 etype : exception type
625 etype : exception type
626 value : exception value
626 value : exception value
627 """
627 """
628 # This method needs to use __call__ from *this* class, not the one from
628 # This method needs to use __call__ from *this* class, not the one from
629 # a subclass whose signature or behavior may be different
629 # a subclass whose signature or behavior may be different
630 ostream = self.ostream
630 ostream = self.ostream
631 ostream.flush()
631 ostream.flush()
632 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
632 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
633 ostream.flush()
633 ostream.flush()
634
634
635 def _some_str(self, value):
635 def _some_str(self, value):
636 # Lifted from traceback.py
636 # Lifted from traceback.py
637 try:
637 try:
638 return str(value)
638 return str(value)
639 except:
639 except:
640 return '<unprintable %s object>' % type(value).__name__
640 return '<unprintable %s object>' % type(value).__name__
641
641
642 #----------------------------------------------------------------------------
642 #----------------------------------------------------------------------------
643 class VerboseTB(TBTools):
643 class VerboseTB(TBTools):
644 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
644 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
645 of HTML. Requires inspect and pydoc. Crazy, man.
645 of HTML. Requires inspect and pydoc. Crazy, man.
646
646
647 Modified version which optionally strips the topmost entries from the
647 Modified version which optionally strips the topmost entries from the
648 traceback, to be used with alternate interpreters (because their own code
648 traceback, to be used with alternate interpreters (because their own code
649 would appear in the traceback)."""
649 would appear in the traceback)."""
650
650
651 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
651 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
652 tb_offset=0, long_header=False, include_vars=True,
652 tb_offset=0, long_header=False, include_vars=True,
653 check_cache=None):
653 check_cache=None):
654 """Specify traceback offset, headers and color scheme.
654 """Specify traceback offset, headers and color scheme.
655
655
656 Define how many frames to drop from the tracebacks. Calling it with
656 Define how many frames to drop from the tracebacks. Calling it with
657 tb_offset=1 allows use of this handler in interpreters which will have
657 tb_offset=1 allows use of this handler in interpreters which will have
658 their own code at the top of the traceback (VerboseTB will first
658 their own code at the top of the traceback (VerboseTB will first
659 remove that frame before printing the traceback info)."""
659 remove that frame before printing the traceback info)."""
660 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
660 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
661 ostream=ostream)
661 ostream=ostream)
662 self.tb_offset = tb_offset
662 self.tb_offset = tb_offset
663 self.long_header = long_header
663 self.long_header = long_header
664 self.include_vars = include_vars
664 self.include_vars = include_vars
665 # By default we use linecache.checkcache, but the user can provide a
665 # By default we use linecache.checkcache, but the user can provide a
666 # different check_cache implementation. This is used by the IPython
666 # different check_cache implementation. This is used by the IPython
667 # kernel to provide tracebacks for interactive code that is cached,
667 # kernel to provide tracebacks for interactive code that is cached,
668 # by a compiler instance that flushes the linecache but preserves its
668 # by a compiler instance that flushes the linecache but preserves its
669 # own code cache.
669 # own code cache.
670 if check_cache is None:
670 if check_cache is None:
671 check_cache = linecache.checkcache
671 check_cache = linecache.checkcache
672 self.check_cache = check_cache
672 self.check_cache = check_cache
673
673
674 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
674 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
675 context=5):
675 context=5):
676 """Return a nice text document describing the traceback."""
676 """Return a nice text document describing the traceback."""
677
677
678 tb_offset = self.tb_offset if tb_offset is None else tb_offset
678 tb_offset = self.tb_offset if tb_offset is None else tb_offset
679
679
680 # some locals
680 # some locals
681 try:
681 try:
682 etype = etype.__name__
682 etype = etype.__name__
683 except AttributeError:
683 except AttributeError:
684 pass
684 pass
685 Colors = self.Colors # just a shorthand + quicker name lookup
685 Colors = self.Colors # just a shorthand + quicker name lookup
686 ColorsNormal = Colors.Normal # used a lot
686 ColorsNormal = Colors.Normal # used a lot
687 col_scheme = self.color_scheme_table.active_scheme_name
687 col_scheme = self.color_scheme_table.active_scheme_name
688 indent = ' '*INDENT_SIZE
688 indent = ' '*INDENT_SIZE
689 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
689 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
690 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
690 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
691 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
691 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
692
692
693 # some internal-use functions
693 # some internal-use functions
694 def text_repr(value):
694 def text_repr(value):
695 """Hopefully pretty robust repr equivalent."""
695 """Hopefully pretty robust repr equivalent."""
696 # this is pretty horrible but should always return *something*
696 # this is pretty horrible but should always return *something*
697 try:
697 try:
698 return pydoc.text.repr(value)
698 return pydoc.text.repr(value)
699 except KeyboardInterrupt:
699 except KeyboardInterrupt:
700 raise
700 raise
701 except:
701 except:
702 try:
702 try:
703 return repr(value)
703 return repr(value)
704 except KeyboardInterrupt:
704 except KeyboardInterrupt:
705 raise
705 raise
706 except:
706 except:
707 try:
707 try:
708 # all still in an except block so we catch
708 # all still in an except block so we catch
709 # getattr raising
709 # getattr raising
710 name = getattr(value, '__name__', None)
710 name = getattr(value, '__name__', None)
711 if name:
711 if name:
712 # ick, recursion
712 # ick, recursion
713 return text_repr(name)
713 return text_repr(name)
714 klass = getattr(value, '__class__', None)
714 klass = getattr(value, '__class__', None)
715 if klass:
715 if klass:
716 return '%s instance' % text_repr(klass)
716 return '%s instance' % text_repr(klass)
717 except KeyboardInterrupt:
717 except KeyboardInterrupt:
718 raise
718 raise
719 except:
719 except:
720 return 'UNRECOVERABLE REPR FAILURE'
720 return 'UNRECOVERABLE REPR FAILURE'
721 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
721 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
722 def nullrepr(value, repr=text_repr): return ''
722 def nullrepr(value, repr=text_repr): return ''
723
723
724 # meat of the code begins
724 # meat of the code begins
725 try:
725 try:
726 etype = etype.__name__
726 etype = etype.__name__
727 except AttributeError:
727 except AttributeError:
728 pass
728 pass
729
729
730 if self.long_header:
730 if self.long_header:
731 # Header with the exception type, python version, and date
731 # Header with the exception type, python version, and date
732 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
732 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
733 date = time.ctime(time.time())
733 date = time.ctime(time.time())
734
734
735 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
735 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
736 exc, ' '*(75-len(str(etype))-len(pyver)),
736 exc, ' '*(75-len(str(etype))-len(pyver)),
737 pyver, date.rjust(75) )
737 pyver, date.rjust(75) )
738 head += "\nA problem occured executing Python code. Here is the sequence of function"\
738 head += "\nA problem occured executing Python code. Here is the sequence of function"\
739 "\ncalls leading up to the error, with the most recent (innermost) call last."
739 "\ncalls leading up to the error, with the most recent (innermost) call last."
740 else:
740 else:
741 # Simplified header
741 # Simplified header
742 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
742 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
743 'Traceback (most recent call last)'.\
743 'Traceback (most recent call last)'.\
744 rjust(75 - len(str(etype)) ) )
744 rjust(75 - len(str(etype)) ) )
745 frames = []
745 frames = []
746 # Flush cache before calling inspect. This helps alleviate some of the
746 # Flush cache before calling inspect. This helps alleviate some of the
747 # problems with python 2.3's inspect.py.
747 # problems with python 2.3's inspect.py.
748 ##self.check_cache()
748 ##self.check_cache()
749 # Drop topmost frames if requested
749 # Drop topmost frames if requested
750 try:
750 try:
751 # Try the default getinnerframes and Alex's: Alex's fixes some
751 # Try the default getinnerframes and Alex's: Alex's fixes some
752 # problems, but it generates empty tracebacks for console errors
752 # problems, but it generates empty tracebacks for console errors
753 # (5 blanks lines) where none should be returned.
753 # (5 blanks lines) where none should be returned.
754 #records = inspect.getinnerframes(etb, context)[tb_offset:]
754 #records = inspect.getinnerframes(etb, context)[tb_offset:]
755 #print 'python records:', records # dbg
755 #print 'python records:', records # dbg
756 records = _fixed_getinnerframes(etb, context, tb_offset)
756 records = _fixed_getinnerframes(etb, context, tb_offset)
757 #print 'alex records:', records # dbg
757 #print 'alex records:', records # dbg
758 except:
758 except:
759
759
760 # FIXME: I've been getting many crash reports from python 2.3
760 # FIXME: I've been getting many crash reports from python 2.3
761 # users, traceable to inspect.py. If I can find a small test-case
761 # users, traceable to inspect.py. If I can find a small test-case
762 # to reproduce this, I should either write a better workaround or
762 # to reproduce this, I should either write a better workaround or
763 # file a bug report against inspect (if that's the real problem).
763 # file a bug report against inspect (if that's the real problem).
764 # So far, I haven't been able to find an isolated example to
764 # So far, I haven't been able to find an isolated example to
765 # reproduce the problem.
765 # reproduce the problem.
766 inspect_error()
766 inspect_error()
767 traceback.print_exc(file=self.ostream)
767 traceback.print_exc(file=self.ostream)
768 info('\nUnfortunately, your original traceback can not be constructed.\n')
768 info('\nUnfortunately, your original traceback can not be constructed.\n')
769 return ''
769 return ''
770
770
771 # build some color string templates outside these nested loops
771 # build some color string templates outside these nested loops
772 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
772 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
773 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
773 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
774 ColorsNormal)
774 ColorsNormal)
775 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
775 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
776 (Colors.vName, Colors.valEm, ColorsNormal)
776 (Colors.vName, Colors.valEm, ColorsNormal)
777 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
777 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
778 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
778 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
779 Colors.vName, ColorsNormal)
779 Colors.vName, ColorsNormal)
780 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
780 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
781 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
781 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
782 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
782 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
783 ColorsNormal)
783 ColorsNormal)
784
784
785 # now, loop over all records printing context and info
785 # now, loop over all records printing context and info
786 abspath = os.path.abspath
786 abspath = os.path.abspath
787 for frame, file, lnum, func, lines, index in records:
787 for frame, file, lnum, func, lines, index in records:
788 #print '*** record:',file,lnum,func,lines,index # dbg
788 #print '*** record:',file,lnum,func,lines,index # dbg
789
789
790 if not file:
790 if not file:
791 file = '?'
791 file = '?'
792 elif not(file.startswith("<") and file.endswith(">")):
792 elif not(file.startswith("<") and file.endswith(">")):
793 # Guess that filenames like <string> aren't real filenames, so
793 # Guess that filenames like <string> aren't real filenames, so
794 # don't call abspath on them.
794 # don't call abspath on them.
795 try:
795 try:
796 file = abspath(file)
796 file = abspath(file)
797 except OSError:
797 except OSError:
798 # Not sure if this can still happen: abspath now works with
798 # Not sure if this can still happen: abspath now works with
799 # file names like <string>
799 # file names like <string>
800 pass
800 pass
801
801
802 link = tpl_link % file
802 link = tpl_link % file
803 args, varargs, varkw, locals = inspect.getargvalues(frame)
803 args, varargs, varkw, locals = inspect.getargvalues(frame)
804
804
805 if func == '?':
805 if func == '?':
806 call = ''
806 call = ''
807 else:
807 else:
808 # Decide whether to include variable details or not
808 # Decide whether to include variable details or not
809 var_repr = self.include_vars and eqrepr or nullrepr
809 var_repr = self.include_vars and eqrepr or nullrepr
810 try:
810 try:
811 call = tpl_call % (func,inspect.formatargvalues(args,
811 call = tpl_call % (func,inspect.formatargvalues(args,
812 varargs, varkw,
812 varargs, varkw,
813 locals,formatvalue=var_repr))
813 locals,formatvalue=var_repr))
814 except KeyError:
814 except KeyError:
815 # This happens in situations like errors inside generator
815 # This happens in situations like errors inside generator
816 # expressions, where local variables are listed in the
816 # expressions, where local variables are listed in the
817 # line, but can't be extracted from the frame. I'm not
817 # line, but can't be extracted from the frame. I'm not
818 # 100% sure this isn't actually a bug in inspect itself,
818 # 100% sure this isn't actually a bug in inspect itself,
819 # but since there's no info for us to compute with, the
819 # but since there's no info for us to compute with, the
820 # best we can do is report the failure and move on. Here
820 # best we can do is report the failure and move on. Here
821 # we must *not* call any traceback construction again,
821 # we must *not* call any traceback construction again,
822 # because that would mess up use of %debug later on. So we
822 # because that would mess up use of %debug later on. So we
823 # simply report the failure and move on. The only
823 # simply report the failure and move on. The only
824 # limitation will be that this frame won't have locals
824 # limitation will be that this frame won't have locals
825 # listed in the call signature. Quite subtle problem...
825 # listed in the call signature. Quite subtle problem...
826 # I can't think of a good way to validate this in a unit
826 # I can't think of a good way to validate this in a unit
827 # test, but running a script consisting of:
827 # test, but running a script consisting of:
828 # dict( (k,v.strip()) for (k,v) in range(10) )
828 # dict( (k,v.strip()) for (k,v) in range(10) )
829 # will illustrate the error, if this exception catch is
829 # will illustrate the error, if this exception catch is
830 # disabled.
830 # disabled.
831 call = tpl_call_fail % func
831 call = tpl_call_fail % func
832
832
833 # Don't attempt to tokenize binary files.
833 # Don't attempt to tokenize binary files.
834 if file.endswith(('.so', '.pyd', '.dll')):
834 if file.endswith(('.so', '.pyd', '.dll')):
835 frames.append('%s %s\n' % (link,call))
835 frames.append('%s %s\n' % (link,call))
836 continue
836 continue
837 elif file.endswith(('.pyc','.pyo')):
837 elif file.endswith(('.pyc','.pyo')):
838 # Look up the corresponding source file.
838 # Look up the corresponding source file.
839 file = pyfile.source_from_cache(file)
839 file = pyfile.source_from_cache(file)
840
840
841 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
841 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
842 line = getline(file, lnum[0])
842 line = getline(file, lnum[0])
843 lnum[0] += 1
843 lnum[0] += 1
844 return line
844 return line
845
845
846 # Build the list of names on this line of code where the exception
846 # Build the list of names on this line of code where the exception
847 # occurred.
847 # occurred.
848 try:
848 try:
849 names = []
849 names = []
850 name_cont = False
850 name_cont = False
851
851
852 for token_type, token, start, end, line in generate_tokens(linereader):
852 for token_type, token, start, end, line in generate_tokens(linereader):
853 # build composite names
853 # build composite names
854 if token_type == tokenize.NAME and token not in keyword.kwlist:
854 if token_type == tokenize.NAME and token not in keyword.kwlist:
855 if name_cont:
855 if name_cont:
856 # Continuation of a dotted name
856 # Continuation of a dotted name
857 try:
857 try:
858 names[-1].append(token)
858 names[-1].append(token)
859 except IndexError:
859 except IndexError:
860 names.append([token])
860 names.append([token])
861 name_cont = False
861 name_cont = False
862 else:
862 else:
863 # Regular new names. We append everything, the caller
863 # Regular new names. We append everything, the caller
864 # will be responsible for pruning the list later. It's
864 # will be responsible for pruning the list later. It's
865 # very tricky to try to prune as we go, b/c composite
865 # very tricky to try to prune as we go, b/c composite
866 # names can fool us. The pruning at the end is easy
866 # names can fool us. The pruning at the end is easy
867 # to do (or the caller can print a list with repeated
867 # to do (or the caller can print a list with repeated
868 # names if so desired.
868 # names if so desired.
869 names.append([token])
869 names.append([token])
870 elif token == '.':
870 elif token == '.':
871 name_cont = True
871 name_cont = True
872 elif token_type == tokenize.NEWLINE:
872 elif token_type == tokenize.NEWLINE:
873 break
873 break
874
874
875 except (IndexError, UnicodeDecodeError):
875 except (IndexError, UnicodeDecodeError):
876 # signals exit of tokenizer
876 # signals exit of tokenizer
877 pass
877 pass
878 except tokenize.TokenError as msg:
878 except tokenize.TokenError as msg:
879 _m = ("An unexpected error occurred while tokenizing input\n"
879 _m = ("An unexpected error occurred while tokenizing input\n"
880 "The following traceback may be corrupted or invalid\n"
880 "The following traceback may be corrupted or invalid\n"
881 "The error message is: %s\n" % msg)
881 "The error message is: %s\n" % msg)
882 error(_m)
882 error(_m)
883
883
884 # Join composite names (e.g. "dict.fromkeys")
884 # Join composite names (e.g. "dict.fromkeys")
885 names = ['.'.join(n) for n in names]
885 names = ['.'.join(n) for n in names]
886 # prune names list of duplicates, but keep the right order
886 # prune names list of duplicates, but keep the right order
887 unique_names = uniq_stable(names)
887 unique_names = uniq_stable(names)
888
888
889 # Start loop over vars
889 # Start loop over vars
890 lvals = []
890 lvals = []
891 if self.include_vars:
891 if self.include_vars:
892 for name_full in unique_names:
892 for name_full in unique_names:
893 name_base = name_full.split('.',1)[0]
893 name_base = name_full.split('.',1)[0]
894 if name_base in frame.f_code.co_varnames:
894 if name_base in frame.f_code.co_varnames:
895 if locals.has_key(name_base):
895 if locals.has_key(name_base):
896 try:
896 try:
897 value = repr(eval(name_full,locals))
897 value = repr(eval(name_full,locals))
898 except:
898 except:
899 value = undefined
899 value = undefined
900 else:
900 else:
901 value = undefined
901 value = undefined
902 name = tpl_local_var % name_full
902 name = tpl_local_var % name_full
903 else:
903 else:
904 if frame.f_globals.has_key(name_base):
904 if frame.f_globals.has_key(name_base):
905 try:
905 try:
906 value = repr(eval(name_full,frame.f_globals))
906 value = repr(eval(name_full,frame.f_globals))
907 except:
907 except:
908 value = undefined
908 value = undefined
909 else:
909 else:
910 value = undefined
910 value = undefined
911 name = tpl_global_var % name_full
911 name = tpl_global_var % name_full
912 lvals.append(tpl_name_val % (name,value))
912 lvals.append(tpl_name_val % (name,value))
913 if lvals:
913 if lvals:
914 lvals = '%s%s' % (indent,em_normal.join(lvals))
914 lvals = '%s%s' % (indent,em_normal.join(lvals))
915 else:
915 else:
916 lvals = ''
916 lvals = ''
917
917
918 level = '%s %s\n' % (link,call)
918 level = '%s %s\n' % (link,call)
919
919
920 if index is None:
920 if index is None:
921 frames.append(level)
921 frames.append(level)
922 else:
922 else:
923 frames.append('%s%s' % (level,''.join(
923 frames.append('%s%s' % (level,''.join(
924 _format_traceback_lines(lnum,index,lines,Colors,lvals,
924 _format_traceback_lines(lnum,index,lines,Colors,lvals,
925 col_scheme))))
925 col_scheme))))
926
926
927 # Get (safely) a string form of the exception info
927 # Get (safely) a string form of the exception info
928 try:
928 try:
929 etype_str,evalue_str = map(str,(etype,evalue))
929 etype_str,evalue_str = map(str,(etype,evalue))
930 except:
930 except:
931 # User exception is improperly defined.
931 # User exception is improperly defined.
932 etype,evalue = str,sys.exc_info()[:2]
932 etype,evalue = str,sys.exc_info()[:2]
933 etype_str,evalue_str = map(str,(etype,evalue))
933 etype_str,evalue_str = map(str,(etype,evalue))
934 # ... and format it
934 # ... and format it
935 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
935 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
936 ColorsNormal, evalue_str)]
936 ColorsNormal, evalue_str)]
937 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
937 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
938 try:
938 try:
939 names = [w for w in dir(evalue) if isinstance(w, basestring)]
939 names = [w for w in dir(evalue) if isinstance(w, basestring)]
940 except:
940 except:
941 # Every now and then, an object with funny inernals blows up
941 # Every now and then, an object with funny inernals blows up
942 # when dir() is called on it. We do the best we can to report
942 # when dir() is called on it. We do the best we can to report
943 # the problem and continue
943 # the problem and continue
944 _m = '%sException reporting error (object with broken dir())%s:'
944 _m = '%sException reporting error (object with broken dir())%s:'
945 exception.append(_m % (Colors.excName,ColorsNormal))
945 exception.append(_m % (Colors.excName,ColorsNormal))
946 etype_str,evalue_str = map(str,sys.exc_info()[:2])
946 etype_str,evalue_str = map(str,sys.exc_info()[:2])
947 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
947 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
948 ColorsNormal, evalue_str))
948 ColorsNormal, evalue_str))
949 names = []
949 names = []
950 for name in names:
950 for name in names:
951 value = text_repr(getattr(evalue, name))
951 value = text_repr(getattr(evalue, name))
952 exception.append('\n%s%s = %s' % (indent, name, value))
952 exception.append('\n%s%s = %s' % (indent, name, value))
953
953
954 # vds: >>
954 # vds: >>
955 if records:
955 if records:
956 filepath, lnum = records[-1][1:3]
956 filepath, lnum = records[-1][1:3]
957 #print "file:", str(file), "linenb", str(lnum) # dbg
957 #print "file:", str(file), "linenb", str(lnum) # dbg
958 filepath = os.path.abspath(filepath)
958 filepath = os.path.abspath(filepath)
959 ipinst = ipapi.get()
959 ipinst = ipapi.get()
960 if ipinst is not None:
960 if ipinst is not None:
961 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
961 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
962 # vds: <<
962 # vds: <<
963
963
964 # return all our info assembled as a single string
964 # return all our info assembled as a single string
965 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
965 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
966 return [head] + frames + [''.join(exception[0])]
966 return [head] + frames + [''.join(exception[0])]
967
967
968 def debugger(self,force=False):
968 def debugger(self,force=False):
969 """Call up the pdb debugger if desired, always clean up the tb
969 """Call up the pdb debugger if desired, always clean up the tb
970 reference.
970 reference.
971
971
972 Keywords:
972 Keywords:
973
973
974 - force(False): by default, this routine checks the instance call_pdb
974 - force(False): by default, this routine checks the instance call_pdb
975 flag and does not actually invoke the debugger if the flag is false.
975 flag and does not actually invoke the debugger if the flag is false.
976 The 'force' option forces the debugger to activate even if the flag
976 The 'force' option forces the debugger to activate even if the flag
977 is false.
977 is false.
978
978
979 If the call_pdb flag is set, the pdb interactive debugger is
979 If the call_pdb flag is set, the pdb interactive debugger is
980 invoked. In all cases, the self.tb reference to the current traceback
980 invoked. In all cases, the self.tb reference to the current traceback
981 is deleted to prevent lingering references which hamper memory
981 is deleted to prevent lingering references which hamper memory
982 management.
982 management.
983
983
984 Note that each call to pdb() does an 'import readline', so if your app
984 Note that each call to pdb() does an 'import readline', so if your app
985 requires a special setup for the readline completers, you'll have to
985 requires a special setup for the readline completers, you'll have to
986 fix that by hand after invoking the exception handler."""
986 fix that by hand after invoking the exception handler."""
987
987
988 if force or self.call_pdb:
988 if force or self.call_pdb:
989 if self.pdb is None:
989 if self.pdb is None:
990 self.pdb = debugger.Pdb(
990 self.pdb = debugger.Pdb(
991 self.color_scheme_table.active_scheme_name)
991 self.color_scheme_table.active_scheme_name)
992 # the system displayhook may have changed, restore the original
992 # the system displayhook may have changed, restore the original
993 # for pdb
993 # for pdb
994 display_trap = DisplayTrap(hook=sys.__displayhook__)
994 display_trap = DisplayTrap(hook=sys.__displayhook__)
995 with display_trap:
995 with display_trap:
996 self.pdb.reset()
996 self.pdb.reset()
997 # Find the right frame so we don't pop up inside ipython itself
997 # Find the right frame so we don't pop up inside ipython itself
998 if hasattr(self,'tb') and self.tb is not None:
998 if hasattr(self,'tb') and self.tb is not None:
999 etb = self.tb
999 etb = self.tb
1000 else:
1000 else:
1001 etb = self.tb = sys.last_traceback
1001 etb = self.tb = sys.last_traceback
1002 while self.tb is not None and self.tb.tb_next is not None:
1002 while self.tb is not None and self.tb.tb_next is not None:
1003 self.tb = self.tb.tb_next
1003 self.tb = self.tb.tb_next
1004 if etb and etb.tb_next:
1004 if etb and etb.tb_next:
1005 etb = etb.tb_next
1005 etb = etb.tb_next
1006 self.pdb.botframe = etb.tb_frame
1006 self.pdb.botframe = etb.tb_frame
1007 self.pdb.interaction(self.tb.tb_frame, self.tb)
1007 self.pdb.interaction(self.tb.tb_frame, self.tb)
1008
1008
1009 if hasattr(self,'tb'):
1009 if hasattr(self,'tb'):
1010 del self.tb
1010 del self.tb
1011
1011
1012 def handler(self, info=None):
1012 def handler(self, info=None):
1013 (etype, evalue, etb) = info or sys.exc_info()
1013 (etype, evalue, etb) = info or sys.exc_info()
1014 self.tb = etb
1014 self.tb = etb
1015 ostream = self.ostream
1015 ostream = self.ostream
1016 ostream.flush()
1016 ostream.flush()
1017 ostream.write(self.text(etype, evalue, etb))
1017 ostream.write(self.text(etype, evalue, etb))
1018 ostream.write('\n')
1018 ostream.write('\n')
1019 ostream.flush()
1019 ostream.flush()
1020
1020
1021 # Changed so an instance can just be called as VerboseTB_inst() and print
1021 # Changed so an instance can just be called as VerboseTB_inst() and print
1022 # out the right info on its own.
1022 # out the right info on its own.
1023 def __call__(self, etype=None, evalue=None, etb=None):
1023 def __call__(self, etype=None, evalue=None, etb=None):
1024 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1024 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1025 if etb is None:
1025 if etb is None:
1026 self.handler()
1026 self.handler()
1027 else:
1027 else:
1028 self.handler((etype, evalue, etb))
1028 self.handler((etype, evalue, etb))
1029 try:
1029 try:
1030 self.debugger()
1030 self.debugger()
1031 except KeyboardInterrupt:
1031 except KeyboardInterrupt:
1032 print "\nKeyboardInterrupt"
1032 print "\nKeyboardInterrupt"
1033
1033
1034 #----------------------------------------------------------------------------
1034 #----------------------------------------------------------------------------
1035 class FormattedTB(VerboseTB, ListTB):
1035 class FormattedTB(VerboseTB, ListTB):
1036 """Subclass ListTB but allow calling with a traceback.
1036 """Subclass ListTB but allow calling with a traceback.
1037
1037
1038 It can thus be used as a sys.excepthook for Python > 2.1.
1038 It can thus be used as a sys.excepthook for Python > 2.1.
1039
1039
1040 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1040 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1041
1041
1042 Allows a tb_offset to be specified. This is useful for situations where
1042 Allows a tb_offset to be specified. This is useful for situations where
1043 one needs to remove a number of topmost frames from the traceback (such as
1043 one needs to remove a number of topmost frames from the traceback (such as
1044 occurs with python programs that themselves execute other python code,
1044 occurs with python programs that themselves execute other python code,
1045 like Python shells). """
1045 like Python shells). """
1046
1046
1047 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1047 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1048 ostream=None,
1048 ostream=None,
1049 tb_offset=0, long_header=False, include_vars=False,
1049 tb_offset=0, long_header=False, include_vars=False,
1050 check_cache=None):
1050 check_cache=None):
1051
1051
1052 # NEVER change the order of this list. Put new modes at the end:
1052 # NEVER change the order of this list. Put new modes at the end:
1053 self.valid_modes = ['Plain','Context','Verbose']
1053 self.valid_modes = ['Plain','Context','Verbose']
1054 self.verbose_modes = self.valid_modes[1:3]
1054 self.verbose_modes = self.valid_modes[1:3]
1055
1055
1056 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1056 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1057 ostream=ostream, tb_offset=tb_offset,
1057 ostream=ostream, tb_offset=tb_offset,
1058 long_header=long_header, include_vars=include_vars,
1058 long_header=long_header, include_vars=include_vars,
1059 check_cache=check_cache)
1059 check_cache=check_cache)
1060
1060
1061 # Different types of tracebacks are joined with different separators to
1061 # Different types of tracebacks are joined with different separators to
1062 # form a single string. They are taken from this dict
1062 # form a single string. They are taken from this dict
1063 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1063 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1064 # set_mode also sets the tb_join_char attribute
1064 # set_mode also sets the tb_join_char attribute
1065 self.set_mode(mode)
1065 self.set_mode(mode)
1066
1066
1067 def _extract_tb(self,tb):
1067 def _extract_tb(self,tb):
1068 if tb:
1068 if tb:
1069 return traceback.extract_tb(tb)
1069 return traceback.extract_tb(tb)
1070 else:
1070 else:
1071 return None
1071 return None
1072
1072
1073 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1073 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1074 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1074 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 mode = self.mode
1075 mode = self.mode
1076 if mode in self.verbose_modes:
1076 if mode in self.verbose_modes:
1077 # Verbose modes need a full traceback
1077 # Verbose modes need a full traceback
1078 return VerboseTB.structured_traceback(
1078 return VerboseTB.structured_traceback(
1079 self, etype, value, tb, tb_offset, context
1079 self, etype, value, tb, tb_offset, context
1080 )
1080 )
1081 else:
1081 else:
1082 # We must check the source cache because otherwise we can print
1082 # We must check the source cache because otherwise we can print
1083 # out-of-date source code.
1083 # out-of-date source code.
1084 self.check_cache()
1084 self.check_cache()
1085 # Now we can extract and format the exception
1085 # Now we can extract and format the exception
1086 elist = self._extract_tb(tb)
1086 elist = self._extract_tb(tb)
1087 return ListTB.structured_traceback(
1087 return ListTB.structured_traceback(
1088 self, etype, value, elist, tb_offset, context
1088 self, etype, value, elist, tb_offset, context
1089 )
1089 )
1090
1090
1091 def stb2text(self, stb):
1091 def stb2text(self, stb):
1092 """Convert a structured traceback (a list) to a string."""
1092 """Convert a structured traceback (a list) to a string."""
1093 return self.tb_join_char.join(stb)
1093 return self.tb_join_char.join(stb)
1094
1094
1095
1095
1096 def set_mode(self,mode=None):
1096 def set_mode(self,mode=None):
1097 """Switch to the desired mode.
1097 """Switch to the desired mode.
1098
1098
1099 If mode is not specified, cycles through the available modes."""
1099 If mode is not specified, cycles through the available modes."""
1100
1100
1101 if not mode:
1101 if not mode:
1102 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1102 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1103 len(self.valid_modes)
1103 len(self.valid_modes)
1104 self.mode = self.valid_modes[new_idx]
1104 self.mode = self.valid_modes[new_idx]
1105 elif mode not in self.valid_modes:
1105 elif mode not in self.valid_modes:
1106 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1106 raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n'
1107 'Valid modes: '+str(self.valid_modes)
1107 'Valid modes: '+str(self.valid_modes))
1108 else:
1108 else:
1109 self.mode = mode
1109 self.mode = mode
1110 # include variable details only in 'Verbose' mode
1110 # include variable details only in 'Verbose' mode
1111 self.include_vars = (self.mode == self.valid_modes[2])
1111 self.include_vars = (self.mode == self.valid_modes[2])
1112 # Set the join character for generating text tracebacks
1112 # Set the join character for generating text tracebacks
1113 self.tb_join_char = self._join_chars[self.mode]
1113 self.tb_join_char = self._join_chars[self.mode]
1114
1114
1115 # some convenient shorcuts
1115 # some convenient shorcuts
1116 def plain(self):
1116 def plain(self):
1117 self.set_mode(self.valid_modes[0])
1117 self.set_mode(self.valid_modes[0])
1118
1118
1119 def context(self):
1119 def context(self):
1120 self.set_mode(self.valid_modes[1])
1120 self.set_mode(self.valid_modes[1])
1121
1121
1122 def verbose(self):
1122 def verbose(self):
1123 self.set_mode(self.valid_modes[2])
1123 self.set_mode(self.valid_modes[2])
1124
1124
1125 #----------------------------------------------------------------------------
1125 #----------------------------------------------------------------------------
1126 class AutoFormattedTB(FormattedTB):
1126 class AutoFormattedTB(FormattedTB):
1127 """A traceback printer which can be called on the fly.
1127 """A traceback printer which can be called on the fly.
1128
1128
1129 It will find out about exceptions by itself.
1129 It will find out about exceptions by itself.
1130
1130
1131 A brief example:
1131 A brief example:
1132
1132
1133 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1133 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1134 try:
1134 try:
1135 ...
1135 ...
1136 except:
1136 except:
1137 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1137 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1138 """
1138 """
1139
1139
1140 def __call__(self,etype=None,evalue=None,etb=None,
1140 def __call__(self,etype=None,evalue=None,etb=None,
1141 out=None,tb_offset=None):
1141 out=None,tb_offset=None):
1142 """Print out a formatted exception traceback.
1142 """Print out a formatted exception traceback.
1143
1143
1144 Optional arguments:
1144 Optional arguments:
1145 - out: an open file-like object to direct output to.
1145 - out: an open file-like object to direct output to.
1146
1146
1147 - tb_offset: the number of frames to skip over in the stack, on a
1147 - tb_offset: the number of frames to skip over in the stack, on a
1148 per-call basis (this overrides temporarily the instance's tb_offset
1148 per-call basis (this overrides temporarily the instance's tb_offset
1149 given at initialization time. """
1149 given at initialization time. """
1150
1150
1151
1151
1152 if out is None:
1152 if out is None:
1153 out = self.ostream
1153 out = self.ostream
1154 out.flush()
1154 out.flush()
1155 out.write(self.text(etype, evalue, etb, tb_offset))
1155 out.write(self.text(etype, evalue, etb, tb_offset))
1156 out.write('\n')
1156 out.write('\n')
1157 out.flush()
1157 out.flush()
1158 # FIXME: we should remove the auto pdb behavior from here and leave
1158 # FIXME: we should remove the auto pdb behavior from here and leave
1159 # that to the clients.
1159 # that to the clients.
1160 try:
1160 try:
1161 self.debugger()
1161 self.debugger()
1162 except KeyboardInterrupt:
1162 except KeyboardInterrupt:
1163 print "\nKeyboardInterrupt"
1163 print "\nKeyboardInterrupt"
1164
1164
1165 def structured_traceback(self, etype=None, value=None, tb=None,
1165 def structured_traceback(self, etype=None, value=None, tb=None,
1166 tb_offset=None, context=5):
1166 tb_offset=None, context=5):
1167 if etype is None:
1167 if etype is None:
1168 etype,value,tb = sys.exc_info()
1168 etype,value,tb = sys.exc_info()
1169 self.tb = tb
1169 self.tb = tb
1170 return FormattedTB.structured_traceback(
1170 return FormattedTB.structured_traceback(
1171 self, etype, value, tb, tb_offset, context)
1171 self, etype, value, tb, tb_offset, context)
1172
1172
1173 #---------------------------------------------------------------------------
1173 #---------------------------------------------------------------------------
1174
1174
1175 # A simple class to preserve Nathan's original functionality.
1175 # A simple class to preserve Nathan's original functionality.
1176 class ColorTB(FormattedTB):
1176 class ColorTB(FormattedTB):
1177 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1177 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1178 def __init__(self,color_scheme='Linux',call_pdb=0):
1178 def __init__(self,color_scheme='Linux',call_pdb=0):
1179 FormattedTB.__init__(self,color_scheme=color_scheme,
1179 FormattedTB.__init__(self,color_scheme=color_scheme,
1180 call_pdb=call_pdb)
1180 call_pdb=call_pdb)
1181
1181
1182
1182
1183 class SyntaxTB(ListTB):
1183 class SyntaxTB(ListTB):
1184 """Extension which holds some state: the last exception value"""
1184 """Extension which holds some state: the last exception value"""
1185
1185
1186 def __init__(self,color_scheme = 'NoColor'):
1186 def __init__(self,color_scheme = 'NoColor'):
1187 ListTB.__init__(self,color_scheme)
1187 ListTB.__init__(self,color_scheme)
1188 self.last_syntax_error = None
1188 self.last_syntax_error = None
1189
1189
1190 def __call__(self, etype, value, elist):
1190 def __call__(self, etype, value, elist):
1191 self.last_syntax_error = value
1191 self.last_syntax_error = value
1192 ListTB.__call__(self,etype,value,elist)
1192 ListTB.__call__(self,etype,value,elist)
1193
1193
1194 def clear_err_state(self):
1194 def clear_err_state(self):
1195 """Return the current error state and clear it"""
1195 """Return the current error state and clear it"""
1196 e = self.last_syntax_error
1196 e = self.last_syntax_error
1197 self.last_syntax_error = None
1197 self.last_syntax_error = None
1198 return e
1198 return e
1199
1199
1200 def stb2text(self, stb):
1200 def stb2text(self, stb):
1201 """Convert a structured traceback (a list) to a string."""
1201 """Convert a structured traceback (a list) to a string."""
1202 return ''.join(stb)
1202 return ''.join(stb)
1203
1203
1204
1204
1205 #----------------------------------------------------------------------------
1205 #----------------------------------------------------------------------------
1206 # module testing (minimal)
1206 # module testing (minimal)
1207 if __name__ == "__main__":
1207 if __name__ == "__main__":
1208 def spam(c, (d, e)):
1208 def spam(c, (d, e)):
1209 x = c + d
1209 x = c + d
1210 y = c * d
1210 y = c * d
1211 foo(x, y)
1211 foo(x, y)
1212
1212
1213 def foo(a, b, bar=1):
1213 def foo(a, b, bar=1):
1214 eggs(a, b + bar)
1214 eggs(a, b + bar)
1215
1215
1216 def eggs(f, g, z=globals()):
1216 def eggs(f, g, z=globals()):
1217 h = f + g
1217 h = f + g
1218 i = f - g
1218 i = f - g
1219 return h / i
1219 return h / i
1220
1220
1221 print ''
1221 print ''
1222 print '*** Before ***'
1222 print '*** Before ***'
1223 try:
1223 try:
1224 print spam(1, (2, 3))
1224 print spam(1, (2, 3))
1225 except:
1225 except:
1226 traceback.print_exc()
1226 traceback.print_exc()
1227 print ''
1227 print ''
1228
1228
1229 handler = ColorTB()
1229 handler = ColorTB()
1230 print '*** ColorTB ***'
1230 print '*** ColorTB ***'
1231 try:
1231 try:
1232 print spam(1, (2, 3))
1232 print spam(1, (2, 3))
1233 except:
1233 except:
1234 apply(handler, sys.exc_info() )
1234 handler(*sys.exc_info())
1235 print ''
1235 print ''
1236
1236
1237 handler = VerboseTB()
1237 handler = VerboseTB()
1238 print '*** VerboseTB ***'
1238 print '*** VerboseTB ***'
1239 try:
1239 try:
1240 print spam(1, (2, 3))
1240 print spam(1, (2, 3))
1241 except:
1241 except:
1242 apply(handler, sys.exc_info() )
1242 handler(*sys.exc_info())
1243 print ''
1243 print ''
1244
1244
@@ -1,537 +1,538 b''
1 """IPython extension to reload modules before executing user code.
1 """IPython extension to reload modules before executing user code.
2
2
3 ``autoreload`` reloads modules automatically before entering the execution of
3 ``autoreload`` reloads modules automatically before entering the execution of
4 code typed at the IPython prompt.
4 code typed at the IPython prompt.
5
5
6 This makes for example the following workflow possible:
6 This makes for example the following workflow possible:
7
7
8 .. sourcecode:: ipython
8 .. sourcecode:: ipython
9
9
10 In [1]: %load_ext autoreload
10 In [1]: %load_ext autoreload
11
11
12 In [2]: %autoreload 2
12 In [2]: %autoreload 2
13
13
14 In [3]: from foo import some_function
14 In [3]: from foo import some_function
15
15
16 In [4]: some_function()
16 In [4]: some_function()
17 Out[4]: 42
17 Out[4]: 42
18
18
19 In [5]: # open foo.py in an editor and change some_function to return 43
19 In [5]: # open foo.py in an editor and change some_function to return 43
20
20
21 In [6]: some_function()
21 In [6]: some_function()
22 Out[6]: 43
22 Out[6]: 43
23
23
24 The module was reloaded without reloading it explicitly, and the object
24 The module was reloaded without reloading it explicitly, and the object
25 imported with ``from foo import ...`` was also updated.
25 imported with ``from foo import ...`` was also updated.
26
26
27 Usage
27 Usage
28 =====
28 =====
29
29
30 The following magic commands are provided:
30 The following magic commands are provided:
31
31
32 ``%autoreload``
32 ``%autoreload``
33
33
34 Reload all modules (except those excluded by ``%aimport``)
34 Reload all modules (except those excluded by ``%aimport``)
35 automatically now.
35 automatically now.
36
36
37 ``%autoreload 0``
37 ``%autoreload 0``
38
38
39 Disable automatic reloading.
39 Disable automatic reloading.
40
40
41 ``%autoreload 1``
41 ``%autoreload 1``
42
42
43 Reload all modules imported with ``%aimport`` every time before
43 Reload all modules imported with ``%aimport`` every time before
44 executing the Python code typed.
44 executing the Python code typed.
45
45
46 ``%autoreload 2``
46 ``%autoreload 2``
47
47
48 Reload all modules (except those excluded by ``%aimport``) every
48 Reload all modules (except those excluded by ``%aimport``) every
49 time before executing the Python code typed.
49 time before executing the Python code typed.
50
50
51 ``%aimport``
51 ``%aimport``
52
52
53 List modules which are to be automatically imported or not to be imported.
53 List modules which are to be automatically imported or not to be imported.
54
54
55 ``%aimport foo``
55 ``%aimport foo``
56
56
57 Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``
57 Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``
58
58
59 ``%aimport -foo``
59 ``%aimport -foo``
60
60
61 Mark module 'foo' to not be autoreloaded.
61 Mark module 'foo' to not be autoreloaded.
62
62
63 Caveats
63 Caveats
64 =======
64 =======
65
65
66 Reloading Python modules in a reliable way is in general difficult,
66 Reloading Python modules in a reliable way is in general difficult,
67 and unexpected things may occur. ``%autoreload`` tries to work around
67 and unexpected things may occur. ``%autoreload`` tries to work around
68 common pitfalls by replacing function code objects and parts of
68 common pitfalls by replacing function code objects and parts of
69 classes previously in the module with new versions. This makes the
69 classes previously in the module with new versions. This makes the
70 following things to work:
70 following things to work:
71
71
72 - Functions and classes imported via 'from xxx import foo' are upgraded
72 - Functions and classes imported via 'from xxx import foo' are upgraded
73 to new versions when 'xxx' is reloaded.
73 to new versions when 'xxx' is reloaded.
74
74
75 - Methods and properties of classes are upgraded on reload, so that
75 - Methods and properties of classes are upgraded on reload, so that
76 calling 'c.foo()' on an object 'c' created before the reload causes
76 calling 'c.foo()' on an object 'c' created before the reload causes
77 the new code for 'foo' to be executed.
77 the new code for 'foo' to be executed.
78
78
79 Some of the known remaining caveats are:
79 Some of the known remaining caveats are:
80
80
81 - Replacing code objects does not always succeed: changing a @property
81 - Replacing code objects does not always succeed: changing a @property
82 in a class to an ordinary method or a method to a member variable
82 in a class to an ordinary method or a method to a member variable
83 can cause problems (but in old objects only).
83 can cause problems (but in old objects only).
84
84
85 - Functions that are removed (eg. via monkey-patching) from a module
85 - Functions that are removed (eg. via monkey-patching) from a module
86 before it is reloaded are not upgraded.
86 before it is reloaded are not upgraded.
87
87
88 - C extension modules cannot be reloaded, and so cannot be autoreloaded.
88 - C extension modules cannot be reloaded, and so cannot be autoreloaded.
89 """
89 """
90 from __future__ import print_function
90
91
91 skip_doctest = True
92 skip_doctest = True
92
93
93 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
94 # Copyright (C) 2000 Thomas Heller
95 # Copyright (C) 2000 Thomas Heller
95 # Copyright (C) 2008 Pauli Virtanen <pav@iki.fi>
96 # Copyright (C) 2008 Pauli Virtanen <pav@iki.fi>
96 # Copyright (C) 2012 The IPython Development Team
97 # Copyright (C) 2012 The IPython Development Team
97 #
98 #
98 # Distributed under the terms of the BSD License. The full license is in
99 # Distributed under the terms of the BSD License. The full license is in
99 # the file COPYING, distributed as part of this software.
100 # the file COPYING, distributed as part of this software.
100 #-----------------------------------------------------------------------------
101 #-----------------------------------------------------------------------------
101 #
102 #
102 # This IPython module is written by Pauli Virtanen, based on the autoreload
103 # This IPython module is written by Pauli Virtanen, based on the autoreload
103 # code by Thomas Heller.
104 # code by Thomas Heller.
104
105
105 #-----------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------
106 # Imports
107 # Imports
107 #-----------------------------------------------------------------------------
108 #-----------------------------------------------------------------------------
108 import atexit
109 import atexit
109 import imp
110 import imp
110 import inspect
111 import inspect
111 import os
112 import os
112 import sys
113 import sys
113 import threading
114 import threading
114 import time
115 import time
115 import traceback
116 import traceback
116 import types
117 import types
117 import weakref
118 import weakref
118
119
119 try:
120 try:
120 # Reload is not defined by default in Python3.
121 # Reload is not defined by default in Python3.
121 reload
122 reload
122 except NameError:
123 except NameError:
123 from imp import reload
124 from imp import reload
124
125
125 from IPython.utils import pyfile
126 from IPython.utils import pyfile
126 from IPython.utils.py3compat import PY3
127 from IPython.utils.py3compat import PY3
127
128
128 #------------------------------------------------------------------------------
129 #------------------------------------------------------------------------------
129 # Autoreload functionality
130 # Autoreload functionality
130 #------------------------------------------------------------------------------
131 #------------------------------------------------------------------------------
131
132
132 def _get_compiled_ext():
133 def _get_compiled_ext():
133 """Official way to get the extension of compiled files (.pyc or .pyo)"""
134 """Official way to get the extension of compiled files (.pyc or .pyo)"""
134 for ext, mode, typ in imp.get_suffixes():
135 for ext, mode, typ in imp.get_suffixes():
135 if typ == imp.PY_COMPILED:
136 if typ == imp.PY_COMPILED:
136 return ext
137 return ext
137
138
138
139
139 PY_COMPILED_EXT = _get_compiled_ext()
140 PY_COMPILED_EXT = _get_compiled_ext()
140
141
141
142
142 class ModuleReloader(object):
143 class ModuleReloader(object):
143 enabled = False
144 enabled = False
144 """Whether this reloader is enabled"""
145 """Whether this reloader is enabled"""
145
146
146 failed = {}
147 failed = {}
147 """Modules that failed to reload: {module: mtime-on-failed-reload, ...}"""
148 """Modules that failed to reload: {module: mtime-on-failed-reload, ...}"""
148
149
149 modules = {}
150 modules = {}
150 """Modules specially marked as autoreloadable."""
151 """Modules specially marked as autoreloadable."""
151
152
152 skip_modules = {}
153 skip_modules = {}
153 """Modules specially marked as not autoreloadable."""
154 """Modules specially marked as not autoreloadable."""
154
155
155 check_all = True
156 check_all = True
156 """Autoreload all modules, not just those listed in 'modules'"""
157 """Autoreload all modules, not just those listed in 'modules'"""
157
158
158 old_objects = {}
159 old_objects = {}
159 """(module-name, name) -> weakref, for replacing old code objects"""
160 """(module-name, name) -> weakref, for replacing old code objects"""
160
161
161 def mark_module_skipped(self, module_name):
162 def mark_module_skipped(self, module_name):
162 """Skip reloading the named module in the future"""
163 """Skip reloading the named module in the future"""
163 try:
164 try:
164 del self.modules[module_name]
165 del self.modules[module_name]
165 except KeyError:
166 except KeyError:
166 pass
167 pass
167 self.skip_modules[module_name] = True
168 self.skip_modules[module_name] = True
168
169
169 def mark_module_reloadable(self, module_name):
170 def mark_module_reloadable(self, module_name):
170 """Reload the named module in the future (if it is imported)"""
171 """Reload the named module in the future (if it is imported)"""
171 try:
172 try:
172 del self.skip_modules[module_name]
173 del self.skip_modules[module_name]
173 except KeyError:
174 except KeyError:
174 pass
175 pass
175 self.modules[module_name] = True
176 self.modules[module_name] = True
176
177
177 def aimport_module(self, module_name):
178 def aimport_module(self, module_name):
178 """Import a module, and mark it reloadable
179 """Import a module, and mark it reloadable
179
180
180 Returns
181 Returns
181 -------
182 -------
182 top_module : module
183 top_module : module
183 The imported module if it is top-level, or the top-level
184 The imported module if it is top-level, or the top-level
184 top_name : module
185 top_name : module
185 Name of top_module
186 Name of top_module
186
187
187 """
188 """
188 self.mark_module_reloadable(module_name)
189 self.mark_module_reloadable(module_name)
189
190
190 __import__(module_name)
191 __import__(module_name)
191 top_name = module_name.split('.')[0]
192 top_name = module_name.split('.')[0]
192 top_module = sys.modules[top_name]
193 top_module = sys.modules[top_name]
193 return top_module, top_name
194 return top_module, top_name
194
195
195 def check(self, check_all=False):
196 def check(self, check_all=False):
196 """Check whether some modules need to be reloaded."""
197 """Check whether some modules need to be reloaded."""
197
198
198 if not self.enabled and not check_all:
199 if not self.enabled and not check_all:
199 return
200 return
200
201
201 if check_all or self.check_all:
202 if check_all or self.check_all:
202 modules = sys.modules.keys()
203 modules = sys.modules.keys()
203 else:
204 else:
204 modules = self.modules.keys()
205 modules = self.modules.keys()
205
206
206 for modname in modules:
207 for modname in modules:
207 m = sys.modules.get(modname, None)
208 m = sys.modules.get(modname, None)
208
209
209 if modname in self.skip_modules:
210 if modname in self.skip_modules:
210 continue
211 continue
211
212
212 if not hasattr(m, '__file__'):
213 if not hasattr(m, '__file__'):
213 continue
214 continue
214
215
215 if m.__name__ == '__main__':
216 if m.__name__ == '__main__':
216 # we cannot reload(__main__)
217 # we cannot reload(__main__)
217 continue
218 continue
218
219
219 filename = m.__file__
220 filename = m.__file__
220 path, ext = os.path.splitext(filename)
221 path, ext = os.path.splitext(filename)
221
222
222 if ext.lower() == '.py':
223 if ext.lower() == '.py':
223 ext = PY_COMPILED_EXT
224 ext = PY_COMPILED_EXT
224 pyc_filename = pyfile.cache_from_source(filename)
225 pyc_filename = pyfile.cache_from_source(filename)
225 py_filename = filename
226 py_filename = filename
226 else:
227 else:
227 pyc_filename = filename
228 pyc_filename = filename
228 try:
229 try:
229 py_filename = pyfile.source_from_cache(filename)
230 py_filename = pyfile.source_from_cache(filename)
230 except ValueError:
231 except ValueError:
231 continue
232 continue
232
233
233 try:
234 try:
234 pymtime = os.stat(py_filename).st_mtime
235 pymtime = os.stat(py_filename).st_mtime
235 if pymtime <= os.stat(pyc_filename).st_mtime:
236 if pymtime <= os.stat(pyc_filename).st_mtime:
236 continue
237 continue
237 if self.failed.get(py_filename, None) == pymtime:
238 if self.failed.get(py_filename, None) == pymtime:
238 continue
239 continue
239 except OSError:
240 except OSError:
240 continue
241 continue
241
242
242 try:
243 try:
243 superreload(m, reload, self.old_objects)
244 superreload(m, reload, self.old_objects)
244 if py_filename in self.failed:
245 if py_filename in self.failed:
245 del self.failed[py_filename]
246 del self.failed[py_filename]
246 except:
247 except:
247 print >> sys.stderr, "[autoreload of %s failed: %s]" % (
248 print("[autoreload of %s failed: %s]" % (
248 modname, traceback.format_exc(1))
249 modname, traceback.format_exc(1)), file=sys.stderr)
249 self.failed[py_filename] = pymtime
250 self.failed[py_filename] = pymtime
250
251
251 #------------------------------------------------------------------------------
252 #------------------------------------------------------------------------------
252 # superreload
253 # superreload
253 #------------------------------------------------------------------------------
254 #------------------------------------------------------------------------------
254
255
255 if PY3:
256 if PY3:
256 func_attrs = ['__code__', '__defaults__', '__doc__',
257 func_attrs = ['__code__', '__defaults__', '__doc__',
257 '__closure__', '__globals__', '__dict__']
258 '__closure__', '__globals__', '__dict__']
258 else:
259 else:
259 func_attrs = ['func_code', 'func_defaults', 'func_doc',
260 func_attrs = ['func_code', 'func_defaults', 'func_doc',
260 'func_closure', 'func_globals', 'func_dict']
261 'func_closure', 'func_globals', 'func_dict']
261
262
262
263
263 def update_function(old, new):
264 def update_function(old, new):
264 """Upgrade the code object of a function"""
265 """Upgrade the code object of a function"""
265 for name in func_attrs:
266 for name in func_attrs:
266 try:
267 try:
267 setattr(old, name, getattr(new, name))
268 setattr(old, name, getattr(new, name))
268 except (AttributeError, TypeError):
269 except (AttributeError, TypeError):
269 pass
270 pass
270
271
271
272
272 def update_class(old, new):
273 def update_class(old, new):
273 """Replace stuff in the __dict__ of a class, and upgrade
274 """Replace stuff in the __dict__ of a class, and upgrade
274 method code objects"""
275 method code objects"""
275 for key in old.__dict__.keys():
276 for key in old.__dict__.keys():
276 old_obj = getattr(old, key)
277 old_obj = getattr(old, key)
277
278
278 try:
279 try:
279 new_obj = getattr(new, key)
280 new_obj = getattr(new, key)
280 except AttributeError:
281 except AttributeError:
281 # obsolete attribute: remove it
282 # obsolete attribute: remove it
282 try:
283 try:
283 delattr(old, key)
284 delattr(old, key)
284 except (AttributeError, TypeError):
285 except (AttributeError, TypeError):
285 pass
286 pass
286 continue
287 continue
287
288
288 if update_generic(old_obj, new_obj): continue
289 if update_generic(old_obj, new_obj): continue
289
290
290 try:
291 try:
291 setattr(old, key, getattr(new, key))
292 setattr(old, key, getattr(new, key))
292 except (AttributeError, TypeError):
293 except (AttributeError, TypeError):
293 pass # skip non-writable attributes
294 pass # skip non-writable attributes
294
295
295
296
296 def update_property(old, new):
297 def update_property(old, new):
297 """Replace get/set/del functions of a property"""
298 """Replace get/set/del functions of a property"""
298 update_generic(old.fdel, new.fdel)
299 update_generic(old.fdel, new.fdel)
299 update_generic(old.fget, new.fget)
300 update_generic(old.fget, new.fget)
300 update_generic(old.fset, new.fset)
301 update_generic(old.fset, new.fset)
301
302
302
303
303 def isinstance2(a, b, typ):
304 def isinstance2(a, b, typ):
304 return isinstance(a, typ) and isinstance(b, typ)
305 return isinstance(a, typ) and isinstance(b, typ)
305
306
306
307
307 UPDATE_RULES = [
308 UPDATE_RULES = [
308 (lambda a, b: isinstance2(a, b, type),
309 (lambda a, b: isinstance2(a, b, type),
309 update_class),
310 update_class),
310 (lambda a, b: isinstance2(a, b, types.FunctionType),
311 (lambda a, b: isinstance2(a, b, types.FunctionType),
311 update_function),
312 update_function),
312 (lambda a, b: isinstance2(a, b, property),
313 (lambda a, b: isinstance2(a, b, property),
313 update_property),
314 update_property),
314 ]
315 ]
315
316
316
317
317 if PY3:
318 if PY3:
318 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType),
319 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType),
319 lambda a, b: update_function(a.__func__, b.__func__)),
320 lambda a, b: update_function(a.__func__, b.__func__)),
320 ])
321 ])
321 else:
322 else:
322 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
323 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
323 update_class),
324 update_class),
324 (lambda a, b: isinstance2(a, b, types.MethodType),
325 (lambda a, b: isinstance2(a, b, types.MethodType),
325 lambda a, b: update_function(a.im_func, b.im_func)),
326 lambda a, b: update_function(a.im_func, b.im_func)),
326 ])
327 ])
327
328
328
329
329 def update_generic(a, b):
330 def update_generic(a, b):
330 for type_check, update in UPDATE_RULES:
331 for type_check, update in UPDATE_RULES:
331 if type_check(a, b):
332 if type_check(a, b):
332 update(a, b)
333 update(a, b)
333 return True
334 return True
334 return False
335 return False
335
336
336
337
337 class StrongRef(object):
338 class StrongRef(object):
338 def __init__(self, obj):
339 def __init__(self, obj):
339 self.obj = obj
340 self.obj = obj
340 def __call__(self):
341 def __call__(self):
341 return self.obj
342 return self.obj
342
343
343
344
344 def superreload(module, reload=reload, old_objects={}):
345 def superreload(module, reload=reload, old_objects={}):
345 """Enhanced version of the builtin reload function.
346 """Enhanced version of the builtin reload function.
346
347
347 superreload remembers objects previously in the module, and
348 superreload remembers objects previously in the module, and
348
349
349 - upgrades the class dictionary of every old class in the module
350 - upgrades the class dictionary of every old class in the module
350 - upgrades the code object of every old function and method
351 - upgrades the code object of every old function and method
351 - clears the module's namespace before reloading
352 - clears the module's namespace before reloading
352
353
353 """
354 """
354
355
355 # collect old objects in the module
356 # collect old objects in the module
356 for name, obj in module.__dict__.items():
357 for name, obj in module.__dict__.items():
357 if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
358 if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
358 continue
359 continue
359 key = (module.__name__, name)
360 key = (module.__name__, name)
360 try:
361 try:
361 old_objects.setdefault(key, []).append(weakref.ref(obj))
362 old_objects.setdefault(key, []).append(weakref.ref(obj))
362 except TypeError:
363 except TypeError:
363 # weakref doesn't work for all types;
364 # weakref doesn't work for all types;
364 # create strong references for 'important' cases
365 # create strong references for 'important' cases
365 if not PY3 and isinstance(obj, types.ClassType):
366 if not PY3 and isinstance(obj, types.ClassType):
366 old_objects.setdefault(key, []).append(StrongRef(obj))
367 old_objects.setdefault(key, []).append(StrongRef(obj))
367
368
368 # reload module
369 # reload module
369 try:
370 try:
370 # clear namespace first from old cruft
371 # clear namespace first from old cruft
371 old_dict = module.__dict__.copy()
372 old_dict = module.__dict__.copy()
372 old_name = module.__name__
373 old_name = module.__name__
373 module.__dict__.clear()
374 module.__dict__.clear()
374 module.__dict__['__name__'] = old_name
375 module.__dict__['__name__'] = old_name
375 module.__dict__['__loader__'] = old_dict['__loader__']
376 module.__dict__['__loader__'] = old_dict['__loader__']
376 except (TypeError, AttributeError, KeyError):
377 except (TypeError, AttributeError, KeyError):
377 pass
378 pass
378
379
379 try:
380 try:
380 module = reload(module)
381 module = reload(module)
381 except:
382 except:
382 # restore module dictionary on failed reload
383 # restore module dictionary on failed reload
383 module.__dict__.update(old_dict)
384 module.__dict__.update(old_dict)
384 raise
385 raise
385
386
386 # iterate over all objects and update functions & classes
387 # iterate over all objects and update functions & classes
387 for name, new_obj in module.__dict__.items():
388 for name, new_obj in module.__dict__.items():
388 key = (module.__name__, name)
389 key = (module.__name__, name)
389 if key not in old_objects: continue
390 if key not in old_objects: continue
390
391
391 new_refs = []
392 new_refs = []
392 for old_ref in old_objects[key]:
393 for old_ref in old_objects[key]:
393 old_obj = old_ref()
394 old_obj = old_ref()
394 if old_obj is None: continue
395 if old_obj is None: continue
395 new_refs.append(old_ref)
396 new_refs.append(old_ref)
396 update_generic(old_obj, new_obj)
397 update_generic(old_obj, new_obj)
397
398
398 if new_refs:
399 if new_refs:
399 old_objects[key] = new_refs
400 old_objects[key] = new_refs
400 else:
401 else:
401 del old_objects[key]
402 del old_objects[key]
402
403
403 return module
404 return module
404
405
405 #------------------------------------------------------------------------------
406 #------------------------------------------------------------------------------
406 # IPython connectivity
407 # IPython connectivity
407 #------------------------------------------------------------------------------
408 #------------------------------------------------------------------------------
408
409
409 from IPython.core.hooks import TryNext
410 from IPython.core.hooks import TryNext
410 from IPython.core.magic import Magics, magics_class, line_magic
411 from IPython.core.magic import Magics, magics_class, line_magic
411 from IPython.core.plugin import Plugin
412 from IPython.core.plugin import Plugin
412
413
413 @magics_class
414 @magics_class
414 class AutoreloadMagics(Magics):
415 class AutoreloadMagics(Magics):
415 def __init__(self, *a, **kw):
416 def __init__(self, *a, **kw):
416 super(AutoreloadMagics, self).__init__(*a, **kw)
417 super(AutoreloadMagics, self).__init__(*a, **kw)
417 self._reloader = ModuleReloader()
418 self._reloader = ModuleReloader()
418 self._reloader.check_all = False
419 self._reloader.check_all = False
419
420
420 @line_magic
421 @line_magic
421 def autoreload(self, parameter_s=''):
422 def autoreload(self, parameter_s=''):
422 r"""%autoreload => Reload modules automatically
423 r"""%autoreload => Reload modules automatically
423
424
424 %autoreload
425 %autoreload
425 Reload all modules (except those excluded by %aimport) automatically
426 Reload all modules (except those excluded by %aimport) automatically
426 now.
427 now.
427
428
428 %autoreload 0
429 %autoreload 0
429 Disable automatic reloading.
430 Disable automatic reloading.
430
431
431 %autoreload 1
432 %autoreload 1
432 Reload all modules imported with %aimport every time before executing
433 Reload all modules imported with %aimport every time before executing
433 the Python code typed.
434 the Python code typed.
434
435
435 %autoreload 2
436 %autoreload 2
436 Reload all modules (except those excluded by %aimport) every time
437 Reload all modules (except those excluded by %aimport) every time
437 before executing the Python code typed.
438 before executing the Python code typed.
438
439
439 Reloading Python modules in a reliable way is in general
440 Reloading Python modules in a reliable way is in general
440 difficult, and unexpected things may occur. %autoreload tries to
441 difficult, and unexpected things may occur. %autoreload tries to
441 work around common pitfalls by replacing function code objects and
442 work around common pitfalls by replacing function code objects and
442 parts of classes previously in the module with new versions. This
443 parts of classes previously in the module with new versions. This
443 makes the following things to work:
444 makes the following things to work:
444
445
445 - Functions and classes imported via 'from xxx import foo' are upgraded
446 - Functions and classes imported via 'from xxx import foo' are upgraded
446 to new versions when 'xxx' is reloaded.
447 to new versions when 'xxx' is reloaded.
447
448
448 - Methods and properties of classes are upgraded on reload, so that
449 - Methods and properties of classes are upgraded on reload, so that
449 calling 'c.foo()' on an object 'c' created before the reload causes
450 calling 'c.foo()' on an object 'c' created before the reload causes
450 the new code for 'foo' to be executed.
451 the new code for 'foo' to be executed.
451
452
452 Some of the known remaining caveats are:
453 Some of the known remaining caveats are:
453
454
454 - Replacing code objects does not always succeed: changing a @property
455 - Replacing code objects does not always succeed: changing a @property
455 in a class to an ordinary method or a method to a member variable
456 in a class to an ordinary method or a method to a member variable
456 can cause problems (but in old objects only).
457 can cause problems (but in old objects only).
457
458
458 - Functions that are removed (eg. via monkey-patching) from a module
459 - Functions that are removed (eg. via monkey-patching) from a module
459 before it is reloaded are not upgraded.
460 before it is reloaded are not upgraded.
460
461
461 - C extension modules cannot be reloaded, and so cannot be
462 - C extension modules cannot be reloaded, and so cannot be
462 autoreloaded.
463 autoreloaded.
463
464
464 """
465 """
465 if parameter_s == '':
466 if parameter_s == '':
466 self._reloader.check(True)
467 self._reloader.check(True)
467 elif parameter_s == '0':
468 elif parameter_s == '0':
468 self._reloader.enabled = False
469 self._reloader.enabled = False
469 elif parameter_s == '1':
470 elif parameter_s == '1':
470 self._reloader.check_all = False
471 self._reloader.check_all = False
471 self._reloader.enabled = True
472 self._reloader.enabled = True
472 elif parameter_s == '2':
473 elif parameter_s == '2':
473 self._reloader.check_all = True
474 self._reloader.check_all = True
474 self._reloader.enabled = True
475 self._reloader.enabled = True
475
476
476 @line_magic
477 @line_magic
477 def aimport(self, parameter_s='', stream=None):
478 def aimport(self, parameter_s='', stream=None):
478 """%aimport => Import modules for automatic reloading.
479 """%aimport => Import modules for automatic reloading.
479
480
480 %aimport
481 %aimport
481 List modules to automatically import and not to import.
482 List modules to automatically import and not to import.
482
483
483 %aimport foo
484 %aimport foo
484 Import module 'foo' and mark it to be autoreloaded for %autoreload 1
485 Import module 'foo' and mark it to be autoreloaded for %autoreload 1
485
486
486 %aimport -foo
487 %aimport -foo
487 Mark module 'foo' to not be autoreloaded for %autoreload 1
488 Mark module 'foo' to not be autoreloaded for %autoreload 1
488 """
489 """
489 modname = parameter_s
490 modname = parameter_s
490 if not modname:
491 if not modname:
491 to_reload = self._reloader.modules.keys()
492 to_reload = self._reloader.modules.keys()
492 to_reload.sort()
493 to_reload.sort()
493 to_skip = self._reloader.skip_modules.keys()
494 to_skip = self._reloader.skip_modules.keys()
494 to_skip.sort()
495 to_skip.sort()
495 if stream is None:
496 if stream is None:
496 stream = sys.stdout
497 stream = sys.stdout
497 if self._reloader.check_all:
498 if self._reloader.check_all:
498 stream.write("Modules to reload:\nall-except-skipped\n")
499 stream.write("Modules to reload:\nall-except-skipped\n")
499 else:
500 else:
500 stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload))
501 stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload))
501 stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip))
502 stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip))
502 elif modname.startswith('-'):
503 elif modname.startswith('-'):
503 modname = modname[1:]
504 modname = modname[1:]
504 self._reloader.mark_module_skipped(modname)
505 self._reloader.mark_module_skipped(modname)
505 else:
506 else:
506 top_module, top_name = self._reloader.aimport_module(modname)
507 top_module, top_name = self._reloader.aimport_module(modname)
507
508
508 # Inject module to user namespace
509 # Inject module to user namespace
509 self.shell.push({top_name: top_module})
510 self.shell.push({top_name: top_module})
510
511
511 def pre_run_code_hook(self, ip):
512 def pre_run_code_hook(self, ip):
512 if not self._reloader.enabled:
513 if not self._reloader.enabled:
513 raise TryNext
514 raise TryNext
514 try:
515 try:
515 self._reloader.check()
516 self._reloader.check()
516 except:
517 except:
517 pass
518 pass
518
519
519
520
520 class AutoreloadPlugin(Plugin):
521 class AutoreloadPlugin(Plugin):
521 def __init__(self, shell=None, config=None):
522 def __init__(self, shell=None, config=None):
522 super(AutoreloadPlugin, self).__init__(shell=shell, config=config)
523 super(AutoreloadPlugin, self).__init__(shell=shell, config=config)
523 self.auto_magics = AutoreloadMagics(shell)
524 self.auto_magics = AutoreloadMagics(shell)
524 shell.register_magics(self.auto_magics)
525 shell.register_magics(self.auto_magics)
525 shell.set_hook('pre_run_code_hook', self.auto_magics.pre_run_code_hook)
526 shell.set_hook('pre_run_code_hook', self.auto_magics.pre_run_code_hook)
526
527
527
528
528 _loaded = False
529 _loaded = False
529
530
530
531
531 def load_ipython_extension(ip):
532 def load_ipython_extension(ip):
532 """Load the extension in IPython."""
533 """Load the extension in IPython."""
533 global _loaded
534 global _loaded
534 if not _loaded:
535 if not _loaded:
535 plugin = AutoreloadPlugin(shell=ip, config=ip.config)
536 plugin = AutoreloadPlugin(shell=ip, config=ip.config)
536 ip.plugin_manager.register_plugin('autoreload', plugin)
537 ip.plugin_manager.register_plugin('autoreload', plugin)
537 _loaded = True
538 _loaded = True
@@ -1,281 +1,281 b''
1 """
1 """
2 Decorators for labeling and modifying behavior of test objects.
2 Decorators for labeling and modifying behavior of test objects.
3
3
4 Decorators that merely return a modified version of the original
4 Decorators that merely return a modified version of the original
5 function object are straightforward. Decorators that return a new
5 function object are straightforward. Decorators that return a new
6 function object need to use
6 function object need to use
7 ::
7 ::
8
8
9 nose.tools.make_decorator(original_function)(decorator)
9 nose.tools.make_decorator(original_function)(decorator)
10
10
11 in returning the decorator, in order to preserve meta-data such as
11 in returning the decorator, in order to preserve meta-data such as
12 function name, setup and teardown functions and so on - see
12 function name, setup and teardown functions and so on - see
13 ``nose.tools`` for more information.
13 ``nose.tools`` for more information.
14
14
15 """
15 """
16 import warnings
16 import warnings
17
17
18 # IPython changes: make this work if numpy not available
18 # IPython changes: make this work if numpy not available
19 # Original code:
19 # Original code:
20 #from numpy.testing.utils import \
20 #from numpy.testing.utils import \
21 # WarningManager, WarningMessage
21 # WarningManager, WarningMessage
22 # Our version:
22 # Our version:
23 from _numpy_testing_utils import WarningManager
23 from _numpy_testing_utils import WarningManager
24 try:
24 try:
25 from _numpy_testing_noseclasses import KnownFailureTest
25 from _numpy_testing_noseclasses import KnownFailureTest
26 except:
26 except:
27 pass
27 pass
28
28
29 # End IPython changes
29 # End IPython changes
30
30
31 def slow(t):
31 def slow(t):
32 """
32 """
33 Label a test as 'slow'.
33 Label a test as 'slow'.
34
34
35 The exact definition of a slow test is obviously both subjective and
35 The exact definition of a slow test is obviously both subjective and
36 hardware-dependent, but in general any individual test that requires more
36 hardware-dependent, but in general any individual test that requires more
37 than a second or two should be labeled as slow (the whole suite consists of
37 than a second or two should be labeled as slow (the whole suite consists of
38 thousands of tests, so even a second is significant).
38 thousands of tests, so even a second is significant).
39
39
40 Parameters
40 Parameters
41 ----------
41 ----------
42 t : callable
42 t : callable
43 The test to label as slow.
43 The test to label as slow.
44
44
45 Returns
45 Returns
46 -------
46 -------
47 t : callable
47 t : callable
48 The decorated test `t`.
48 The decorated test `t`.
49
49
50 Examples
50 Examples
51 --------
51 --------
52 The `numpy.testing` module includes ``import decorators as dec``.
52 The `numpy.testing` module includes ``import decorators as dec``.
53 A test can be decorated as slow like this::
53 A test can be decorated as slow like this::
54
54
55 from numpy.testing import *
55 from numpy.testing import *
56
56
57 @dec.slow
57 @dec.slow
58 def test_big(self):
58 def test_big(self):
59 print 'Big, slow test'
59 print 'Big, slow test'
60
60
61 """
61 """
62
62
63 t.slow = True
63 t.slow = True
64 return t
64 return t
65
65
66 def setastest(tf=True):
66 def setastest(tf=True):
67 """
67 """
68 Signals to nose that this function is or is not a test.
68 Signals to nose that this function is or is not a test.
69
69
70 Parameters
70 Parameters
71 ----------
71 ----------
72 tf : bool
72 tf : bool
73 If True, specifies that the decorated callable is a test.
73 If True, specifies that the decorated callable is a test.
74 If False, specifies that the decorated callable is not a test.
74 If False, specifies that the decorated callable is not a test.
75 Default is True.
75 Default is True.
76
76
77 Notes
77 Notes
78 -----
78 -----
79 This decorator can't use the nose namespace, because it can be
79 This decorator can't use the nose namespace, because it can be
80 called from a non-test module. See also ``istest`` and ``nottest`` in
80 called from a non-test module. See also ``istest`` and ``nottest`` in
81 ``nose.tools``.
81 ``nose.tools``.
82
82
83 Examples
83 Examples
84 --------
84 --------
85 `setastest` can be used in the following way::
85 `setastest` can be used in the following way::
86
86
87 from numpy.testing.decorators import setastest
87 from numpy.testing.decorators import setastest
88
88
89 @setastest(False)
89 @setastest(False)
90 def func_with_test_in_name(arg1, arg2):
90 def func_with_test_in_name(arg1, arg2):
91 pass
91 pass
92
92
93 """
93 """
94 def set_test(t):
94 def set_test(t):
95 t.__test__ = tf
95 t.__test__ = tf
96 return t
96 return t
97 return set_test
97 return set_test
98
98
99 def skipif(skip_condition, msg=None):
99 def skipif(skip_condition, msg=None):
100 """
100 """
101 Make function raise SkipTest exception if a given condition is true.
101 Make function raise SkipTest exception if a given condition is true.
102
102
103 If the condition is a callable, it is used at runtime to dynamically
103 If the condition is a callable, it is used at runtime to dynamically
104 make the decision. This is useful for tests that may require costly
104 make the decision. This is useful for tests that may require costly
105 imports, to delay the cost until the test suite is actually executed.
105 imports, to delay the cost until the test suite is actually executed.
106
106
107 Parameters
107 Parameters
108 ----------
108 ----------
109 skip_condition : bool or callable
109 skip_condition : bool or callable
110 Flag to determine whether to skip the decorated test.
110 Flag to determine whether to skip the decorated test.
111 msg : str, optional
111 msg : str, optional
112 Message to give on raising a SkipTest exception. Default is None.
112 Message to give on raising a SkipTest exception. Default is None.
113
113
114 Returns
114 Returns
115 -------
115 -------
116 decorator : function
116 decorator : function
117 Decorator which, when applied to a function, causes SkipTest
117 Decorator which, when applied to a function, causes SkipTest
118 to be raised when `skip_condition` is True, and the function
118 to be raised when `skip_condition` is True, and the function
119 to be called normally otherwise.
119 to be called normally otherwise.
120
120
121 Notes
121 Notes
122 -----
122 -----
123 The decorator itself is decorated with the ``nose.tools.make_decorator``
123 The decorator itself is decorated with the ``nose.tools.make_decorator``
124 function in order to transmit function name, and various other metadata.
124 function in order to transmit function name, and various other metadata.
125
125
126 """
126 """
127
127
128 def skip_decorator(f):
128 def skip_decorator(f):
129 # Local import to avoid a hard nose dependency and only incur the
129 # Local import to avoid a hard nose dependency and only incur the
130 # import time overhead at actual test-time.
130 # import time overhead at actual test-time.
131 import nose
131 import nose
132
132
133 # Allow for both boolean or callable skip conditions.
133 # Allow for both boolean or callable skip conditions.
134 if callable(skip_condition):
134 if callable(skip_condition):
135 skip_val = lambda : skip_condition()
135 skip_val = lambda : skip_condition()
136 else:
136 else:
137 skip_val = lambda : skip_condition
137 skip_val = lambda : skip_condition
138
138
139 def get_msg(func,msg=None):
139 def get_msg(func,msg=None):
140 """Skip message with information about function being skipped."""
140 """Skip message with information about function being skipped."""
141 if msg is None:
141 if msg is None:
142 out = 'Test skipped due to test condition'
142 out = 'Test skipped due to test condition'
143 else:
143 else:
144 out = '\n'+msg
144 out = '\n'+msg
145
145
146 return "Skipping test: %s%s" % (func.__name__,out)
146 return "Skipping test: %s%s" % (func.__name__,out)
147
147
148 # We need to define *two* skippers because Python doesn't allow both
148 # We need to define *two* skippers because Python doesn't allow both
149 # return with value and yield inside the same function.
149 # return with value and yield inside the same function.
150 def skipper_func(*args, **kwargs):
150 def skipper_func(*args, **kwargs):
151 """Skipper for normal test functions."""
151 """Skipper for normal test functions."""
152 if skip_val():
152 if skip_val():
153 raise nose.SkipTest(get_msg(f,msg))
153 raise nose.SkipTest(get_msg(f,msg))
154 else:
154 else:
155 return f(*args, **kwargs)
155 return f(*args, **kwargs)
156
156
157 def skipper_gen(*args, **kwargs):
157 def skipper_gen(*args, **kwargs):
158 """Skipper for test generators."""
158 """Skipper for test generators."""
159 if skip_val():
159 if skip_val():
160 raise nose.SkipTest(get_msg(f,msg))
160 raise nose.SkipTest(get_msg(f,msg))
161 else:
161 else:
162 for x in f(*args, **kwargs):
162 for x in f(*args, **kwargs):
163 yield x
163 yield x
164
164
165 # Choose the right skipper to use when building the actual decorator.
165 # Choose the right skipper to use when building the actual decorator.
166 if nose.util.isgenerator(f):
166 if nose.util.isgenerator(f):
167 skipper = skipper_gen
167 skipper = skipper_gen
168 else:
168 else:
169 skipper = skipper_func
169 skipper = skipper_func
170
170
171 return nose.tools.make_decorator(f)(skipper)
171 return nose.tools.make_decorator(f)(skipper)
172
172
173 return skip_decorator
173 return skip_decorator
174
174
175 def knownfailureif(fail_condition, msg=None):
175 def knownfailureif(fail_condition, msg=None):
176 """
176 """
177 Make function raise KnownFailureTest exception if given condition is true.
177 Make function raise KnownFailureTest exception if given condition is true.
178
178
179 If the condition is a callable, it is used at runtime to dynamically
179 If the condition is a callable, it is used at runtime to dynamically
180 make the decision. This is useful for tests that may require costly
180 make the decision. This is useful for tests that may require costly
181 imports, to delay the cost until the test suite is actually executed.
181 imports, to delay the cost until the test suite is actually executed.
182
182
183 Parameters
183 Parameters
184 ----------
184 ----------
185 fail_condition : bool or callable
185 fail_condition : bool or callable
186 Flag to determine whether to mark the decorated test as a known
186 Flag to determine whether to mark the decorated test as a known
187 failure (if True) or not (if False).
187 failure (if True) or not (if False).
188 msg : str, optional
188 msg : str, optional
189 Message to give on raising a KnownFailureTest exception.
189 Message to give on raising a KnownFailureTest exception.
190 Default is None.
190 Default is None.
191
191
192 Returns
192 Returns
193 -------
193 -------
194 decorator : function
194 decorator : function
195 Decorator, which, when applied to a function, causes SkipTest
195 Decorator, which, when applied to a function, causes SkipTest
196 to be raised when `skip_condition` is True, and the function
196 to be raised when `skip_condition` is True, and the function
197 to be called normally otherwise.
197 to be called normally otherwise.
198
198
199 Notes
199 Notes
200 -----
200 -----
201 The decorator itself is decorated with the ``nose.tools.make_decorator``
201 The decorator itself is decorated with the ``nose.tools.make_decorator``
202 function in order to transmit function name, and various other metadata.
202 function in order to transmit function name, and various other metadata.
203
203
204 """
204 """
205 if msg is None:
205 if msg is None:
206 msg = 'Test skipped due to known failure'
206 msg = 'Test skipped due to known failure'
207
207
208 # Allow for both boolean or callable known failure conditions.
208 # Allow for both boolean or callable known failure conditions.
209 if callable(fail_condition):
209 if callable(fail_condition):
210 fail_val = lambda : fail_condition()
210 fail_val = lambda : fail_condition()
211 else:
211 else:
212 fail_val = lambda : fail_condition
212 fail_val = lambda : fail_condition
213
213
214 def knownfail_decorator(f):
214 def knownfail_decorator(f):
215 # Local import to avoid a hard nose dependency and only incur the
215 # Local import to avoid a hard nose dependency and only incur the
216 # import time overhead at actual test-time.
216 # import time overhead at actual test-time.
217 import nose
217 import nose
218 def knownfailer(*args, **kwargs):
218 def knownfailer(*args, **kwargs):
219 if fail_val():
219 if fail_val():
220 raise KnownFailureTest, msg
220 raise KnownFailureTest(msg)
221 else:
221 else:
222 return f(*args, **kwargs)
222 return f(*args, **kwargs)
223 return nose.tools.make_decorator(f)(knownfailer)
223 return nose.tools.make_decorator(f)(knownfailer)
224
224
225 return knownfail_decorator
225 return knownfail_decorator
226
226
227 def deprecated(conditional=True):
227 def deprecated(conditional=True):
228 """
228 """
229 Filter deprecation warnings while running the test suite.
229 Filter deprecation warnings while running the test suite.
230
230
231 This decorator can be used to filter DeprecationWarning's, to avoid
231 This decorator can be used to filter DeprecationWarning's, to avoid
232 printing them during the test suite run, while checking that the test
232 printing them during the test suite run, while checking that the test
233 actually raises a DeprecationWarning.
233 actually raises a DeprecationWarning.
234
234
235 Parameters
235 Parameters
236 ----------
236 ----------
237 conditional : bool or callable, optional
237 conditional : bool or callable, optional
238 Flag to determine whether to mark test as deprecated or not. If the
238 Flag to determine whether to mark test as deprecated or not. If the
239 condition is a callable, it is used at runtime to dynamically make the
239 condition is a callable, it is used at runtime to dynamically make the
240 decision. Default is True.
240 decision. Default is True.
241
241
242 Returns
242 Returns
243 -------
243 -------
244 decorator : function
244 decorator : function
245 The `deprecated` decorator itself.
245 The `deprecated` decorator itself.
246
246
247 Notes
247 Notes
248 -----
248 -----
249 .. versionadded:: 1.4.0
249 .. versionadded:: 1.4.0
250
250
251 """
251 """
252 def deprecate_decorator(f):
252 def deprecate_decorator(f):
253 # Local import to avoid a hard nose dependency and only incur the
253 # Local import to avoid a hard nose dependency and only incur the
254 # import time overhead at actual test-time.
254 # import time overhead at actual test-time.
255 import nose
255 import nose
256
256
257 def _deprecated_imp(*args, **kwargs):
257 def _deprecated_imp(*args, **kwargs):
258 # Poor man's replacement for the with statement
258 # Poor man's replacement for the with statement
259 ctx = WarningManager(record=True)
259 ctx = WarningManager(record=True)
260 l = ctx.__enter__()
260 l = ctx.__enter__()
261 warnings.simplefilter('always')
261 warnings.simplefilter('always')
262 try:
262 try:
263 f(*args, **kwargs)
263 f(*args, **kwargs)
264 if not len(l) > 0:
264 if not len(l) > 0:
265 raise AssertionError("No warning raised when calling %s"
265 raise AssertionError("No warning raised when calling %s"
266 % f.__name__)
266 % f.__name__)
267 if not l[0].category is DeprecationWarning:
267 if not l[0].category is DeprecationWarning:
268 raise AssertionError("First warning for %s is not a " \
268 raise AssertionError("First warning for %s is not a " \
269 "DeprecationWarning( is %s)" % (f.__name__, l[0]))
269 "DeprecationWarning( is %s)" % (f.__name__, l[0]))
270 finally:
270 finally:
271 ctx.__exit__()
271 ctx.__exit__()
272
272
273 if callable(conditional):
273 if callable(conditional):
274 cond = conditional()
274 cond = conditional()
275 else:
275 else:
276 cond = conditional
276 cond = conditional
277 if cond:
277 if cond:
278 return nose.tools.make_decorator(f)(_deprecated_imp)
278 return nose.tools.make_decorator(f)(_deprecated_imp)
279 else:
279 else:
280 return f
280 return f
281 return deprecate_decorator
281 return deprecate_decorator
@@ -1,1900 +1,1900 b''
1 """Pexpect is a Python module for spawning child applications and controlling
1 """Pexpect is a Python module for spawning child applications and controlling
2 them automatically. Pexpect can be used for automating interactive applications
2 them automatically. Pexpect can be used for automating interactive applications
3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
3 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4 scripts for duplicating software package installations on different servers. It
4 scripts for duplicating software package installations on different servers. It
5 can be used for automated software testing. Pexpect is in the spirit of Don
5 can be used for automated software testing. Pexpect is in the spirit of Don
6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
6 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
7 require TCL and Expect or require C extensions to be compiled. Pexpect does not
8 use C, Expect, or TCL extensions. It should work on any platform that supports
8 use C, Expect, or TCL extensions. It should work on any platform that supports
9 the standard Python pty module. The Pexpect interface focuses on ease of use so
9 the standard Python pty module. The Pexpect interface focuses on ease of use so
10 that simple tasks are easy.
10 that simple tasks are easy.
11
11
12 There are two main interfaces to the Pexpect system; these are the function,
12 There are two main interfaces to the Pexpect system; these are the function,
13 run() and the class, spawn. The spawn class is more powerful. The run()
13 run() and the class, spawn. The spawn class is more powerful. The run()
14 function is simpler than spawn, and is good for quickly calling program. When
14 function is simpler than spawn, and is good for quickly calling program. When
15 you call the run() function it executes a given program and then returns the
15 you call the run() function it executes a given program and then returns the
16 output. This is a handy replacement for os.system().
16 output. This is a handy replacement for os.system().
17
17
18 For example::
18 For example::
19
19
20 pexpect.run('ls -la')
20 pexpect.run('ls -la')
21
21
22 The spawn class is the more powerful interface to the Pexpect system. You can
22 The spawn class is the more powerful interface to the Pexpect system. You can
23 use this to spawn a child program then interact with it by sending input and
23 use this to spawn a child program then interact with it by sending input and
24 expecting responses (waiting for patterns in the child's output).
24 expecting responses (waiting for patterns in the child's output).
25
25
26 For example::
26 For example::
27
27
28 child = pexpect.spawn('scp foo myname@host.example.com:.')
28 child = pexpect.spawn('scp foo myname@host.example.com:.')
29 child.expect ('Password:')
29 child.expect ('Password:')
30 child.sendline (mypassword)
30 child.sendline (mypassword)
31
31
32 This works even for commands that ask for passwords or other input outside of
32 This works even for commands that ask for passwords or other input outside of
33 the normal stdio streams. For example, ssh reads input directly from the TTY
33 the normal stdio streams. For example, ssh reads input directly from the TTY
34 device which bypasses stdin.
34 device which bypasses stdin.
35
35
36 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
36 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
37 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
37 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
38 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
38 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
39 Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
39 Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
40 Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
40 Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
41 Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
41 Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
42 Spiegel, Jan Grant, Shane Kerr and Thomas Kluyver. Let me know if I forgot anyone.
42 Spiegel, Jan Grant, Shane Kerr and Thomas Kluyver. Let me know if I forgot anyone.
43
43
44 Pexpect is free, open source, and all that good stuff.
44 Pexpect is free, open source, and all that good stuff.
45
45
46 Permission is hereby granted, free of charge, to any person obtaining a copy of
46 Permission is hereby granted, free of charge, to any person obtaining a copy of
47 this software and associated documentation files (the "Software"), to deal in
47 this software and associated documentation files (the "Software"), to deal in
48 the Software without restriction, including without limitation the rights to
48 the Software without restriction, including without limitation the rights to
49 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
49 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
50 of the Software, and to permit persons to whom the Software is furnished to do
50 of the Software, and to permit persons to whom the Software is furnished to do
51 so, subject to the following conditions:
51 so, subject to the following conditions:
52
52
53 The above copyright notice and this permission notice shall be included in all
53 The above copyright notice and this permission notice shall be included in all
54 copies or substantial portions of the Software.
54 copies or substantial portions of the Software.
55
55
56 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
56 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
57 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
57 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
58 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
58 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
59 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
59 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
60 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
60 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
61 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
61 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
62 SOFTWARE.
62 SOFTWARE.
63
63
64 Pexpect Copyright (c) 2008-2011 Noah Spurrier
64 Pexpect Copyright (c) 2008-2011 Noah Spurrier
65 http://pexpect.sourceforge.net/
65 http://pexpect.sourceforge.net/
66 """
66 """
67
67
68 try:
68 try:
69 import os, sys, time
69 import os, sys, time
70 import select
70 import select
71 import re
71 import re
72 import struct
72 import struct
73 import resource
73 import resource
74 import types
74 import types
75 import pty
75 import pty
76 import tty
76 import tty
77 import termios
77 import termios
78 import fcntl
78 import fcntl
79 import errno
79 import errno
80 import traceback
80 import traceback
81 import signal
81 import signal
82 except ImportError as e:
82 except ImportError as e:
83 raise ImportError (str(e) + """
83 raise ImportError (str(e) + """
84
84
85 A critical module was not found. Probably this operating system does not
85 A critical module was not found. Probably this operating system does not
86 support it. Pexpect is intended for UNIX-like operating systems.""")
86 support it. Pexpect is intended for UNIX-like operating systems.""")
87
87
88 __version__ = '2.6.dev'
88 __version__ = '2.6.dev'
89 version = __version__
89 version = __version__
90 version_info = (2,6,'dev')
90 version_info = (2,6,'dev')
91 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which',
91 __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which',
92 'split_command_line', '__version__']
92 'split_command_line', '__version__']
93
93
94 # Exception classes used by this module.
94 # Exception classes used by this module.
95 class ExceptionPexpect(Exception):
95 class ExceptionPexpect(Exception):
96
96
97 """Base class for all exceptions raised by this module.
97 """Base class for all exceptions raised by this module.
98 """
98 """
99
99
100 def __init__(self, value):
100 def __init__(self, value):
101
101
102 self.value = value
102 self.value = value
103
103
104 def __str__(self):
104 def __str__(self):
105
105
106 return str(self.value)
106 return str(self.value)
107
107
108 def get_trace(self):
108 def get_trace(self):
109
109
110 """This returns an abbreviated stack trace with lines that only concern
110 """This returns an abbreviated stack trace with lines that only concern
111 the caller. In other words, the stack trace inside the Pexpect module
111 the caller. In other words, the stack trace inside the Pexpect module
112 is not included. """
112 is not included. """
113
113
114 tblist = traceback.extract_tb(sys.exc_info()[2])
114 tblist = traceback.extract_tb(sys.exc_info()[2])
115 #tblist = filter(self.__filter_not_pexpect, tblist)
115 #tblist = filter(self.__filter_not_pexpect, tblist)
116 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
116 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
117 tblist = traceback.format_list(tblist)
117 tblist = traceback.format_list(tblist)
118 return ''.join(tblist)
118 return ''.join(tblist)
119
119
120 def __filter_not_pexpect(self, trace_list_item):
120 def __filter_not_pexpect(self, trace_list_item):
121
121
122 """This returns True if list item 0 the string 'pexpect.py' in it. """
122 """This returns True if list item 0 the string 'pexpect.py' in it. """
123
123
124 if trace_list_item[0].find('pexpect.py') == -1:
124 if trace_list_item[0].find('pexpect.py') == -1:
125 return True
125 return True
126 else:
126 else:
127 return False
127 return False
128
128
129 class EOF(ExceptionPexpect):
129 class EOF(ExceptionPexpect):
130
130
131 """Raised when EOF is read from a child. This usually means the child has exited."""
131 """Raised when EOF is read from a child. This usually means the child has exited."""
132
132
133 class TIMEOUT(ExceptionPexpect):
133 class TIMEOUT(ExceptionPexpect):
134
134
135 """Raised when a read time exceeds the timeout. """
135 """Raised when a read time exceeds the timeout. """
136
136
137 ##class TIMEOUT_PATTERN(TIMEOUT):
137 ##class TIMEOUT_PATTERN(TIMEOUT):
138 ## """Raised when the pattern match time exceeds the timeout.
138 ## """Raised when the pattern match time exceeds the timeout.
139 ## This is different than a read TIMEOUT because the child process may
139 ## This is different than a read TIMEOUT because the child process may
140 ## give output, thus never give a TIMEOUT, but the output
140 ## give output, thus never give a TIMEOUT, but the output
141 ## may never match a pattern.
141 ## may never match a pattern.
142 ## """
142 ## """
143 ##class MAXBUFFER(ExceptionPexpect):
143 ##class MAXBUFFER(ExceptionPexpect):
144 ## """Raised when a scan buffer fills before matching an expected pattern."""
144 ## """Raised when a scan buffer fills before matching an expected pattern."""
145
145
146 PY3 = (sys.version_info[0] >= 3)
146 PY3 = (sys.version_info[0] >= 3)
147
147
148 def _cast_bytes(s, enc):
148 def _cast_bytes(s, enc):
149 if isinstance(s, unicode):
149 if isinstance(s, unicode):
150 return s.encode(enc)
150 return s.encode(enc)
151 return s
151 return s
152
152
153 def _cast_unicode(s, enc):
153 def _cast_unicode(s, enc):
154 if isinstance(s, bytes):
154 if isinstance(s, bytes):
155 return s.decode(enc)
155 return s.decode(enc)
156 return s
156 return s
157
157
158 re_type = type(re.compile(''))
158 re_type = type(re.compile(''))
159
159
160 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None,
160 def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None,
161 logfile=None, cwd=None, env=None, encoding='utf-8'):
161 logfile=None, cwd=None, env=None, encoding='utf-8'):
162
162
163 """
163 """
164 This function runs the given command; waits for it to finish; then
164 This function runs the given command; waits for it to finish; then
165 returns all output as a string. STDERR is included in output. If the full
165 returns all output as a string. STDERR is included in output. If the full
166 path to the command is not given then the path is searched.
166 path to the command is not given then the path is searched.
167
167
168 Note that lines are terminated by CR/LF (\\r\\n) combination even on
168 Note that lines are terminated by CR/LF (\\r\\n) combination even on
169 UNIX-like systems because this is the standard for pseudo ttys. If you set
169 UNIX-like systems because this is the standard for pseudo ttys. If you set
170 'withexitstatus' to true, then run will return a tuple of (command_output,
170 'withexitstatus' to true, then run will return a tuple of (command_output,
171 exitstatus). If 'withexitstatus' is false then this returns just
171 exitstatus). If 'withexitstatus' is false then this returns just
172 command_output.
172 command_output.
173
173
174 The run() function can often be used instead of creating a spawn instance.
174 The run() function can often be used instead of creating a spawn instance.
175 For example, the following code uses spawn::
175 For example, the following code uses spawn::
176
176
177 from pexpect import *
177 from pexpect import *
178 child = spawn('scp foo myname@host.example.com:.')
178 child = spawn('scp foo myname@host.example.com:.')
179 child.expect ('(?i)password')
179 child.expect ('(?i)password')
180 child.sendline (mypassword)
180 child.sendline (mypassword)
181
181
182 The previous code can be replace with the following::
182 The previous code can be replace with the following::
183
183
184 from pexpect import *
184 from pexpect import *
185 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
185 run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})
186
186
187 Examples
187 Examples
188 ========
188 ========
189
189
190 Start the apache daemon on the local machine::
190 Start the apache daemon on the local machine::
191
191
192 from pexpect import *
192 from pexpect import *
193 run ("/usr/local/apache/bin/apachectl start")
193 run ("/usr/local/apache/bin/apachectl start")
194
194
195 Check in a file using SVN::
195 Check in a file using SVN::
196
196
197 from pexpect import *
197 from pexpect import *
198 run ("svn ci -m 'automatic commit' my_file.py")
198 run ("svn ci -m 'automatic commit' my_file.py")
199
199
200 Run a command and capture exit status::
200 Run a command and capture exit status::
201
201
202 from pexpect import *
202 from pexpect import *
203 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
203 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
204
204
205 Tricky Examples
205 Tricky Examples
206 ===============
206 ===============
207
207
208 The following will run SSH and execute 'ls -l' on the remote machine. The
208 The following will run SSH and execute 'ls -l' on the remote machine. The
209 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
209 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
210
210
211 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
211 run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'})
212
212
213 This will start mencoder to rip a video from DVD. This will also display
213 This will start mencoder to rip a video from DVD. This will also display
214 progress ticks every 5 seconds as it runs. For example::
214 progress ticks every 5 seconds as it runs. For example::
215
215
216 from pexpect import *
216 from pexpect import *
217 def print_ticks(d):
217 def print_ticks(d):
218 print d['event_count'],
218 print d['event_count'],
219 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
219 run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
220
220
221 The 'events' argument should be a dictionary of patterns and responses.
221 The 'events' argument should be a dictionary of patterns and responses.
222 Whenever one of the patterns is seen in the command out run() will send the
222 Whenever one of the patterns is seen in the command out run() will send the
223 associated response string. Note that you should put newlines in your
223 associated response string. Note that you should put newlines in your
224 string if Enter is necessary. The responses may also contain callback
224 string if Enter is necessary. The responses may also contain callback
225 functions. Any callback is function that takes a dictionary as an argument.
225 functions. Any callback is function that takes a dictionary as an argument.
226 The dictionary contains all the locals from the run() function, so you can
226 The dictionary contains all the locals from the run() function, so you can
227 access the child spawn object or any other variable defined in run()
227 access the child spawn object or any other variable defined in run()
228 (event_count, child, and extra_args are the most useful). A callback may
228 (event_count, child, and extra_args are the most useful). A callback may
229 return True to stop the current run process otherwise run() continues until
229 return True to stop the current run process otherwise run() continues until
230 the next event. A callback may also return a string which will be sent to
230 the next event. A callback may also return a string which will be sent to
231 the child. 'extra_args' is not used by directly run(). It provides a way to
231 the child. 'extra_args' is not used by directly run(). It provides a way to
232 pass data to a callback function through run() through the locals
232 pass data to a callback function through run() through the locals
233 dictionary passed to a callback."""
233 dictionary passed to a callback."""
234
234
235 if timeout == -1:
235 if timeout == -1:
236 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
236 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
237 encoding=encoding)
237 encoding=encoding)
238 else:
238 else:
239 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
239 child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
240 cwd=cwd, env=env, encoding=encoding)
240 cwd=cwd, env=env, encoding=encoding)
241 if events is not None:
241 if events is not None:
242 patterns = events.keys()
242 patterns = events.keys()
243 responses = events.values()
243 responses = events.values()
244 else:
244 else:
245 patterns=None # We assume that EOF or TIMEOUT will save us.
245 patterns=None # We assume that EOF or TIMEOUT will save us.
246 responses=None
246 responses=None
247 child_result_list = []
247 child_result_list = []
248 event_count = 0
248 event_count = 0
249 while 1:
249 while 1:
250 try:
250 try:
251 index = child.expect (patterns)
251 index = child.expect (patterns)
252 if isinstance(child.after, basestring):
252 if isinstance(child.after, basestring):
253 child_result_list.append(child.before + child.after)
253 child_result_list.append(child.before + child.after)
254 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
254 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
255 child_result_list.append(child.before)
255 child_result_list.append(child.before)
256 if isinstance(responses[index], basestring):
256 if isinstance(responses[index], basestring):
257 child.send(responses[index])
257 child.send(responses[index])
258 elif type(responses[index]) is types.FunctionType:
258 elif type(responses[index]) is types.FunctionType:
259 callback_result = responses[index](locals())
259 callback_result = responses[index](locals())
260 sys.stdout.flush()
260 sys.stdout.flush()
261 if isinstance(callback_result, basestring):
261 if isinstance(callback_result, basestring):
262 child.send(callback_result)
262 child.send(callback_result)
263 elif callback_result:
263 elif callback_result:
264 break
264 break
265 else:
265 else:
266 raise TypeError ('The callback must be a string or function type.')
266 raise TypeError ('The callback must be a string or function type.')
267 event_count = event_count + 1
267 event_count = event_count + 1
268 except TIMEOUT as e:
268 except TIMEOUT as e:
269 child_result_list.append(child.before)
269 child_result_list.append(child.before)
270 break
270 break
271 except EOF as e:
271 except EOF as e:
272 child_result_list.append(child.before)
272 child_result_list.append(child.before)
273 break
273 break
274 child_result = child._empty_buffer.join(child_result_list)
274 child_result = child._empty_buffer.join(child_result_list)
275 if withexitstatus:
275 if withexitstatus:
276 child.close()
276 child.close()
277 return (child_result, child.exitstatus)
277 return (child_result, child.exitstatus)
278 else:
278 else:
279 return child_result
279 return child_result
280
280
281 class spawnb(object):
281 class spawnb(object):
282 """Use this class to start and control child applications with a pure-bytes
282 """Use this class to start and control child applications with a pure-bytes
283 interface."""
283 interface."""
284
284
285 _buffer_type = bytes
285 _buffer_type = bytes
286 def _cast_buffer_type(self, s):
286 def _cast_buffer_type(self, s):
287 return _cast_bytes(s, self.encoding)
287 return _cast_bytes(s, self.encoding)
288 _empty_buffer = b''
288 _empty_buffer = b''
289 _pty_newline = b'\r\n'
289 _pty_newline = b'\r\n'
290
290
291 # Some code needs this to exist, but it's mainly for the spawn subclass.
291 # Some code needs this to exist, but it's mainly for the spawn subclass.
292 encoding = 'utf-8'
292 encoding = 'utf-8'
293
293
294 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None,
294 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None,
295 logfile=None, cwd=None, env=None):
295 logfile=None, cwd=None, env=None):
296
296
297 """This is the constructor. The command parameter may be a string that
297 """This is the constructor. The command parameter may be a string that
298 includes a command and any arguments to the command. For example::
298 includes a command and any arguments to the command. For example::
299
299
300 child = pexpect.spawn ('/usr/bin/ftp')
300 child = pexpect.spawn ('/usr/bin/ftp')
301 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
301 child = pexpect.spawn ('/usr/bin/ssh user@example.com')
302 child = pexpect.spawn ('ls -latr /tmp')
302 child = pexpect.spawn ('ls -latr /tmp')
303
303
304 You may also construct it with a list of arguments like so::
304 You may also construct it with a list of arguments like so::
305
305
306 child = pexpect.spawn ('/usr/bin/ftp', [])
306 child = pexpect.spawn ('/usr/bin/ftp', [])
307 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
307 child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
308 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
308 child = pexpect.spawn ('ls', ['-latr', '/tmp'])
309
309
310 After this the child application will be created and will be ready to
310 After this the child application will be created and will be ready to
311 talk to. For normal use, see expect() and send() and sendline().
311 talk to. For normal use, see expect() and send() and sendline().
312
312
313 Remember that Pexpect does NOT interpret shell meta characters such as
313 Remember that Pexpect does NOT interpret shell meta characters such as
314 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
314 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
315 If you want to run a command and pipe it through another command then
315 If you want to run a command and pipe it through another command then
316 you must also start a shell. For example::
316 you must also start a shell. For example::
317
317
318 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
318 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
319 child.expect(pexpect.EOF)
319 child.expect(pexpect.EOF)
320
320
321 The second form of spawn (where you pass a list of arguments) is useful
321 The second form of spawn (where you pass a list of arguments) is useful
322 in situations where you wish to spawn a command and pass it its own
322 in situations where you wish to spawn a command and pass it its own
323 argument list. This can make syntax more clear. For example, the
323 argument list. This can make syntax more clear. For example, the
324 following is equivalent to the previous example::
324 following is equivalent to the previous example::
325
325
326 shell_cmd = 'ls -l | grep LOG > log_list.txt'
326 shell_cmd = 'ls -l | grep LOG > log_list.txt'
327 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
327 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
328 child.expect(pexpect.EOF)
328 child.expect(pexpect.EOF)
329
329
330 The maxread attribute sets the read buffer size. This is maximum number
330 The maxread attribute sets the read buffer size. This is maximum number
331 of bytes that Pexpect will try to read from a TTY at one time. Setting
331 of bytes that Pexpect will try to read from a TTY at one time. Setting
332 the maxread size to 1 will turn off buffering. Setting the maxread
332 the maxread size to 1 will turn off buffering. Setting the maxread
333 value higher may help performance in cases where large amounts of
333 value higher may help performance in cases where large amounts of
334 output are read back from the child. This feature is useful in
334 output are read back from the child. This feature is useful in
335 conjunction with searchwindowsize.
335 conjunction with searchwindowsize.
336
336
337 The searchwindowsize attribute sets the how far back in the incomming
337 The searchwindowsize attribute sets the how far back in the incomming
338 seach buffer Pexpect will search for pattern matches. Every time
338 seach buffer Pexpect will search for pattern matches. Every time
339 Pexpect reads some data from the child it will append the data to the
339 Pexpect reads some data from the child it will append the data to the
340 incomming buffer. The default is to search from the beginning of the
340 incomming buffer. The default is to search from the beginning of the
341 imcomming buffer each time new data is read from the child. But this is
341 imcomming buffer each time new data is read from the child. But this is
342 very inefficient if you are running a command that generates a large
342 very inefficient if you are running a command that generates a large
343 amount of data where you want to match The searchwindowsize does not
343 amount of data where you want to match The searchwindowsize does not
344 effect the size of the incomming data buffer. You will still have
344 effect the size of the incomming data buffer. You will still have
345 access to the full buffer after expect() returns.
345 access to the full buffer after expect() returns.
346
346
347 The logfile member turns on or off logging. All input and output will
347 The logfile member turns on or off logging. All input and output will
348 be copied to the given file object. Set logfile to None to stop
348 be copied to the given file object. Set logfile to None to stop
349 logging. This is the default. Set logfile to sys.stdout to echo
349 logging. This is the default. Set logfile to sys.stdout to echo
350 everything to standard output. The logfile is flushed after each write.
350 everything to standard output. The logfile is flushed after each write.
351
351
352 Example log input and output to a file::
352 Example log input and output to a file::
353
353
354 child = pexpect.spawn('some_command')
354 child = pexpect.spawn('some_command')
355 fout = open('mylog.txt','w')
355 fout = open('mylog.txt','w')
356 child.logfile = fout
356 child.logfile = fout
357
357
358 Example log to stdout::
358 Example log to stdout::
359
359
360 child = pexpect.spawn('some_command')
360 child = pexpect.spawn('some_command')
361 child.logfile = sys.stdout
361 child.logfile = sys.stdout
362
362
363 The logfile_read and logfile_send members can be used to separately log
363 The logfile_read and logfile_send members can be used to separately log
364 the input from the child and output sent to the child. Sometimes you
364 the input from the child and output sent to the child. Sometimes you
365 don't want to see everything you write to the child. You only want to
365 don't want to see everything you write to the child. You only want to
366 log what the child sends back. For example::
366 log what the child sends back. For example::
367
367
368 child = pexpect.spawn('some_command')
368 child = pexpect.spawn('some_command')
369 child.logfile_read = sys.stdout
369 child.logfile_read = sys.stdout
370
370
371 To separately log output sent to the child use logfile_send::
371 To separately log output sent to the child use logfile_send::
372
372
373 self.logfile_send = fout
373 self.logfile_send = fout
374
374
375 The delaybeforesend helps overcome a weird behavior that many users
375 The delaybeforesend helps overcome a weird behavior that many users
376 were experiencing. The typical problem was that a user would expect() a
376 were experiencing. The typical problem was that a user would expect() a
377 "Password:" prompt and then immediately call sendline() to send the
377 "Password:" prompt and then immediately call sendline() to send the
378 password. The user would then see that their password was echoed back
378 password. The user would then see that their password was echoed back
379 to them. Passwords don't normally echo. The problem is caused by the
379 to them. Passwords don't normally echo. The problem is caused by the
380 fact that most applications print out the "Password" prompt and then
380 fact that most applications print out the "Password" prompt and then
381 turn off stdin echo, but if you send your password before the
381 turn off stdin echo, but if you send your password before the
382 application turned off echo, then you get your password echoed.
382 application turned off echo, then you get your password echoed.
383 Normally this wouldn't be a problem when interacting with a human at a
383 Normally this wouldn't be a problem when interacting with a human at a
384 real keyboard. If you introduce a slight delay just before writing then
384 real keyboard. If you introduce a slight delay just before writing then
385 this seems to clear up the problem. This was such a common problem for
385 this seems to clear up the problem. This was such a common problem for
386 many users that I decided that the default pexpect behavior should be
386 many users that I decided that the default pexpect behavior should be
387 to sleep just before writing to the child application. 1/20th of a
387 to sleep just before writing to the child application. 1/20th of a
388 second (50 ms) seems to be enough to clear up the problem. You can set
388 second (50 ms) seems to be enough to clear up the problem. You can set
389 delaybeforesend to 0 to return to the old behavior. Most Linux machines
389 delaybeforesend to 0 to return to the old behavior. Most Linux machines
390 don't like this to be below 0.03. I don't know why.
390 don't like this to be below 0.03. I don't know why.
391
391
392 Note that spawn is clever about finding commands on your path.
392 Note that spawn is clever about finding commands on your path.
393 It uses the same logic that "which" uses to find executables.
393 It uses the same logic that "which" uses to find executables.
394
394
395 If you wish to get the exit status of the child you must call the
395 If you wish to get the exit status of the child you must call the
396 close() method. The exit or signal status of the child will be stored
396 close() method. The exit or signal status of the child will be stored
397 in self.exitstatus or self.signalstatus. If the child exited normally
397 in self.exitstatus or self.signalstatus. If the child exited normally
398 then exitstatus will store the exit return code and signalstatus will
398 then exitstatus will store the exit return code and signalstatus will
399 be None. If the child was terminated abnormally with a signal then
399 be None. If the child was terminated abnormally with a signal then
400 signalstatus will store the signal value and exitstatus will be None.
400 signalstatus will store the signal value and exitstatus will be None.
401 If you need more detail you can also read the self.status member which
401 If you need more detail you can also read the self.status member which
402 stores the status returned by os.waitpid. You can interpret this using
402 stores the status returned by os.waitpid. You can interpret this using
403 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
403 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
404
404
405 self.STDIN_FILENO = pty.STDIN_FILENO
405 self.STDIN_FILENO = pty.STDIN_FILENO
406 self.STDOUT_FILENO = pty.STDOUT_FILENO
406 self.STDOUT_FILENO = pty.STDOUT_FILENO
407 self.STDERR_FILENO = pty.STDERR_FILENO
407 self.STDERR_FILENO = pty.STDERR_FILENO
408 self.stdin = sys.stdin
408 self.stdin = sys.stdin
409 self.stdout = sys.stdout
409 self.stdout = sys.stdout
410 self.stderr = sys.stderr
410 self.stderr = sys.stderr
411
411
412 self.searcher = None
412 self.searcher = None
413 self.ignorecase = False
413 self.ignorecase = False
414 self.before = None
414 self.before = None
415 self.after = None
415 self.after = None
416 self.match = None
416 self.match = None
417 self.match_index = None
417 self.match_index = None
418 self.terminated = True
418 self.terminated = True
419 self.exitstatus = None
419 self.exitstatus = None
420 self.signalstatus = None
420 self.signalstatus = None
421 self.status = None # status returned by os.waitpid
421 self.status = None # status returned by os.waitpid
422 self.flag_eof = False
422 self.flag_eof = False
423 self.pid = None
423 self.pid = None
424 self.child_fd = -1 # initially closed
424 self.child_fd = -1 # initially closed
425 self.timeout = timeout
425 self.timeout = timeout
426 self.delimiter = EOF
426 self.delimiter = EOF
427 self.logfile = logfile
427 self.logfile = logfile
428 self.logfile_read = None # input from child (read_nonblocking)
428 self.logfile_read = None # input from child (read_nonblocking)
429 self.logfile_send = None # output to send (send, sendline)
429 self.logfile_send = None # output to send (send, sendline)
430 self.maxread = maxread # max bytes to read at one time into buffer
430 self.maxread = maxread # max bytes to read at one time into buffer
431 self.buffer = self._empty_buffer # This is the read buffer. See maxread.
431 self.buffer = self._empty_buffer # This is the read buffer. See maxread.
432 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
432 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched.
433 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
433 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
434 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
434 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds.
435 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
435 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds.
436 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
436 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds.
437 self.softspace = False # File-like object.
437 self.softspace = False # File-like object.
438 self.name = '<' + repr(self) + '>' # File-like object.
438 self.name = '<' + repr(self) + '>' # File-like object.
439 self.closed = True # File-like object.
439 self.closed = True # File-like object.
440 self.cwd = cwd
440 self.cwd = cwd
441 self.env = env
441 self.env = env
442 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
442 self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix
443 # Solaris uses internal __fork_pty(). All others use pty.fork().
443 # Solaris uses internal __fork_pty(). All others use pty.fork().
444 if 'solaris' in sys.platform.lower() or 'sunos5' in sys.platform.lower():
444 if 'solaris' in sys.platform.lower() or 'sunos5' in sys.platform.lower():
445 self.use_native_pty_fork = False
445 self.use_native_pty_fork = False
446 else:
446 else:
447 self.use_native_pty_fork = True
447 self.use_native_pty_fork = True
448
448
449
449
450 # allow dummy instances for subclasses that may not use command or args.
450 # allow dummy instances for subclasses that may not use command or args.
451 if command is None:
451 if command is None:
452 self.command = None
452 self.command = None
453 self.args = None
453 self.args = None
454 self.name = '<pexpect factory incomplete>'
454 self.name = '<pexpect factory incomplete>'
455 else:
455 else:
456 self._spawn (command, args)
456 self._spawn (command, args)
457
457
458 def __del__(self):
458 def __del__(self):
459
459
460 """This makes sure that no system resources are left open. Python only
460 """This makes sure that no system resources are left open. Python only
461 garbage collects Python objects. OS file descriptors are not Python
461 garbage collects Python objects. OS file descriptors are not Python
462 objects, so they must be handled explicitly. If the child file
462 objects, so they must be handled explicitly. If the child file
463 descriptor was opened outside of this class (passed to the constructor)
463 descriptor was opened outside of this class (passed to the constructor)
464 then this does not close it. """
464 then this does not close it. """
465
465
466 if not self.closed:
466 if not self.closed:
467 # It is possible for __del__ methods to execute during the
467 # It is possible for __del__ methods to execute during the
468 # teardown of the Python VM itself. Thus self.close() may
468 # teardown of the Python VM itself. Thus self.close() may
469 # trigger an exception because os.close may be None.
469 # trigger an exception because os.close may be None.
470 # -- Fernando Perez
470 # -- Fernando Perez
471 try:
471 try:
472 self.close()
472 self.close()
473 except:
473 except:
474 pass
474 pass
475
475
476 def __str__(self):
476 def __str__(self):
477
477
478 """This returns a human-readable string that represents the state of
478 """This returns a human-readable string that represents the state of
479 the object. """
479 the object. """
480
480
481 s = []
481 s = []
482 s.append(repr(self))
482 s.append(repr(self))
483 s.append('version: ' + __version__)
483 s.append('version: ' + __version__)
484 s.append('command: ' + str(self.command))
484 s.append('command: ' + str(self.command))
485 s.append('args: ' + str(self.args))
485 s.append('args: ' + str(self.args))
486 s.append('searcher: ' + str(self.searcher))
486 s.append('searcher: ' + str(self.searcher))
487 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
487 s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
488 s.append('before (last 100 chars): ' + str(self.before)[-100:])
488 s.append('before (last 100 chars): ' + str(self.before)[-100:])
489 s.append('after: ' + str(self.after))
489 s.append('after: ' + str(self.after))
490 s.append('match: ' + str(self.match))
490 s.append('match: ' + str(self.match))
491 s.append('match_index: ' + str(self.match_index))
491 s.append('match_index: ' + str(self.match_index))
492 s.append('exitstatus: ' + str(self.exitstatus))
492 s.append('exitstatus: ' + str(self.exitstatus))
493 s.append('flag_eof: ' + str(self.flag_eof))
493 s.append('flag_eof: ' + str(self.flag_eof))
494 s.append('pid: ' + str(self.pid))
494 s.append('pid: ' + str(self.pid))
495 s.append('child_fd: ' + str(self.child_fd))
495 s.append('child_fd: ' + str(self.child_fd))
496 s.append('closed: ' + str(self.closed))
496 s.append('closed: ' + str(self.closed))
497 s.append('timeout: ' + str(self.timeout))
497 s.append('timeout: ' + str(self.timeout))
498 s.append('delimiter: ' + str(self.delimiter))
498 s.append('delimiter: ' + str(self.delimiter))
499 s.append('logfile: ' + str(self.logfile))
499 s.append('logfile: ' + str(self.logfile))
500 s.append('logfile_read: ' + str(self.logfile_read))
500 s.append('logfile_read: ' + str(self.logfile_read))
501 s.append('logfile_send: ' + str(self.logfile_send))
501 s.append('logfile_send: ' + str(self.logfile_send))
502 s.append('maxread: ' + str(self.maxread))
502 s.append('maxread: ' + str(self.maxread))
503 s.append('ignorecase: ' + str(self.ignorecase))
503 s.append('ignorecase: ' + str(self.ignorecase))
504 s.append('searchwindowsize: ' + str(self.searchwindowsize))
504 s.append('searchwindowsize: ' + str(self.searchwindowsize))
505 s.append('delaybeforesend: ' + str(self.delaybeforesend))
505 s.append('delaybeforesend: ' + str(self.delaybeforesend))
506 s.append('delayafterclose: ' + str(self.delayafterclose))
506 s.append('delayafterclose: ' + str(self.delayafterclose))
507 s.append('delayafterterminate: ' + str(self.delayafterterminate))
507 s.append('delayafterterminate: ' + str(self.delayafterterminate))
508 return '\n'.join(s)
508 return '\n'.join(s)
509
509
510 def _spawn(self,command,args=[]):
510 def _spawn(self,command,args=[]):
511
511
512 """This starts the given command in a child process. This does all the
512 """This starts the given command in a child process. This does all the
513 fork/exec type of stuff for a pty. This is called by __init__. If args
513 fork/exec type of stuff for a pty. This is called by __init__. If args
514 is empty then command will be parsed (split on spaces) and args will be
514 is empty then command will be parsed (split on spaces) and args will be
515 set to parsed arguments. """
515 set to parsed arguments. """
516
516
517 # The pid and child_fd of this object get set by this method.
517 # The pid and child_fd of this object get set by this method.
518 # Note that it is difficult for this method to fail.
518 # Note that it is difficult for this method to fail.
519 # You cannot detect if the child process cannot start.
519 # You cannot detect if the child process cannot start.
520 # So the only way you can tell if the child process started
520 # So the only way you can tell if the child process started
521 # or not is to try to read from the file descriptor. If you get
521 # or not is to try to read from the file descriptor. If you get
522 # EOF immediately then it means that the child is already dead.
522 # EOF immediately then it means that the child is already dead.
523 # That may not necessarily be bad because you may haved spawned a child
523 # That may not necessarily be bad because you may haved spawned a child
524 # that performs some task; creates no stdout output; and then dies.
524 # that performs some task; creates no stdout output; and then dies.
525
525
526 # If command is an int type then it may represent a file descriptor.
526 # If command is an int type then it may represent a file descriptor.
527 if type(command) == type(0):
527 if type(command) == type(0):
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.')
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 if type (args) != type([]):
530 if type (args) != type([]):
531 raise TypeError ('The argument, args, must be a list.')
531 raise TypeError ('The argument, args, must be a list.')
532
532
533 if args == []:
533 if args == []:
534 self.args = split_command_line(command)
534 self.args = split_command_line(command)
535 self.command = self.args[0]
535 self.command = self.args[0]
536 else:
536 else:
537 self.args = args[:] # work with a copy
537 self.args = args[:] # work with a copy
538 self.args.insert (0, command)
538 self.args.insert (0, command)
539 self.command = command
539 self.command = command
540
540
541 command_with_path = which(self.command)
541 command_with_path = which(self.command)
542 if command_with_path is None:
542 if command_with_path is None:
543 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
543 raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command)
544 self.command = command_with_path
544 self.command = command_with_path
545 self.args[0] = self.command
545 self.args[0] = self.command
546
546
547 self.name = '<' + ' '.join (self.args) + '>'
547 self.name = '<' + ' '.join (self.args) + '>'
548
548
549 assert self.pid is None, 'The pid member should be None.'
549 assert self.pid is None, 'The pid member should be None.'
550 assert self.command is not None, 'The command member should not be None.'
550 assert self.command is not None, 'The command member should not be None.'
551
551
552 if self.use_native_pty_fork:
552 if self.use_native_pty_fork:
553 try:
553 try:
554 self.pid, self.child_fd = pty.fork()
554 self.pid, self.child_fd = pty.fork()
555 except OSError as e:
555 except OSError as e:
556 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
556 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
557 else: # Use internal __fork_pty
557 else: # Use internal __fork_pty
558 self.pid, self.child_fd = self.__fork_pty()
558 self.pid, self.child_fd = self.__fork_pty()
559
559
560 if self.pid == 0: # Child
560 if self.pid == 0: # Child
561 try:
561 try:
562 self.child_fd = sys.stdout.fileno() # used by setwinsize()
562 self.child_fd = sys.stdout.fileno() # used by setwinsize()
563 self.setwinsize(24, 80)
563 self.setwinsize(24, 80)
564 except:
564 except:
565 # Some platforms do not like setwinsize (Cygwin).
565 # Some platforms do not like setwinsize (Cygwin).
566 # This will cause problem when running applications that
566 # This will cause problem when running applications that
567 # are very picky about window size.
567 # are very picky about window size.
568 # This is a serious limitation, but not a show stopper.
568 # This is a serious limitation, but not a show stopper.
569 pass
569 pass
570 # Do not allow child to inherit open file descriptors from parent.
570 # Do not allow child to inherit open file descriptors from parent.
571 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
571 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
572 for i in range (3, max_fd):
572 for i in range (3, max_fd):
573 try:
573 try:
574 os.close (i)
574 os.close (i)
575 except OSError:
575 except OSError:
576 pass
576 pass
577
577
578 # I don't know why this works, but ignoring SIGHUP fixes a
578 # I don't know why this works, but ignoring SIGHUP fixes a
579 # problem when trying to start a Java daemon with sudo
579 # problem when trying to start a Java daemon with sudo
580 # (specifically, Tomcat).
580 # (specifically, Tomcat).
581 signal.signal(signal.SIGHUP, signal.SIG_IGN)
581 signal.signal(signal.SIGHUP, signal.SIG_IGN)
582
582
583 if self.cwd is not None:
583 if self.cwd is not None:
584 os.chdir(self.cwd)
584 os.chdir(self.cwd)
585 if self.env is None:
585 if self.env is None:
586 os.execv(self.command, self.args)
586 os.execv(self.command, self.args)
587 else:
587 else:
588 os.execvpe(self.command, self.args, self.env)
588 os.execvpe(self.command, self.args, self.env)
589
589
590 # Parent
590 # Parent
591 self.terminated = False
591 self.terminated = False
592 self.closed = False
592 self.closed = False
593
593
594 def __fork_pty(self):
594 def __fork_pty(self):
595
595
596 """This implements a substitute for the forkpty system call. This
596 """This implements a substitute for the forkpty system call. This
597 should be more portable than the pty.fork() function. Specifically,
597 should be more portable than the pty.fork() function. Specifically,
598 this should work on Solaris.
598 this should work on Solaris.
599
599
600 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
600 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
601 resolve the issue with Python's pty.fork() not supporting Solaris,
601 resolve the issue with Python's pty.fork() not supporting Solaris,
602 particularly ssh. Based on patch to posixmodule.c authored by Noah
602 particularly ssh. Based on patch to posixmodule.c authored by Noah
603 Spurrier::
603 Spurrier::
604
604
605 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
605 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
606
606
607 """
607 """
608
608
609 parent_fd, child_fd = os.openpty()
609 parent_fd, child_fd = os.openpty()
610 if parent_fd < 0 or child_fd < 0:
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 pid = os.fork()
613 pid = os.fork()
614 if pid < 0:
614 if pid < 0:
615 raise ExceptionPexpect, "Error! Failed os.fork()."
615 raise ExceptionPexpect("Error! Failed os.fork().")
616 elif pid == 0:
616 elif pid == 0:
617 # Child.
617 # Child.
618 os.close(parent_fd)
618 os.close(parent_fd)
619 self.__pty_make_controlling_tty(child_fd)
619 self.__pty_make_controlling_tty(child_fd)
620
620
621 os.dup2(child_fd, 0)
621 os.dup2(child_fd, 0)
622 os.dup2(child_fd, 1)
622 os.dup2(child_fd, 1)
623 os.dup2(child_fd, 2)
623 os.dup2(child_fd, 2)
624
624
625 if child_fd > 2:
625 if child_fd > 2:
626 os.close(child_fd)
626 os.close(child_fd)
627 else:
627 else:
628 # Parent.
628 # Parent.
629 os.close(child_fd)
629 os.close(child_fd)
630
630
631 return pid, parent_fd
631 return pid, parent_fd
632
632
633 def __pty_make_controlling_tty(self, tty_fd):
633 def __pty_make_controlling_tty(self, tty_fd):
634
634
635 """This makes the pseudo-terminal the controlling tty. This should be
635 """This makes the pseudo-terminal the controlling tty. This should be
636 more portable than the pty.fork() function. Specifically, this should
636 more portable than the pty.fork() function. Specifically, this should
637 work on Solaris. """
637 work on Solaris. """
638
638
639 child_name = os.ttyname(tty_fd)
639 child_name = os.ttyname(tty_fd)
640
640
641 # Disconnect from controlling tty. Harmless if not already connected.
641 # Disconnect from controlling tty. Harmless if not already connected.
642 try:
642 try:
643 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
643 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
644 if fd >= 0:
644 if fd >= 0:
645 os.close(fd)
645 os.close(fd)
646 except:
646 except:
647 # Already disconnected. This happens if running inside cron.
647 # Already disconnected. This happens if running inside cron.
648 pass
648 pass
649
649
650 os.setsid()
650 os.setsid()
651
651
652 # Verify we are disconnected from controlling tty
652 # Verify we are disconnected from controlling tty
653 # by attempting to open it again.
653 # by attempting to open it again.
654 try:
654 try:
655 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
655 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
656 if fd >= 0:
656 if fd >= 0:
657 os.close(fd)
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 except:
659 except:
660 # Good! We are disconnected from a controlling tty.
660 # Good! We are disconnected from a controlling tty.
661 pass
661 pass
662
662
663 # Verify we can open child pty.
663 # Verify we can open child pty.
664 fd = os.open(child_name, os.O_RDWR);
664 fd = os.open(child_name, os.O_RDWR);
665 if fd < 0:
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 else:
667 else:
668 os.close(fd)
668 os.close(fd)
669
669
670 # Verify we now have a controlling tty.
670 # Verify we now have a controlling tty.
671 fd = os.open("/dev/tty", os.O_WRONLY)
671 fd = os.open("/dev/tty", os.O_WRONLY)
672 if fd < 0:
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 else:
674 else:
675 os.close(fd)
675 os.close(fd)
676
676
677 def fileno (self): # File-like object.
677 def fileno (self): # File-like object.
678
678
679 """This returns the file descriptor of the pty for the child.
679 """This returns the file descriptor of the pty for the child.
680 """
680 """
681
681
682 return self.child_fd
682 return self.child_fd
683
683
684 def close (self, force=True): # File-like object.
684 def close (self, force=True): # File-like object.
685
685
686 """This closes the connection with the child application. Note that
686 """This closes the connection with the child application. Note that
687 calling close() more than once is valid. This emulates standard Python
687 calling close() more than once is valid. This emulates standard Python
688 behavior with files. Set force to True if you want to make sure that
688 behavior with files. Set force to True if you want to make sure that
689 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
689 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
690 and SIGINT). """
690 and SIGINT). """
691
691
692 if not self.closed:
692 if not self.closed:
693 self.flush()
693 self.flush()
694 os.close (self.child_fd)
694 os.close (self.child_fd)
695 time.sleep(self.delayafterclose) # Give kernel time to update process status.
695 time.sleep(self.delayafterclose) # Give kernel time to update process status.
696 if self.isalive():
696 if self.isalive():
697 if not self.terminate(force):
697 if not self.terminate(force):
698 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
698 raise ExceptionPexpect ('close() could not terminate the child using terminate()')
699 self.child_fd = -1
699 self.child_fd = -1
700 self.closed = True
700 self.closed = True
701 #self.pid = None
701 #self.pid = None
702
702
703 def flush (self): # File-like object.
703 def flush (self): # File-like object.
704
704
705 """This does nothing. It is here to support the interface for a
705 """This does nothing. It is here to support the interface for a
706 File-like object. """
706 File-like object. """
707
707
708 pass
708 pass
709
709
710 def isatty (self): # File-like object.
710 def isatty (self): # File-like object.
711
711
712 """This returns True if the file descriptor is open and connected to a
712 """This returns True if the file descriptor is open and connected to a
713 tty(-like) device, else False. """
713 tty(-like) device, else False. """
714
714
715 return os.isatty(self.child_fd)
715 return os.isatty(self.child_fd)
716
716
717 def waitnoecho (self, timeout=-1):
717 def waitnoecho (self, timeout=-1):
718
718
719 """This waits until the terminal ECHO flag is set False. This returns
719 """This waits until the terminal ECHO flag is set False. This returns
720 True if the echo mode is off. This returns False if the ECHO flag was
720 True if the echo mode is off. This returns False if the ECHO flag was
721 not set False before the timeout. This can be used to detect when the
721 not set False before the timeout. This can be used to detect when the
722 child is waiting for a password. Usually a child application will turn
722 child is waiting for a password. Usually a child application will turn
723 off echo mode when it is waiting for the user to enter a password. For
723 off echo mode when it is waiting for the user to enter a password. For
724 example, instead of expecting the "password:" prompt you can wait for
724 example, instead of expecting the "password:" prompt you can wait for
725 the child to set ECHO off::
725 the child to set ECHO off::
726
726
727 p = pexpect.spawn ('ssh user@example.com')
727 p = pexpect.spawn ('ssh user@example.com')
728 p.waitnoecho()
728 p.waitnoecho()
729 p.sendline(mypassword)
729 p.sendline(mypassword)
730
730
731 If timeout==-1 then this method will use the value in self.timeout.
731 If timeout==-1 then this method will use the value in self.timeout.
732 If timeout==None then this method to block until ECHO flag is False.
732 If timeout==None then this method to block until ECHO flag is False.
733 """
733 """
734
734
735 if timeout == -1:
735 if timeout == -1:
736 timeout = self.timeout
736 timeout = self.timeout
737 if timeout is not None:
737 if timeout is not None:
738 end_time = time.time() + timeout
738 end_time = time.time() + timeout
739 while True:
739 while True:
740 if not self.getecho():
740 if not self.getecho():
741 return True
741 return True
742 if timeout < 0 and timeout is not None:
742 if timeout < 0 and timeout is not None:
743 return False
743 return False
744 if timeout is not None:
744 if timeout is not None:
745 timeout = end_time - time.time()
745 timeout = end_time - time.time()
746 time.sleep(0.1)
746 time.sleep(0.1)
747
747
748 def getecho (self):
748 def getecho (self):
749
749
750 """This returns the terminal echo mode. This returns True if echo is
750 """This returns the terminal echo mode. This returns True if echo is
751 on or False if echo is off. Child applications that are expecting you
751 on or False if echo is off. Child applications that are expecting you
752 to enter a password often set ECHO False. See waitnoecho(). """
752 to enter a password often set ECHO False. See waitnoecho(). """
753
753
754 attr = termios.tcgetattr(self.child_fd)
754 attr = termios.tcgetattr(self.child_fd)
755 if attr[3] & termios.ECHO:
755 if attr[3] & termios.ECHO:
756 return True
756 return True
757 return False
757 return False
758
758
759 def setecho (self, state):
759 def setecho (self, state):
760
760
761 """This sets the terminal echo mode on or off. Note that anything the
761 """This sets the terminal echo mode on or off. Note that anything the
762 child sent before the echo will be lost, so you should be sure that
762 child sent before the echo will be lost, so you should be sure that
763 your input buffer is empty before you call setecho(). For example, the
763 your input buffer is empty before you call setecho(). For example, the
764 following will work as expected::
764 following will work as expected::
765
765
766 p = pexpect.spawn('cat')
766 p = pexpect.spawn('cat')
767 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
767 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
768 p.expect (['1234'])
768 p.expect (['1234'])
769 p.expect (['1234'])
769 p.expect (['1234'])
770 p.setecho(False) # Turn off tty echo
770 p.setecho(False) # Turn off tty echo
771 p.sendline ('abcd') # We will set this only once (echoed by cat).
771 p.sendline ('abcd') # We will set this only once (echoed by cat).
772 p.sendline ('wxyz') # We will set this only once (echoed by cat)
772 p.sendline ('wxyz') # We will set this only once (echoed by cat)
773 p.expect (['abcd'])
773 p.expect (['abcd'])
774 p.expect (['wxyz'])
774 p.expect (['wxyz'])
775
775
776 The following WILL NOT WORK because the lines sent before the setecho
776 The following WILL NOT WORK because the lines sent before the setecho
777 will be lost::
777 will be lost::
778
778
779 p = pexpect.spawn('cat')
779 p = pexpect.spawn('cat')
780 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
780 p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
781 p.setecho(False) # Turn off tty echo
781 p.setecho(False) # Turn off tty echo
782 p.sendline ('abcd') # We will set this only once (echoed by cat).
782 p.sendline ('abcd') # We will set this only once (echoed by cat).
783 p.sendline ('wxyz') # We will set this only once (echoed by cat)
783 p.sendline ('wxyz') # We will set this only once (echoed by cat)
784 p.expect (['1234'])
784 p.expect (['1234'])
785 p.expect (['1234'])
785 p.expect (['1234'])
786 p.expect (['abcd'])
786 p.expect (['abcd'])
787 p.expect (['wxyz'])
787 p.expect (['wxyz'])
788 """
788 """
789
789
790 self.child_fd
790 self.child_fd
791 attr = termios.tcgetattr(self.child_fd)
791 attr = termios.tcgetattr(self.child_fd)
792 if state:
792 if state:
793 attr[3] = attr[3] | termios.ECHO
793 attr[3] = attr[3] | termios.ECHO
794 else:
794 else:
795 attr[3] = attr[3] & ~termios.ECHO
795 attr[3] = attr[3] & ~termios.ECHO
796 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
796 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
797 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
797 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
798 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
798 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
799
799
800 def read_nonblocking (self, size = 1, timeout = -1):
800 def read_nonblocking (self, size = 1, timeout = -1):
801
801
802 """This reads at most size bytes from the child application. It
802 """This reads at most size bytes from the child application. It
803 includes a timeout. If the read does not complete within the timeout
803 includes a timeout. If the read does not complete within the timeout
804 period then a TIMEOUT exception is raised. If the end of file is read
804 period then a TIMEOUT exception is raised. If the end of file is read
805 then an EOF exception will be raised. If a log file was set using
805 then an EOF exception will be raised. If a log file was set using
806 setlog() then all data will also be written to the log file.
806 setlog() then all data will also be written to the log file.
807
807
808 If timeout is None then the read may block indefinitely. If timeout is -1
808 If timeout is None then the read may block indefinitely. If timeout is -1
809 then the self.timeout value is used. If timeout is 0 then the child is
809 then the self.timeout value is used. If timeout is 0 then the child is
810 polled and if there was no data immediately ready then this will raise
810 polled and if there was no data immediately ready then this will raise
811 a TIMEOUT exception.
811 a TIMEOUT exception.
812
812
813 The timeout refers only to the amount of time to read at least one
813 The timeout refers only to the amount of time to read at least one
814 character. This is not effected by the 'size' parameter, so if you call
814 character. This is not effected by the 'size' parameter, so if you call
815 read_nonblocking(size=100, timeout=30) and only one character is
815 read_nonblocking(size=100, timeout=30) and only one character is
816 available right away then one character will be returned immediately.
816 available right away then one character will be returned immediately.
817 It will not wait for 30 seconds for another 99 characters to come in.
817 It will not wait for 30 seconds for another 99 characters to come in.
818
818
819 This is a wrapper around os.read(). It uses select.select() to
819 This is a wrapper around os.read(). It uses select.select() to
820 implement the timeout. """
820 implement the timeout. """
821
821
822 if self.closed:
822 if self.closed:
823 raise ValueError ('I/O operation on closed file in read_nonblocking().')
823 raise ValueError ('I/O operation on closed file in read_nonblocking().')
824
824
825 if timeout == -1:
825 if timeout == -1:
826 timeout = self.timeout
826 timeout = self.timeout
827
827
828 # Note that some systems such as Solaris do not give an EOF when
828 # Note that some systems such as Solaris do not give an EOF when
829 # the child dies. In fact, you can still try to read
829 # the child dies. In fact, you can still try to read
830 # from the child_fd -- it will block forever or until TIMEOUT.
830 # from the child_fd -- it will block forever or until TIMEOUT.
831 # For this case, I test isalive() before doing any reading.
831 # For this case, I test isalive() before doing any reading.
832 # If isalive() is false, then I pretend that this is the same as EOF.
832 # If isalive() is false, then I pretend that this is the same as EOF.
833 if not self.isalive():
833 if not self.isalive():
834 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
834 r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll"
835 if not r:
835 if not r:
836 self.flag_eof = True
836 self.flag_eof = True
837 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
837 raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.')
838 elif self.__irix_hack:
838 elif self.__irix_hack:
839 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
839 # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.
840 # This adds a 2 second delay, but only when the child is terminated.
840 # This adds a 2 second delay, but only when the child is terminated.
841 r, w, e = self.__select([self.child_fd], [], [], 2)
841 r, w, e = self.__select([self.child_fd], [], [], 2)
842 if not r and not self.isalive():
842 if not r and not self.isalive():
843 self.flag_eof = True
843 self.flag_eof = True
844 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
844 raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.')
845
845
846 r,w,e = self.__select([self.child_fd], [], [], timeout)
846 r,w,e = self.__select([self.child_fd], [], [], timeout)
847
847
848 if not r:
848 if not r:
849 if not self.isalive():
849 if not self.isalive():
850 # Some platforms, such as Irix, will claim that their processes are alive;
850 # Some platforms, such as Irix, will claim that their processes are alive;
851 # then timeout on the select; and then finally admit that they are not alive.
851 # then timeout on the select; and then finally admit that they are not alive.
852 self.flag_eof = True
852 self.flag_eof = True
853 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
853 raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.')
854 else:
854 else:
855 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
855 raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
856
856
857 if self.child_fd in r:
857 if self.child_fd in r:
858 try:
858 try:
859 s = os.read(self.child_fd, size)
859 s = os.read(self.child_fd, size)
860 except OSError as e: # Linux does this
860 except OSError as e: # Linux does this
861 self.flag_eof = True
861 self.flag_eof = True
862 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
862 raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.')
863 if s == b'': # BSD style
863 if s == b'': # BSD style
864 self.flag_eof = True
864 self.flag_eof = True
865 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
865 raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
866
866
867 s2 = self._cast_buffer_type(s)
867 s2 = self._cast_buffer_type(s)
868 if self.logfile is not None:
868 if self.logfile is not None:
869 self.logfile.write(s2)
869 self.logfile.write(s2)
870 self.logfile.flush()
870 self.logfile.flush()
871 if self.logfile_read is not None:
871 if self.logfile_read is not None:
872 self.logfile_read.write(s2)
872 self.logfile_read.write(s2)
873 self.logfile_read.flush()
873 self.logfile_read.flush()
874
874
875 return s
875 return s
876
876
877 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
877 raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
878
878
879 def read (self, size = -1): # File-like object.
879 def read (self, size = -1): # File-like object.
880 """This reads at most "size" bytes from the file (less if the read hits
880 """This reads at most "size" bytes from the file (less if the read hits
881 EOF before obtaining size bytes). If the size argument is negative or
881 EOF before obtaining size bytes). If the size argument is negative or
882 omitted, read all data until EOF is reached. The bytes are returned as
882 omitted, read all data until EOF is reached. The bytes are returned as
883 a string object. An empty string is returned when EOF is encountered
883 a string object. An empty string is returned when EOF is encountered
884 immediately. """
884 immediately. """
885
885
886 if size == 0:
886 if size == 0:
887 return self._empty_buffer
887 return self._empty_buffer
888 if size < 0:
888 if size < 0:
889 self.expect (self.delimiter) # delimiter default is EOF
889 self.expect (self.delimiter) # delimiter default is EOF
890 return self.before
890 return self.before
891
891
892 # I could have done this more directly by not using expect(), but
892 # I could have done this more directly by not using expect(), but
893 # I deliberately decided to couple read() to expect() so that
893 # I deliberately decided to couple read() to expect() so that
894 # I would catch any bugs early and ensure consistant behavior.
894 # I would catch any bugs early and ensure consistant behavior.
895 # It's a little less efficient, but there is less for me to
895 # It's a little less efficient, but there is less for me to
896 # worry about if I have to later modify read() or expect().
896 # worry about if I have to later modify read() or expect().
897 # Note, it's OK if size==-1 in the regex. That just means it
897 # Note, it's OK if size==-1 in the regex. That just means it
898 # will never match anything in which case we stop only on EOF.
898 # will never match anything in which case we stop only on EOF.
899 if self._buffer_type is bytes:
899 if self._buffer_type is bytes:
900 pat = (u'.{%d}' % size).encode('ascii')
900 pat = (u'.{%d}' % size).encode('ascii')
901 else:
901 else:
902 pat = u'.{%d}' % size
902 pat = u'.{%d}' % size
903 cre = re.compile(pat, re.DOTALL)
903 cre = re.compile(pat, re.DOTALL)
904 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
904 index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
905 if index == 0:
905 if index == 0:
906 return self.after ### self.before should be ''. Should I assert this?
906 return self.after ### self.before should be ''. Should I assert this?
907 return self.before
907 return self.before
908
908
909 def readline(self, size = -1):
909 def readline(self, size = -1):
910 """This reads and returns one entire line. A trailing newline is kept
910 """This reads and returns one entire line. A trailing newline is kept
911 in the string, but may be absent when a file ends with an incomplete
911 in the string, but may be absent when a file ends with an incomplete
912 line. Note: This readline() looks for a \\r\\n pair even on UNIX
912 line. Note: This readline() looks for a \\r\\n pair even on UNIX
913 because this is what the pseudo tty device returns. So contrary to what
913 because this is what the pseudo tty device returns. So contrary to what
914 you may expect you will receive the newline as \\r\\n. An empty string
914 you may expect you will receive the newline as \\r\\n. An empty string
915 is returned when EOF is hit immediately. Currently, the size argument is
915 is returned when EOF is hit immediately. Currently, the size argument is
916 mostly ignored, so this behavior is not standard for a file-like
916 mostly ignored, so this behavior is not standard for a file-like
917 object. If size is 0 then an empty string is returned. """
917 object. If size is 0 then an empty string is returned. """
918
918
919 if size == 0:
919 if size == 0:
920 return self._empty_buffer
920 return self._empty_buffer
921 index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF
921 index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF
922 if index == 0:
922 if index == 0:
923 return self.before + self._pty_newline
923 return self.before + self._pty_newline
924 return self.before
924 return self.before
925
925
926 def __iter__ (self): # File-like object.
926 def __iter__ (self): # File-like object.
927
927
928 """This is to support iterators over a file-like object.
928 """This is to support iterators over a file-like object.
929 """
929 """
930
930
931 return self
931 return self
932
932
933 def next (self): # File-like object.
933 def next (self): # File-like object.
934
934
935 """This is to support iterators over a file-like object.
935 """This is to support iterators over a file-like object.
936 """
936 """
937
937
938 result = self.readline()
938 result = self.readline()
939 if result == self._empty_buffer:
939 if result == self._empty_buffer:
940 raise StopIteration
940 raise StopIteration
941 return result
941 return result
942
942
943 def readlines (self, sizehint = -1): # File-like object.
943 def readlines (self, sizehint = -1): # File-like object.
944
944
945 """This reads until EOF using readline() and returns a list containing
945 """This reads until EOF using readline() and returns a list containing
946 the lines thus read. The optional "sizehint" argument is ignored. """
946 the lines thus read. The optional "sizehint" argument is ignored. """
947
947
948 lines = []
948 lines = []
949 while True:
949 while True:
950 line = self.readline()
950 line = self.readline()
951 if not line:
951 if not line:
952 break
952 break
953 lines.append(line)
953 lines.append(line)
954 return lines
954 return lines
955
955
956 def write(self, s): # File-like object.
956 def write(self, s): # File-like object.
957
957
958 """This is similar to send() except that there is no return value.
958 """This is similar to send() except that there is no return value.
959 """
959 """
960
960
961 self.send (s)
961 self.send (s)
962
962
963 def writelines (self, sequence): # File-like object.
963 def writelines (self, sequence): # File-like object.
964
964
965 """This calls write() for each element in the sequence. The sequence
965 """This calls write() for each element in the sequence. The sequence
966 can be any iterable object producing strings, typically a list of
966 can be any iterable object producing strings, typically a list of
967 strings. This does not add line separators There is no return value.
967 strings. This does not add line separators There is no return value.
968 """
968 """
969
969
970 for s in sequence:
970 for s in sequence:
971 self.write (s)
971 self.write (s)
972
972
973 def send(self, s):
973 def send(self, s):
974
974
975 """This sends a string to the child process. This returns the number of
975 """This sends a string to the child process. This returns the number of
976 bytes written. If a log file was set then the data is also written to
976 bytes written. If a log file was set then the data is also written to
977 the log. """
977 the log. """
978
978
979 time.sleep(self.delaybeforesend)
979 time.sleep(self.delaybeforesend)
980
980
981 s2 = self._cast_buffer_type(s)
981 s2 = self._cast_buffer_type(s)
982 if self.logfile is not None:
982 if self.logfile is not None:
983 self.logfile.write(s2)
983 self.logfile.write(s2)
984 self.logfile.flush()
984 self.logfile.flush()
985 if self.logfile_send is not None:
985 if self.logfile_send is not None:
986 self.logfile_send.write(s2)
986 self.logfile_send.write(s2)
987 self.logfile_send.flush()
987 self.logfile_send.flush()
988 c = os.write (self.child_fd, _cast_bytes(s, self.encoding))
988 c = os.write (self.child_fd, _cast_bytes(s, self.encoding))
989 return c
989 return c
990
990
991 def sendline(self, s=''):
991 def sendline(self, s=''):
992
992
993 """This is like send(), but it adds a line feed (os.linesep). This
993 """This is like send(), but it adds a line feed (os.linesep). This
994 returns the number of bytes written. """
994 returns the number of bytes written. """
995
995
996 n = self.send (s)
996 n = self.send (s)
997 n = n + self.send (os.linesep)
997 n = n + self.send (os.linesep)
998 return n
998 return n
999
999
1000 def sendcontrol(self, char):
1000 def sendcontrol(self, char):
1001
1001
1002 """This sends a control character to the child such as Ctrl-C or
1002 """This sends a control character to the child such as Ctrl-C or
1003 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
1003 Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
1004
1004
1005 child.sendcontrol('g')
1005 child.sendcontrol('g')
1006
1006
1007 See also, sendintr() and sendeof().
1007 See also, sendintr() and sendeof().
1008 """
1008 """
1009
1009
1010 char = char.lower()
1010 char = char.lower()
1011 a = ord(char)
1011 a = ord(char)
1012 if a>=97 and a<=122:
1012 if a>=97 and a<=122:
1013 a = a - ord('a') + 1
1013 a = a - ord('a') + 1
1014 return self.send (chr(a))
1014 return self.send (chr(a))
1015 d = {'@':0, '`':0,
1015 d = {'@':0, '`':0,
1016 '[':27, '{':27,
1016 '[':27, '{':27,
1017 '\\':28, '|':28,
1017 '\\':28, '|':28,
1018 ']':29, '}': 29,
1018 ']':29, '}': 29,
1019 '^':30, '~':30,
1019 '^':30, '~':30,
1020 '_':31,
1020 '_':31,
1021 '?':127}
1021 '?':127}
1022 if char not in d:
1022 if char not in d:
1023 return 0
1023 return 0
1024 return self.send (chr(d[char]))
1024 return self.send (chr(d[char]))
1025
1025
1026 def sendeof(self):
1026 def sendeof(self):
1027
1027
1028 """This sends an EOF to the child. This sends a character which causes
1028 """This sends an EOF to the child. This sends a character which causes
1029 the pending parent output buffer to be sent to the waiting child
1029 the pending parent output buffer to be sent to the waiting child
1030 program without waiting for end-of-line. If it is the first character
1030 program without waiting for end-of-line. If it is the first character
1031 of the line, the read() in the user program returns 0, which signifies
1031 of the line, the read() in the user program returns 0, which signifies
1032 end-of-file. This means to work as expected a sendeof() has to be
1032 end-of-file. This means to work as expected a sendeof() has to be
1033 called at the beginning of a line. This method does not send a newline.
1033 called at the beginning of a line. This method does not send a newline.
1034 It is the responsibility of the caller to ensure the eof is sent at the
1034 It is the responsibility of the caller to ensure the eof is sent at the
1035 beginning of a line. """
1035 beginning of a line. """
1036
1036
1037 ### Hmmm... how do I send an EOF?
1037 ### Hmmm... how do I send an EOF?
1038 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1038 ###C if ((m = write(pty, *buf, p - *buf)) < 0)
1039 ###C return (errno == EWOULDBLOCK) ? n : -1;
1039 ###C return (errno == EWOULDBLOCK) ? n : -1;
1040 #fd = sys.stdin.fileno()
1040 #fd = sys.stdin.fileno()
1041 #old = termios.tcgetattr(fd) # remember current state
1041 #old = termios.tcgetattr(fd) # remember current state
1042 #attr = termios.tcgetattr(fd)
1042 #attr = termios.tcgetattr(fd)
1043 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1043 #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1044 #try: # use try/finally to ensure state gets restored
1044 #try: # use try/finally to ensure state gets restored
1045 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1045 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1046 # if hasattr(termios, 'CEOF'):
1046 # if hasattr(termios, 'CEOF'):
1047 # os.write (self.child_fd, '%c' % termios.CEOF)
1047 # os.write (self.child_fd, '%c' % termios.CEOF)
1048 # else:
1048 # else:
1049 # # Silly platform does not define CEOF so assume CTRL-D
1049 # # Silly platform does not define CEOF so assume CTRL-D
1050 # os.write (self.child_fd, '%c' % 4)
1050 # os.write (self.child_fd, '%c' % 4)
1051 #finally: # restore state
1051 #finally: # restore state
1052 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1052 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1053 if hasattr(termios, 'VEOF'):
1053 if hasattr(termios, 'VEOF'):
1054 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1054 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1055 else:
1055 else:
1056 # platform does not define VEOF so assume CTRL-D
1056 # platform does not define VEOF so assume CTRL-D
1057 char = chr(4)
1057 char = chr(4)
1058 self.send(char)
1058 self.send(char)
1059
1059
1060 def sendintr(self):
1060 def sendintr(self):
1061
1061
1062 """This sends a SIGINT to the child. It does not require
1062 """This sends a SIGINT to the child. It does not require
1063 the SIGINT to be the first character on a line. """
1063 the SIGINT to be the first character on a line. """
1064
1064
1065 if hasattr(termios, 'VINTR'):
1065 if hasattr(termios, 'VINTR'):
1066 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1066 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1067 else:
1067 else:
1068 # platform does not define VINTR so assume CTRL-C
1068 # platform does not define VINTR so assume CTRL-C
1069 char = chr(3)
1069 char = chr(3)
1070 self.send (char)
1070 self.send (char)
1071
1071
1072 def eof (self):
1072 def eof (self):
1073
1073
1074 """This returns True if the EOF exception was ever raised.
1074 """This returns True if the EOF exception was ever raised.
1075 """
1075 """
1076
1076
1077 return self.flag_eof
1077 return self.flag_eof
1078
1078
1079 def terminate(self, force=False):
1079 def terminate(self, force=False):
1080
1080
1081 """This forces a child process to terminate. It starts nicely with
1081 """This forces a child process to terminate. It starts nicely with
1082 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1082 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1083 returns True if the child was terminated. This returns False if the
1083 returns True if the child was terminated. This returns False if the
1084 child could not be terminated. """
1084 child could not be terminated. """
1085
1085
1086 if not self.isalive():
1086 if not self.isalive():
1087 return True
1087 return True
1088 try:
1088 try:
1089 self.kill(signal.SIGHUP)
1089 self.kill(signal.SIGHUP)
1090 time.sleep(self.delayafterterminate)
1090 time.sleep(self.delayafterterminate)
1091 if not self.isalive():
1091 if not self.isalive():
1092 return True
1092 return True
1093 self.kill(signal.SIGCONT)
1093 self.kill(signal.SIGCONT)
1094 time.sleep(self.delayafterterminate)
1094 time.sleep(self.delayafterterminate)
1095 if not self.isalive():
1095 if not self.isalive():
1096 return True
1096 return True
1097 self.kill(signal.SIGINT)
1097 self.kill(signal.SIGINT)
1098 time.sleep(self.delayafterterminate)
1098 time.sleep(self.delayafterterminate)
1099 if not self.isalive():
1099 if not self.isalive():
1100 return True
1100 return True
1101 if force:
1101 if force:
1102 self.kill(signal.SIGKILL)
1102 self.kill(signal.SIGKILL)
1103 time.sleep(self.delayafterterminate)
1103 time.sleep(self.delayafterterminate)
1104 if not self.isalive():
1104 if not self.isalive():
1105 return True
1105 return True
1106 else:
1106 else:
1107 return False
1107 return False
1108 return False
1108 return False
1109 except OSError as e:
1109 except OSError as e:
1110 # I think there are kernel timing issues that sometimes cause
1110 # I think there are kernel timing issues that sometimes cause
1111 # this to happen. I think isalive() reports True, but the
1111 # this to happen. I think isalive() reports True, but the
1112 # process is dead to the kernel.
1112 # process is dead to the kernel.
1113 # Make one last attempt to see if the kernel is up to date.
1113 # Make one last attempt to see if the kernel is up to date.
1114 time.sleep(self.delayafterterminate)
1114 time.sleep(self.delayafterterminate)
1115 if not self.isalive():
1115 if not self.isalive():
1116 return True
1116 return True
1117 else:
1117 else:
1118 return False
1118 return False
1119
1119
1120 def wait(self):
1120 def wait(self):
1121
1121
1122 """This waits until the child exits. This is a blocking call. This will
1122 """This waits until the child exits. This is a blocking call. This will
1123 not read any data from the child, so this will block forever if the
1123 not read any data from the child, so this will block forever if the
1124 child has unread output and has terminated. In other words, the child
1124 child has unread output and has terminated. In other words, the child
1125 may have printed output then called exit(); but, technically, the child
1125 may have printed output then called exit(); but, technically, the child
1126 is still alive until its output is read. """
1126 is still alive until its output is read. """
1127
1127
1128 if self.isalive():
1128 if self.isalive():
1129 pid, status = os.waitpid(self.pid, 0)
1129 pid, status = os.waitpid(self.pid, 0)
1130 else:
1130 else:
1131 raise ExceptionPexpect ('Cannot wait for dead child process.')
1131 raise ExceptionPexpect ('Cannot wait for dead child process.')
1132 self.exitstatus = os.WEXITSTATUS(status)
1132 self.exitstatus = os.WEXITSTATUS(status)
1133 if os.WIFEXITED (status):
1133 if os.WIFEXITED (status):
1134 self.status = status
1134 self.status = status
1135 self.exitstatus = os.WEXITSTATUS(status)
1135 self.exitstatus = os.WEXITSTATUS(status)
1136 self.signalstatus = None
1136 self.signalstatus = None
1137 self.terminated = True
1137 self.terminated = True
1138 elif os.WIFSIGNALED (status):
1138 elif os.WIFSIGNALED (status):
1139 self.status = status
1139 self.status = status
1140 self.exitstatus = None
1140 self.exitstatus = None
1141 self.signalstatus = os.WTERMSIG(status)
1141 self.signalstatus = os.WTERMSIG(status)
1142 self.terminated = True
1142 self.terminated = True
1143 elif os.WIFSTOPPED (status):
1143 elif os.WIFSTOPPED (status):
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?')
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 return self.exitstatus
1145 return self.exitstatus
1146
1146
1147 def isalive(self):
1147 def isalive(self):
1148
1148
1149 """This tests if the child process is running or not. This is
1149 """This tests if the child process is running or not. This is
1150 non-blocking. If the child was terminated then this will read the
1150 non-blocking. If the child was terminated then this will read the
1151 exitstatus or signalstatus of the child. This returns True if the child
1151 exitstatus or signalstatus of the child. This returns True if the child
1152 process appears to be running or False if not. It can take literally
1152 process appears to be running or False if not. It can take literally
1153 SECONDS for Solaris to return the right status. """
1153 SECONDS for Solaris to return the right status. """
1154
1154
1155 if self.terminated:
1155 if self.terminated:
1156 return False
1156 return False
1157
1157
1158 if self.flag_eof:
1158 if self.flag_eof:
1159 # This is for Linux, which requires the blocking form of waitpid to get
1159 # This is for Linux, which requires the blocking form of waitpid to get
1160 # status of a defunct process. This is super-lame. The flag_eof would have
1160 # status of a defunct process. This is super-lame. The flag_eof would have
1161 # been set in read_nonblocking(), so this should be safe.
1161 # been set in read_nonblocking(), so this should be safe.
1162 waitpid_options = 0
1162 waitpid_options = 0
1163 else:
1163 else:
1164 waitpid_options = os.WNOHANG
1164 waitpid_options = os.WNOHANG
1165
1165
1166 try:
1166 try:
1167 pid, status = os.waitpid(self.pid, waitpid_options)
1167 pid, status = os.waitpid(self.pid, waitpid_options)
1168 except OSError as e: # No child processes
1168 except OSError as e: # No child processes
1169 if e.errno == errno.ECHILD:
1169 if e.errno == errno.ECHILD:
1170 raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
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 else:
1171 else:
1172 raise e
1172 raise e
1173
1173
1174 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1174 # I have to do this twice for Solaris. I can't even believe that I figured this out...
1175 # If waitpid() returns 0 it means that no child process wishes to
1175 # If waitpid() returns 0 it means that no child process wishes to
1176 # report, and the value of status is undefined.
1176 # report, and the value of status is undefined.
1177 if pid == 0:
1177 if pid == 0:
1178 try:
1178 try:
1179 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1179 pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris!
1180 except OSError as e: # This should never happen...
1180 except OSError as e: # This should never happen...
1181 if e[0] == errno.ECHILD:
1181 if e[0] == errno.ECHILD:
1182 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1182 raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
1183 else:
1183 else:
1184 raise e
1184 raise e
1185
1185
1186 # If pid is still 0 after two calls to waitpid() then
1186 # If pid is still 0 after two calls to waitpid() then
1187 # the process really is alive. This seems to work on all platforms, except
1187 # the process really is alive. This seems to work on all platforms, except
1188 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1188 # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking
1189 # take care of this situation (unfortunately, this requires waiting through the timeout).
1189 # take care of this situation (unfortunately, this requires waiting through the timeout).
1190 if pid == 0:
1190 if pid == 0:
1191 return True
1191 return True
1192
1192
1193 if pid == 0:
1193 if pid == 0:
1194 return True
1194 return True
1195
1195
1196 if os.WIFEXITED (status):
1196 if os.WIFEXITED (status):
1197 self.status = status
1197 self.status = status
1198 self.exitstatus = os.WEXITSTATUS(status)
1198 self.exitstatus = os.WEXITSTATUS(status)
1199 self.signalstatus = None
1199 self.signalstatus = None
1200 self.terminated = True
1200 self.terminated = True
1201 elif os.WIFSIGNALED (status):
1201 elif os.WIFSIGNALED (status):
1202 self.status = status
1202 self.status = status
1203 self.exitstatus = None
1203 self.exitstatus = None
1204 self.signalstatus = os.WTERMSIG(status)
1204 self.signalstatus = os.WTERMSIG(status)
1205 self.terminated = True
1205 self.terminated = True
1206 elif os.WIFSTOPPED (status):
1206 elif os.WIFSTOPPED (status):
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?')
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 return False
1208 return False
1209
1209
1210 def kill(self, sig):
1210 def kill(self, sig):
1211
1211
1212 """This sends the given signal to the child application. In keeping
1212 """This sends the given signal to the child application. In keeping
1213 with UNIX tradition it has a misleading name. It does not necessarily
1213 with UNIX tradition it has a misleading name. It does not necessarily
1214 kill the child unless you send the right signal. """
1214 kill the child unless you send the right signal. """
1215
1215
1216 # Same as os.kill, but the pid is given for you.
1216 # Same as os.kill, but the pid is given for you.
1217 if self.isalive():
1217 if self.isalive():
1218 os.kill(self.pid, sig)
1218 os.kill(self.pid, sig)
1219
1219
1220 def compile_pattern_list(self, patterns):
1220 def compile_pattern_list(self, patterns):
1221
1221
1222 """This compiles a pattern-string or a list of pattern-strings.
1222 """This compiles a pattern-string or a list of pattern-strings.
1223 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1223 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1224 those. Patterns may also be None which results in an empty list (you
1224 those. Patterns may also be None which results in an empty list (you
1225 might do this if waiting for an EOF or TIMEOUT condition without
1225 might do this if waiting for an EOF or TIMEOUT condition without
1226 expecting any pattern).
1226 expecting any pattern).
1227
1227
1228 This is used by expect() when calling expect_list(). Thus expect() is
1228 This is used by expect() when calling expect_list(). Thus expect() is
1229 nothing more than::
1229 nothing more than::
1230
1230
1231 cpl = self.compile_pattern_list(pl)
1231 cpl = self.compile_pattern_list(pl)
1232 return self.expect_list(cpl, timeout)
1232 return self.expect_list(cpl, timeout)
1233
1233
1234 If you are using expect() within a loop it may be more
1234 If you are using expect() within a loop it may be more
1235 efficient to compile the patterns first and then call expect_list().
1235 efficient to compile the patterns first and then call expect_list().
1236 This avoid calls in a loop to compile_pattern_list()::
1236 This avoid calls in a loop to compile_pattern_list()::
1237
1237
1238 cpl = self.compile_pattern_list(my_pattern)
1238 cpl = self.compile_pattern_list(my_pattern)
1239 while some_condition:
1239 while some_condition:
1240 ...
1240 ...
1241 i = self.expect_list(clp, timeout)
1241 i = self.expect_list(clp, timeout)
1242 ...
1242 ...
1243 """
1243 """
1244
1244
1245 if patterns is None:
1245 if patterns is None:
1246 return []
1246 return []
1247 if not isinstance(patterns, list):
1247 if not isinstance(patterns, list):
1248 patterns = [patterns]
1248 patterns = [patterns]
1249
1249
1250 compile_flags = re.DOTALL # Allow dot to match \n
1250 compile_flags = re.DOTALL # Allow dot to match \n
1251 if self.ignorecase:
1251 if self.ignorecase:
1252 compile_flags = compile_flags | re.IGNORECASE
1252 compile_flags = compile_flags | re.IGNORECASE
1253 compiled_pattern_list = []
1253 compiled_pattern_list = []
1254 for p in patterns:
1254 for p in patterns:
1255 if isinstance(p, (bytes, unicode)):
1255 if isinstance(p, (bytes, unicode)):
1256 p = self._cast_buffer_type(p)
1256 p = self._cast_buffer_type(p)
1257 compiled_pattern_list.append(re.compile(p, compile_flags))
1257 compiled_pattern_list.append(re.compile(p, compile_flags))
1258 elif p is EOF:
1258 elif p is EOF:
1259 compiled_pattern_list.append(EOF)
1259 compiled_pattern_list.append(EOF)
1260 elif p is TIMEOUT:
1260 elif p is TIMEOUT:
1261 compiled_pattern_list.append(TIMEOUT)
1261 compiled_pattern_list.append(TIMEOUT)
1262 elif type(p) is re_type:
1262 elif type(p) is re_type:
1263 p = self._prepare_regex_pattern(p)
1263 p = self._prepare_regex_pattern(p)
1264 compiled_pattern_list.append(p)
1264 compiled_pattern_list.append(p)
1265 else:
1265 else:
1266 raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
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 return compiled_pattern_list
1268 return compiled_pattern_list
1269
1269
1270 def _prepare_regex_pattern(self, p):
1270 def _prepare_regex_pattern(self, p):
1271 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1271 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1272 if isinstance(p.pattern, unicode):
1272 if isinstance(p.pattern, unicode):
1273 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1273 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1274 return p
1274 return p
1275
1275
1276 def expect(self, pattern, timeout = -1, searchwindowsize=-1):
1276 def expect(self, pattern, timeout = -1, searchwindowsize=-1):
1277
1277
1278 """This seeks through the stream until a pattern is matched. The
1278 """This seeks through the stream until a pattern is matched. The
1279 pattern is overloaded and may take several types. The pattern can be a
1279 pattern is overloaded and may take several types. The pattern can be a
1280 StringType, EOF, a compiled re, or a list of any of those types.
1280 StringType, EOF, a compiled re, or a list of any of those types.
1281 Strings will be compiled to re types. This returns the index into the
1281 Strings will be compiled to re types. This returns the index into the
1282 pattern list. If the pattern was not a list this returns index 0 on a
1282 pattern list. If the pattern was not a list this returns index 0 on a
1283 successful match. This may raise exceptions for EOF or TIMEOUT. To
1283 successful match. This may raise exceptions for EOF or TIMEOUT. To
1284 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1284 avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1285 list. That will cause expect to match an EOF or TIMEOUT condition
1285 list. That will cause expect to match an EOF or TIMEOUT condition
1286 instead of raising an exception.
1286 instead of raising an exception.
1287
1287
1288 If you pass a list of patterns and more than one matches, the first match
1288 If you pass a list of patterns and more than one matches, the first match
1289 in the stream is chosen. If more than one pattern matches at that point,
1289 in the stream is chosen. If more than one pattern matches at that point,
1290 the leftmost in the pattern list is chosen. For example::
1290 the leftmost in the pattern list is chosen. For example::
1291
1291
1292 # the input is 'foobar'
1292 # the input is 'foobar'
1293 index = p.expect (['bar', 'foo', 'foobar'])
1293 index = p.expect (['bar', 'foo', 'foobar'])
1294 # returns 1 ('foo') even though 'foobar' is a "better" match
1294 # returns 1 ('foo') even though 'foobar' is a "better" match
1295
1295
1296 Please note, however, that buffering can affect this behavior, since
1296 Please note, however, that buffering can affect this behavior, since
1297 input arrives in unpredictable chunks. For example::
1297 input arrives in unpredictable chunks. For example::
1298
1298
1299 # the input is 'foobar'
1299 # the input is 'foobar'
1300 index = p.expect (['foobar', 'foo'])
1300 index = p.expect (['foobar', 'foo'])
1301 # returns 0 ('foobar') if all input is available at once,
1301 # returns 0 ('foobar') if all input is available at once,
1302 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1302 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1303
1303
1304 After a match is found the instance attributes 'before', 'after' and
1304 After a match is found the instance attributes 'before', 'after' and
1305 'match' will be set. You can see all the data read before the match in
1305 'match' will be set. You can see all the data read before the match in
1306 'before'. You can see the data that was matched in 'after'. The
1306 'before'. You can see the data that was matched in 'after'. The
1307 re.MatchObject used in the re match will be in 'match'. If an error
1307 re.MatchObject used in the re match will be in 'match'. If an error
1308 occurred then 'before' will be set to all the data read so far and
1308 occurred then 'before' will be set to all the data read so far and
1309 'after' and 'match' will be None.
1309 'after' and 'match' will be None.
1310
1310
1311 If timeout is -1 then timeout will be set to the self.timeout value.
1311 If timeout is -1 then timeout will be set to the self.timeout value.
1312
1312
1313 A list entry may be EOF or TIMEOUT instead of a string. This will
1313 A list entry may be EOF or TIMEOUT instead of a string. This will
1314 catch these exceptions and return the index of the list entry instead
1314 catch these exceptions and return the index of the list entry instead
1315 of raising the exception. The attribute 'after' will be set to the
1315 of raising the exception. The attribute 'after' will be set to the
1316 exception type. The attribute 'match' will be None. This allows you to
1316 exception type. The attribute 'match' will be None. This allows you to
1317 write code like this::
1317 write code like this::
1318
1318
1319 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1319 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1320 if index == 0:
1320 if index == 0:
1321 do_something()
1321 do_something()
1322 elif index == 1:
1322 elif index == 1:
1323 do_something_else()
1323 do_something_else()
1324 elif index == 2:
1324 elif index == 2:
1325 do_some_other_thing()
1325 do_some_other_thing()
1326 elif index == 3:
1326 elif index == 3:
1327 do_something_completely_different()
1327 do_something_completely_different()
1328
1328
1329 instead of code like this::
1329 instead of code like this::
1330
1330
1331 try:
1331 try:
1332 index = p.expect (['good', 'bad'])
1332 index = p.expect (['good', 'bad'])
1333 if index == 0:
1333 if index == 0:
1334 do_something()
1334 do_something()
1335 elif index == 1:
1335 elif index == 1:
1336 do_something_else()
1336 do_something_else()
1337 except EOF:
1337 except EOF:
1338 do_some_other_thing()
1338 do_some_other_thing()
1339 except TIMEOUT:
1339 except TIMEOUT:
1340 do_something_completely_different()
1340 do_something_completely_different()
1341
1341
1342 These two forms are equivalent. It all depends on what you want. You
1342 These two forms are equivalent. It all depends on what you want. You
1343 can also just expect the EOF if you are waiting for all output of a
1343 can also just expect the EOF if you are waiting for all output of a
1344 child to finish. For example::
1344 child to finish. For example::
1345
1345
1346 p = pexpect.spawn('/bin/ls')
1346 p = pexpect.spawn('/bin/ls')
1347 p.expect (pexpect.EOF)
1347 p.expect (pexpect.EOF)
1348 print p.before
1348 print p.before
1349
1349
1350 If you are trying to optimize for speed then see expect_list().
1350 If you are trying to optimize for speed then see expect_list().
1351 """
1351 """
1352
1352
1353 compiled_pattern_list = self.compile_pattern_list(pattern)
1353 compiled_pattern_list = self.compile_pattern_list(pattern)
1354 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1354 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1355
1355
1356 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1356 def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
1357
1357
1358 """This takes a list of compiled regular expressions and returns the
1358 """This takes a list of compiled regular expressions and returns the
1359 index into the pattern_list that matched the child output. The list may
1359 index into the pattern_list that matched the child output. The list may
1360 also contain EOF or TIMEOUT (which are not compiled regular
1360 also contain EOF or TIMEOUT (which are not compiled regular
1361 expressions). This method is similar to the expect() method except that
1361 expressions). This method is similar to the expect() method except that
1362 expect_list() does not recompile the pattern list on every call. This
1362 expect_list() does not recompile the pattern list on every call. This
1363 may help if you are trying to optimize for speed, otherwise just use
1363 may help if you are trying to optimize for speed, otherwise just use
1364 the expect() method. This is called by expect(). If timeout==-1 then
1364 the expect() method. This is called by expect(). If timeout==-1 then
1365 the self.timeout value is used. If searchwindowsize==-1 then the
1365 the self.timeout value is used. If searchwindowsize==-1 then the
1366 self.searchwindowsize value is used. """
1366 self.searchwindowsize value is used. """
1367
1367
1368 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1368 return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
1369
1369
1370 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1370 def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
1371
1371
1372 """This is similar to expect(), but uses plain string matching instead
1372 """This is similar to expect(), but uses plain string matching instead
1373 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1373 of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1374 may be a string; a list or other sequence of strings; or TIMEOUT and
1374 may be a string; a list or other sequence of strings; or TIMEOUT and
1375 EOF.
1375 EOF.
1376
1376
1377 This call might be faster than expect() for two reasons: string
1377 This call might be faster than expect() for two reasons: string
1378 searching is faster than RE matching and it is possible to limit the
1378 searching is faster than RE matching and it is possible to limit the
1379 search to just the end of the input buffer.
1379 search to just the end of the input buffer.
1380
1380
1381 This method is also useful when you don't want to have to worry about
1381 This method is also useful when you don't want to have to worry about
1382 escaping regular expression characters that you want to match."""
1382 escaping regular expression characters that you want to match."""
1383
1383
1384 if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF):
1384 if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF):
1385 pattern_list = [pattern_list]
1385 pattern_list = [pattern_list]
1386 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1386 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1387
1387
1388 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1388 def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1):
1389
1389
1390 """This is the common loop used inside expect. The 'searcher' should be
1390 """This is the common loop used inside expect. The 'searcher' should be
1391 an instance of searcher_re or searcher_string, which describes how and what
1391 an instance of searcher_re or searcher_string, which describes how and what
1392 to search for in the input.
1392 to search for in the input.
1393
1393
1394 See expect() for other arguments, return value and exceptions. """
1394 See expect() for other arguments, return value and exceptions. """
1395
1395
1396 self.searcher = searcher
1396 self.searcher = searcher
1397
1397
1398 if timeout == -1:
1398 if timeout == -1:
1399 timeout = self.timeout
1399 timeout = self.timeout
1400 if timeout is not None:
1400 if timeout is not None:
1401 end_time = time.time() + timeout
1401 end_time = time.time() + timeout
1402 if searchwindowsize == -1:
1402 if searchwindowsize == -1:
1403 searchwindowsize = self.searchwindowsize
1403 searchwindowsize = self.searchwindowsize
1404
1404
1405 try:
1405 try:
1406 incoming = self.buffer
1406 incoming = self.buffer
1407 freshlen = len(incoming)
1407 freshlen = len(incoming)
1408 while True: # Keep reading until exception or return.
1408 while True: # Keep reading until exception or return.
1409 index = searcher.search(incoming, freshlen, searchwindowsize)
1409 index = searcher.search(incoming, freshlen, searchwindowsize)
1410 if index >= 0:
1410 if index >= 0:
1411 self.buffer = incoming[searcher.end : ]
1411 self.buffer = incoming[searcher.end : ]
1412 self.before = incoming[ : searcher.start]
1412 self.before = incoming[ : searcher.start]
1413 self.after = incoming[searcher.start : searcher.end]
1413 self.after = incoming[searcher.start : searcher.end]
1414 self.match = searcher.match
1414 self.match = searcher.match
1415 self.match_index = index
1415 self.match_index = index
1416 return self.match_index
1416 return self.match_index
1417 # No match at this point
1417 # No match at this point
1418 if timeout is not None and timeout < 0:
1418 if timeout is not None and timeout < 0:
1419 raise TIMEOUT ('Timeout exceeded in expect_any().')
1419 raise TIMEOUT ('Timeout exceeded in expect_any().')
1420 # Still have time left, so read more data
1420 # Still have time left, so read more data
1421 c = self.read_nonblocking (self.maxread, timeout)
1421 c = self.read_nonblocking (self.maxread, timeout)
1422 freshlen = len(c)
1422 freshlen = len(c)
1423 time.sleep (0.0001)
1423 time.sleep (0.0001)
1424 incoming = incoming + c
1424 incoming = incoming + c
1425 if timeout is not None:
1425 if timeout is not None:
1426 timeout = end_time - time.time()
1426 timeout = end_time - time.time()
1427 except EOF as e:
1427 except EOF as e:
1428 self.buffer = self._empty_buffer
1428 self.buffer = self._empty_buffer
1429 self.before = incoming
1429 self.before = incoming
1430 self.after = EOF
1430 self.after = EOF
1431 index = searcher.eof_index
1431 index = searcher.eof_index
1432 if index >= 0:
1432 if index >= 0:
1433 self.match = EOF
1433 self.match = EOF
1434 self.match_index = index
1434 self.match_index = index
1435 return self.match_index
1435 return self.match_index
1436 else:
1436 else:
1437 self.match = None
1437 self.match = None
1438 self.match_index = None
1438 self.match_index = None
1439 raise EOF (str(e) + '\n' + str(self))
1439 raise EOF (str(e) + '\n' + str(self))
1440 except TIMEOUT as e:
1440 except TIMEOUT as e:
1441 self.buffer = incoming
1441 self.buffer = incoming
1442 self.before = incoming
1442 self.before = incoming
1443 self.after = TIMEOUT
1443 self.after = TIMEOUT
1444 index = searcher.timeout_index
1444 index = searcher.timeout_index
1445 if index >= 0:
1445 if index >= 0:
1446 self.match = TIMEOUT
1446 self.match = TIMEOUT
1447 self.match_index = index
1447 self.match_index = index
1448 return self.match_index
1448 return self.match_index
1449 else:
1449 else:
1450 self.match = None
1450 self.match = None
1451 self.match_index = None
1451 self.match_index = None
1452 raise TIMEOUT (str(e) + '\n' + str(self))
1452 raise TIMEOUT (str(e) + '\n' + str(self))
1453 except:
1453 except:
1454 self.before = incoming
1454 self.before = incoming
1455 self.after = None
1455 self.after = None
1456 self.match = None
1456 self.match = None
1457 self.match_index = None
1457 self.match_index = None
1458 raise
1458 raise
1459
1459
1460 def getwinsize(self):
1460 def getwinsize(self):
1461
1461
1462 """This returns the terminal window size of the child tty. The return
1462 """This returns the terminal window size of the child tty. The return
1463 value is a tuple of (rows, cols). """
1463 value is a tuple of (rows, cols). """
1464
1464
1465 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1465 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1466 s = struct.pack('HHHH', 0, 0, 0, 0)
1466 s = struct.pack('HHHH', 0, 0, 0, 0)
1467 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1467 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1468 return struct.unpack('HHHH', x)[0:2]
1468 return struct.unpack('HHHH', x)[0:2]
1469
1469
1470 def setwinsize(self, r, c):
1470 def setwinsize(self, r, c):
1471
1471
1472 """This sets the terminal window size of the child tty. This will cause
1472 """This sets the terminal window size of the child tty. This will cause
1473 a SIGWINCH signal to be sent to the child. This does not change the
1473 a SIGWINCH signal to be sent to the child. This does not change the
1474 physical window size. It changes the size reported to TTY-aware
1474 physical window size. It changes the size reported to TTY-aware
1475 applications like vi or curses -- applications that respond to the
1475 applications like vi or curses -- applications that respond to the
1476 SIGWINCH signal. """
1476 SIGWINCH signal. """
1477
1477
1478 # Check for buggy platforms. Some Python versions on some platforms
1478 # Check for buggy platforms. Some Python versions on some platforms
1479 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1479 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1480 # termios.TIOCSWINSZ. It is not clear why this happens.
1480 # termios.TIOCSWINSZ. It is not clear why this happens.
1481 # These platforms don't seem to handle the signed int very well;
1481 # These platforms don't seem to handle the signed int very well;
1482 # yet other platforms like OpenBSD have a large negative value for
1482 # yet other platforms like OpenBSD have a large negative value for
1483 # TIOCSWINSZ and they don't have a truncate problem.
1483 # TIOCSWINSZ and they don't have a truncate problem.
1484 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1484 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1485 # Note that this fix is a hack.
1485 # Note that this fix is a hack.
1486 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1486 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1487 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1487 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1488 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1488 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1489 # Note, assume ws_xpixel and ws_ypixel are zero.
1489 # Note, assume ws_xpixel and ws_ypixel are zero.
1490 s = struct.pack('HHHH', r, c, 0, 0)
1490 s = struct.pack('HHHH', r, c, 0, 0)
1491 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1491 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1492
1492
1493 def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None):
1493 def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None):
1494
1494
1495 """This gives control of the child process to the interactive user (the
1495 """This gives control of the child process to the interactive user (the
1496 human at the keyboard). Keystrokes are sent to the child process, and
1496 human at the keyboard). Keystrokes are sent to the child process, and
1497 the stdout and stderr output of the child process is printed. This
1497 the stdout and stderr output of the child process is printed. This
1498 simply echos the child stdout and child stderr to the real stdout and
1498 simply echos the child stdout and child stderr to the real stdout and
1499 it echos the real stdin to the child stdin. When the user types the
1499 it echos the real stdin to the child stdin. When the user types the
1500 escape_character this method will stop. The default for
1500 escape_character this method will stop. The default for
1501 escape_character is ^]. This should not be confused with ASCII 27 --
1501 escape_character is ^]. This should not be confused with ASCII 27 --
1502 the ESC character. ASCII 29 was chosen for historical merit because
1502 the ESC character. ASCII 29 was chosen for historical merit because
1503 this is the character used by 'telnet' as the escape character. The
1503 this is the character used by 'telnet' as the escape character. The
1504 escape_character will not be sent to the child process.
1504 escape_character will not be sent to the child process.
1505
1505
1506 You may pass in optional input and output filter functions. These
1506 You may pass in optional input and output filter functions. These
1507 functions should take a string and return a string. The output_filter
1507 functions should take a string and return a string. The output_filter
1508 will be passed all the output from the child process. The input_filter
1508 will be passed all the output from the child process. The input_filter
1509 will be passed all the keyboard input from the user. The input_filter
1509 will be passed all the keyboard input from the user. The input_filter
1510 is run BEFORE the check for the escape_character.
1510 is run BEFORE the check for the escape_character.
1511
1511
1512 Note that if you change the window size of the parent the SIGWINCH
1512 Note that if you change the window size of the parent the SIGWINCH
1513 signal will not be passed through to the child. If you want the child
1513 signal will not be passed through to the child. If you want the child
1514 window size to change when the parent's window size changes then do
1514 window size to change when the parent's window size changes then do
1515 something like the following example::
1515 something like the following example::
1516
1516
1517 import pexpect, struct, fcntl, termios, signal, sys
1517 import pexpect, struct, fcntl, termios, signal, sys
1518 def sigwinch_passthrough (sig, data):
1518 def sigwinch_passthrough (sig, data):
1519 s = struct.pack("HHHH", 0, 0, 0, 0)
1519 s = struct.pack("HHHH", 0, 0, 0, 0)
1520 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1520 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
1521 global p
1521 global p
1522 p.setwinsize(a[0],a[1])
1522 p.setwinsize(a[0],a[1])
1523 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1523 p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough.
1524 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1524 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1525 p.interact()
1525 p.interact()
1526 """
1526 """
1527
1527
1528 # Flush the buffer.
1528 # Flush the buffer.
1529 if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding))
1529 if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding))
1530 else: self.stdout.write(self.buffer)
1530 else: self.stdout.write(self.buffer)
1531 self.stdout.flush()
1531 self.stdout.flush()
1532 self.buffer = self._empty_buffer
1532 self.buffer = self._empty_buffer
1533 mode = tty.tcgetattr(self.STDIN_FILENO)
1533 mode = tty.tcgetattr(self.STDIN_FILENO)
1534 tty.setraw(self.STDIN_FILENO)
1534 tty.setraw(self.STDIN_FILENO)
1535 try:
1535 try:
1536 self.__interact_copy(escape_character, input_filter, output_filter)
1536 self.__interact_copy(escape_character, input_filter, output_filter)
1537 finally:
1537 finally:
1538 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1538 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1539
1539
1540 def __interact_writen(self, fd, data):
1540 def __interact_writen(self, fd, data):
1541
1541
1542 """This is used by the interact() method.
1542 """This is used by the interact() method.
1543 """
1543 """
1544
1544
1545 while data != b'' and self.isalive():
1545 while data != b'' and self.isalive():
1546 n = os.write(fd, data)
1546 n = os.write(fd, data)
1547 data = data[n:]
1547 data = data[n:]
1548
1548
1549 def __interact_read(self, fd):
1549 def __interact_read(self, fd):
1550
1550
1551 """This is used by the interact() method.
1551 """This is used by the interact() method.
1552 """
1552 """
1553
1553
1554 return os.read(fd, 1000)
1554 return os.read(fd, 1000)
1555
1555
1556 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1556 def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
1557
1557
1558 """This is used by the interact() method.
1558 """This is used by the interact() method.
1559 """
1559 """
1560
1560
1561 while self.isalive():
1561 while self.isalive():
1562 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1562 r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1563 if self.child_fd in r:
1563 if self.child_fd in r:
1564 data = self.__interact_read(self.child_fd)
1564 data = self.__interact_read(self.child_fd)
1565 if output_filter: data = output_filter(data)
1565 if output_filter: data = output_filter(data)
1566 if self.logfile is not None:
1566 if self.logfile is not None:
1567 self.logfile.write (data)
1567 self.logfile.write (data)
1568 self.logfile.flush()
1568 self.logfile.flush()
1569 os.write(self.STDOUT_FILENO, data)
1569 os.write(self.STDOUT_FILENO, data)
1570 if self.STDIN_FILENO in r:
1570 if self.STDIN_FILENO in r:
1571 data = self.__interact_read(self.STDIN_FILENO)
1571 data = self.__interact_read(self.STDIN_FILENO)
1572 if input_filter: data = input_filter(data)
1572 if input_filter: data = input_filter(data)
1573 i = data.rfind(escape_character)
1573 i = data.rfind(escape_character)
1574 if i != -1:
1574 if i != -1:
1575 data = data[:i]
1575 data = data[:i]
1576 self.__interact_writen(self.child_fd, data)
1576 self.__interact_writen(self.child_fd, data)
1577 break
1577 break
1578 self.__interact_writen(self.child_fd, data)
1578 self.__interact_writen(self.child_fd, data)
1579
1579
1580 def __select (self, iwtd, owtd, ewtd, timeout=None):
1580 def __select (self, iwtd, owtd, ewtd, timeout=None):
1581
1581
1582 """This is a wrapper around select.select() that ignores signals. If
1582 """This is a wrapper around select.select() that ignores signals. If
1583 select.select raises a select.error exception and errno is an EINTR
1583 select.select raises a select.error exception and errno is an EINTR
1584 error then it is ignored. Mainly this is used to ignore sigwinch
1584 error then it is ignored. Mainly this is used to ignore sigwinch
1585 (terminal resize). """
1585 (terminal resize). """
1586
1586
1587 # if select() is interrupted by a signal (errno==EINTR) then
1587 # if select() is interrupted by a signal (errno==EINTR) then
1588 # we loop back and enter the select() again.
1588 # we loop back and enter the select() again.
1589 if timeout is not None:
1589 if timeout is not None:
1590 end_time = time.time() + timeout
1590 end_time = time.time() + timeout
1591 while True:
1591 while True:
1592 try:
1592 try:
1593 return select.select (iwtd, owtd, ewtd, timeout)
1593 return select.select (iwtd, owtd, ewtd, timeout)
1594 except select.error as e:
1594 except select.error as e:
1595 if e.args[0] == errno.EINTR:
1595 if e.args[0] == errno.EINTR:
1596 # if we loop back we have to subtract the amount of time we already waited.
1596 # if we loop back we have to subtract the amount of time we already waited.
1597 if timeout is not None:
1597 if timeout is not None:
1598 timeout = end_time - time.time()
1598 timeout = end_time - time.time()
1599 if timeout < 0:
1599 if timeout < 0:
1600 return ([],[],[])
1600 return ([],[],[])
1601 else: # something else caused the select.error, so this really is an exception
1601 else: # something else caused the select.error, so this really is an exception
1602 raise
1602 raise
1603
1603
1604 class spawn(spawnb):
1604 class spawn(spawnb):
1605 """This is the main class interface for Pexpect. Use this class to start
1605 """This is the main class interface for Pexpect. Use this class to start
1606 and control child applications."""
1606 and control child applications."""
1607
1607
1608 _buffer_type = unicode
1608 _buffer_type = unicode
1609 def _cast_buffer_type(self, s):
1609 def _cast_buffer_type(self, s):
1610 return _cast_unicode(s, self.encoding)
1610 return _cast_unicode(s, self.encoding)
1611 _empty_buffer = u''
1611 _empty_buffer = u''
1612 _pty_newline = u'\r\n'
1612 _pty_newline = u'\r\n'
1613
1613
1614 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None,
1614 def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None,
1615 logfile=None, cwd=None, env=None, encoding='utf-8'):
1615 logfile=None, cwd=None, env=None, encoding='utf-8'):
1616 super(spawn, self).__init__(command, args, timeout=timeout, maxread=maxread,
1616 super(spawn, self).__init__(command, args, timeout=timeout, maxread=maxread,
1617 searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env)
1617 searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env)
1618 self.encoding = encoding
1618 self.encoding = encoding
1619
1619
1620 def _prepare_regex_pattern(self, p):
1620 def _prepare_regex_pattern(self, p):
1621 "Recompile bytes regexes as unicode regexes."
1621 "Recompile bytes regexes as unicode regexes."
1622 if isinstance(p.pattern, bytes):
1622 if isinstance(p.pattern, bytes):
1623 p = re.compile(p.pattern.decode(self.encoding), p.flags)
1623 p = re.compile(p.pattern.decode(self.encoding), p.flags)
1624 return p
1624 return p
1625
1625
1626 def read_nonblocking(self, size=1, timeout=-1):
1626 def read_nonblocking(self, size=1, timeout=-1):
1627 return super(spawn, self).read_nonblocking(size=size, timeout=timeout)\
1627 return super(spawn, self).read_nonblocking(size=size, timeout=timeout)\
1628 .decode(self.encoding)
1628 .decode(self.encoding)
1629
1629
1630 read_nonblocking.__doc__ = spawnb.read_nonblocking.__doc__
1630 read_nonblocking.__doc__ = spawnb.read_nonblocking.__doc__
1631
1631
1632
1632
1633 ##############################################################################
1633 ##############################################################################
1634 # End of spawn class
1634 # End of spawn class
1635 ##############################################################################
1635 ##############################################################################
1636
1636
1637 class searcher_string (object):
1637 class searcher_string (object):
1638
1638
1639 """This is a plain string search helper for the spawn.expect_any() method.
1639 """This is a plain string search helper for the spawn.expect_any() method.
1640 This helper class is for speed. For more powerful regex patterns
1640 This helper class is for speed. For more powerful regex patterns
1641 see the helper class, searcher_re.
1641 see the helper class, searcher_re.
1642
1642
1643 Attributes:
1643 Attributes:
1644
1644
1645 eof_index - index of EOF, or -1
1645 eof_index - index of EOF, or -1
1646 timeout_index - index of TIMEOUT, or -1
1646 timeout_index - index of TIMEOUT, or -1
1647
1647
1648 After a successful match by the search() method the following attributes
1648 After a successful match by the search() method the following attributes
1649 are available:
1649 are available:
1650
1650
1651 start - index into the buffer, first byte of match
1651 start - index into the buffer, first byte of match
1652 end - index into the buffer, first byte after match
1652 end - index into the buffer, first byte after match
1653 match - the matching string itself
1653 match - the matching string itself
1654
1654
1655 """
1655 """
1656
1656
1657 def __init__(self, strings):
1657 def __init__(self, strings):
1658
1658
1659 """This creates an instance of searcher_string. This argument 'strings'
1659 """This creates an instance of searcher_string. This argument 'strings'
1660 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1660 may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
1661
1661
1662 self.eof_index = -1
1662 self.eof_index = -1
1663 self.timeout_index = -1
1663 self.timeout_index = -1
1664 self._strings = []
1664 self._strings = []
1665 for n, s in enumerate(strings):
1665 for n, s in enumerate(strings):
1666 if s is EOF:
1666 if s is EOF:
1667 self.eof_index = n
1667 self.eof_index = n
1668 continue
1668 continue
1669 if s is TIMEOUT:
1669 if s is TIMEOUT:
1670 self.timeout_index = n
1670 self.timeout_index = n
1671 continue
1671 continue
1672 self._strings.append((n, s))
1672 self._strings.append((n, s))
1673
1673
1674 def __str__(self):
1674 def __str__(self):
1675
1675
1676 """This returns a human-readable string that represents the state of
1676 """This returns a human-readable string that represents the state of
1677 the object."""
1677 the object."""
1678
1678
1679 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1679 ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ]
1680 ss.append((-1,'searcher_string:'))
1680 ss.append((-1,'searcher_string:'))
1681 if self.eof_index >= 0:
1681 if self.eof_index >= 0:
1682 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1682 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1683 if self.timeout_index >= 0:
1683 if self.timeout_index >= 0:
1684 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1684 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1685 ss.sort()
1685 ss.sort()
1686 return '\n'.join(a[1] for a in ss)
1686 return '\n'.join(a[1] for a in ss)
1687
1687
1688 def search(self, buffer, freshlen, searchwindowsize=None):
1688 def search(self, buffer, freshlen, searchwindowsize=None):
1689
1689
1690 """This searches 'buffer' for the first occurence of one of the search
1690 """This searches 'buffer' for the first occurence of one of the search
1691 strings. 'freshlen' must indicate the number of bytes at the end of
1691 strings. 'freshlen' must indicate the number of bytes at the end of
1692 'buffer' which have not been searched before. It helps to avoid
1692 'buffer' which have not been searched before. It helps to avoid
1693 searching the same, possibly big, buffer over and over again.
1693 searching the same, possibly big, buffer over and over again.
1694
1694
1695 See class spawn for the 'searchwindowsize' argument.
1695 See class spawn for the 'searchwindowsize' argument.
1696
1696
1697 If there is a match this returns the index of that string, and sets
1697 If there is a match this returns the index of that string, and sets
1698 'start', 'end' and 'match'. Otherwise, this returns -1. """
1698 'start', 'end' and 'match'. Otherwise, this returns -1. """
1699
1699
1700 absurd_match = len(buffer)
1700 absurd_match = len(buffer)
1701 first_match = absurd_match
1701 first_match = absurd_match
1702
1702
1703 # 'freshlen' helps a lot here. Further optimizations could
1703 # 'freshlen' helps a lot here. Further optimizations could
1704 # possibly include:
1704 # possibly include:
1705 #
1705 #
1706 # using something like the Boyer-Moore Fast String Searching
1706 # using something like the Boyer-Moore Fast String Searching
1707 # Algorithm; pre-compiling the search through a list of
1707 # Algorithm; pre-compiling the search through a list of
1708 # strings into something that can scan the input once to
1708 # strings into something that can scan the input once to
1709 # search for all N strings; realize that if we search for
1709 # search for all N strings; realize that if we search for
1710 # ['bar', 'baz'] and the input is '...foo' we need not bother
1710 # ['bar', 'baz'] and the input is '...foo' we need not bother
1711 # rescanning until we've read three more bytes.
1711 # rescanning until we've read three more bytes.
1712 #
1712 #
1713 # Sadly, I don't know enough about this interesting topic. /grahn
1713 # Sadly, I don't know enough about this interesting topic. /grahn
1714
1714
1715 for index, s in self._strings:
1715 for index, s in self._strings:
1716 if searchwindowsize is None:
1716 if searchwindowsize is None:
1717 # the match, if any, can only be in the fresh data,
1717 # the match, if any, can only be in the fresh data,
1718 # or at the very end of the old data
1718 # or at the very end of the old data
1719 offset = -(freshlen+len(s))
1719 offset = -(freshlen+len(s))
1720 else:
1720 else:
1721 # better obey searchwindowsize
1721 # better obey searchwindowsize
1722 offset = -searchwindowsize
1722 offset = -searchwindowsize
1723 n = buffer.find(s, offset)
1723 n = buffer.find(s, offset)
1724 if n >= 0 and n < first_match:
1724 if n >= 0 and n < first_match:
1725 first_match = n
1725 first_match = n
1726 best_index, best_match = index, s
1726 best_index, best_match = index, s
1727 if first_match == absurd_match:
1727 if first_match == absurd_match:
1728 return -1
1728 return -1
1729 self.match = best_match
1729 self.match = best_match
1730 self.start = first_match
1730 self.start = first_match
1731 self.end = self.start + len(self.match)
1731 self.end = self.start + len(self.match)
1732 return best_index
1732 return best_index
1733
1733
1734 class searcher_re (object):
1734 class searcher_re (object):
1735
1735
1736 """This is regular expression string search helper for the
1736 """This is regular expression string search helper for the
1737 spawn.expect_any() method. This helper class is for powerful
1737 spawn.expect_any() method. This helper class is for powerful
1738 pattern matching. For speed, see the helper class, searcher_string.
1738 pattern matching. For speed, see the helper class, searcher_string.
1739
1739
1740 Attributes:
1740 Attributes:
1741
1741
1742 eof_index - index of EOF, or -1
1742 eof_index - index of EOF, or -1
1743 timeout_index - index of TIMEOUT, or -1
1743 timeout_index - index of TIMEOUT, or -1
1744
1744
1745 After a successful match by the search() method the following attributes
1745 After a successful match by the search() method the following attributes
1746 are available:
1746 are available:
1747
1747
1748 start - index into the buffer, first byte of match
1748 start - index into the buffer, first byte of match
1749 end - index into the buffer, first byte after match
1749 end - index into the buffer, first byte after match
1750 match - the re.match object returned by a succesful re.search
1750 match - the re.match object returned by a succesful re.search
1751
1751
1752 """
1752 """
1753
1753
1754 def __init__(self, patterns):
1754 def __init__(self, patterns):
1755
1755
1756 """This creates an instance that searches for 'patterns' Where
1756 """This creates an instance that searches for 'patterns' Where
1757 'patterns' may be a list or other sequence of compiled regular
1757 'patterns' may be a list or other sequence of compiled regular
1758 expressions, or the EOF or TIMEOUT types."""
1758 expressions, or the EOF or TIMEOUT types."""
1759
1759
1760 self.eof_index = -1
1760 self.eof_index = -1
1761 self.timeout_index = -1
1761 self.timeout_index = -1
1762 self._searches = []
1762 self._searches = []
1763 for n, s in enumerate(patterns):
1763 for n, s in enumerate(patterns):
1764 if s is EOF:
1764 if s is EOF:
1765 self.eof_index = n
1765 self.eof_index = n
1766 continue
1766 continue
1767 if s is TIMEOUT:
1767 if s is TIMEOUT:
1768 self.timeout_index = n
1768 self.timeout_index = n
1769 continue
1769 continue
1770 self._searches.append((n, s))
1770 self._searches.append((n, s))
1771
1771
1772 def __str__(self):
1772 def __str__(self):
1773
1773
1774 """This returns a human-readable string that represents the state of
1774 """This returns a human-readable string that represents the state of
1775 the object."""
1775 the object."""
1776
1776
1777 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1777 ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches]
1778 ss.append((-1,'searcher_re:'))
1778 ss.append((-1,'searcher_re:'))
1779 if self.eof_index >= 0:
1779 if self.eof_index >= 0:
1780 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1780 ss.append ((self.eof_index,' %d: EOF' % self.eof_index))
1781 if self.timeout_index >= 0:
1781 if self.timeout_index >= 0:
1782 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1782 ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index))
1783 ss.sort()
1783 ss.sort()
1784 return '\n'.join(a[1] for a in ss)
1784 return '\n'.join(a[1] for a in ss)
1785
1785
1786 def search(self, buffer, freshlen, searchwindowsize=None):
1786 def search(self, buffer, freshlen, searchwindowsize=None):
1787
1787
1788 """This searches 'buffer' for the first occurence of one of the regular
1788 """This searches 'buffer' for the first occurence of one of the regular
1789 expressions. 'freshlen' must indicate the number of bytes at the end of
1789 expressions. 'freshlen' must indicate the number of bytes at the end of
1790 'buffer' which have not been searched before.
1790 'buffer' which have not been searched before.
1791
1791
1792 See class spawn for the 'searchwindowsize' argument.
1792 See class spawn for the 'searchwindowsize' argument.
1793
1793
1794 If there is a match this returns the index of that string, and sets
1794 If there is a match this returns the index of that string, and sets
1795 'start', 'end' and 'match'. Otherwise, returns -1."""
1795 'start', 'end' and 'match'. Otherwise, returns -1."""
1796
1796
1797 absurd_match = len(buffer)
1797 absurd_match = len(buffer)
1798 first_match = absurd_match
1798 first_match = absurd_match
1799 # 'freshlen' doesn't help here -- we cannot predict the
1799 # 'freshlen' doesn't help here -- we cannot predict the
1800 # length of a match, and the re module provides no help.
1800 # length of a match, and the re module provides no help.
1801 if searchwindowsize is None:
1801 if searchwindowsize is None:
1802 searchstart = 0
1802 searchstart = 0
1803 else:
1803 else:
1804 searchstart = max(0, len(buffer)-searchwindowsize)
1804 searchstart = max(0, len(buffer)-searchwindowsize)
1805 for index, s in self._searches:
1805 for index, s in self._searches:
1806 match = s.search(buffer, searchstart)
1806 match = s.search(buffer, searchstart)
1807 if match is None:
1807 if match is None:
1808 continue
1808 continue
1809 n = match.start()
1809 n = match.start()
1810 if n < first_match:
1810 if n < first_match:
1811 first_match = n
1811 first_match = n
1812 the_match = match
1812 the_match = match
1813 best_index = index
1813 best_index = index
1814 if first_match == absurd_match:
1814 if first_match == absurd_match:
1815 return -1
1815 return -1
1816 self.start = first_match
1816 self.start = first_match
1817 self.match = the_match
1817 self.match = the_match
1818 self.end = self.match.end()
1818 self.end = self.match.end()
1819 return best_index
1819 return best_index
1820
1820
1821 def which (filename):
1821 def which (filename):
1822
1822
1823 """This takes a given filename; tries to find it in the environment path;
1823 """This takes a given filename; tries to find it in the environment path;
1824 then checks if it is executable. This returns the full path to the filename
1824 then checks if it is executable. This returns the full path to the filename
1825 if found and executable. Otherwise this returns None."""
1825 if found and executable. Otherwise this returns None."""
1826
1826
1827 # Special case where filename already contains a path.
1827 # Special case where filename already contains a path.
1828 if os.path.dirname(filename) != '':
1828 if os.path.dirname(filename) != '':
1829 if os.access (filename, os.X_OK):
1829 if os.access (filename, os.X_OK):
1830 return filename
1830 return filename
1831
1831
1832 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1832 if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
1833 p = os.defpath
1833 p = os.defpath
1834 else:
1834 else:
1835 p = os.environ['PATH']
1835 p = os.environ['PATH']
1836
1836
1837 pathlist = p.split(os.pathsep)
1837 pathlist = p.split(os.pathsep)
1838
1838
1839 for path in pathlist:
1839 for path in pathlist:
1840 f = os.path.join(path, filename)
1840 f = os.path.join(path, filename)
1841 if os.access(f, os.X_OK):
1841 if os.access(f, os.X_OK):
1842 return f
1842 return f
1843 return None
1843 return None
1844
1844
1845 def split_command_line(command_line):
1845 def split_command_line(command_line):
1846
1846
1847 """This splits a command line into a list of arguments. It splits arguments
1847 """This splits a command line into a list of arguments. It splits arguments
1848 on spaces, but handles embedded quotes, doublequotes, and escaped
1848 on spaces, but handles embedded quotes, doublequotes, and escaped
1849 characters. It's impossible to do this with a regular expression, so I
1849 characters. It's impossible to do this with a regular expression, so I
1850 wrote a little state machine to parse the command line. """
1850 wrote a little state machine to parse the command line. """
1851
1851
1852 arg_list = []
1852 arg_list = []
1853 arg = ''
1853 arg = ''
1854
1854
1855 # Constants to name the states we can be in.
1855 # Constants to name the states we can be in.
1856 state_basic = 0
1856 state_basic = 0
1857 state_esc = 1
1857 state_esc = 1
1858 state_singlequote = 2
1858 state_singlequote = 2
1859 state_doublequote = 3
1859 state_doublequote = 3
1860 state_whitespace = 4 # The state of consuming whitespace between commands.
1860 state_whitespace = 4 # The state of consuming whitespace between commands.
1861 state = state_basic
1861 state = state_basic
1862
1862
1863 for c in command_line:
1863 for c in command_line:
1864 if state == state_basic or state == state_whitespace:
1864 if state == state_basic or state == state_whitespace:
1865 if c == '\\': # Escape the next character
1865 if c == '\\': # Escape the next character
1866 state = state_esc
1866 state = state_esc
1867 elif c == r"'": # Handle single quote
1867 elif c == r"'": # Handle single quote
1868 state = state_singlequote
1868 state = state_singlequote
1869 elif c == r'"': # Handle double quote
1869 elif c == r'"': # Handle double quote
1870 state = state_doublequote
1870 state = state_doublequote
1871 elif c.isspace():
1871 elif c.isspace():
1872 # Add arg to arg_list if we aren't in the middle of whitespace.
1872 # Add arg to arg_list if we aren't in the middle of whitespace.
1873 if state == state_whitespace:
1873 if state == state_whitespace:
1874 None # Do nothing.
1874 None # Do nothing.
1875 else:
1875 else:
1876 arg_list.append(arg)
1876 arg_list.append(arg)
1877 arg = ''
1877 arg = ''
1878 state = state_whitespace
1878 state = state_whitespace
1879 else:
1879 else:
1880 arg = arg + c
1880 arg = arg + c
1881 state = state_basic
1881 state = state_basic
1882 elif state == state_esc:
1882 elif state == state_esc:
1883 arg = arg + c
1883 arg = arg + c
1884 state = state_basic
1884 state = state_basic
1885 elif state == state_singlequote:
1885 elif state == state_singlequote:
1886 if c == r"'":
1886 if c == r"'":
1887 state = state_basic
1887 state = state_basic
1888 else:
1888 else:
1889 arg = arg + c
1889 arg = arg + c
1890 elif state == state_doublequote:
1890 elif state == state_doublequote:
1891 if c == r'"':
1891 if c == r'"':
1892 state = state_basic
1892 state = state_basic
1893 else:
1893 else:
1894 arg = arg + c
1894 arg = arg + c
1895
1895
1896 if arg != '':
1896 if arg != '':
1897 arg_list.append(arg)
1897 arg_list.append(arg)
1898 return arg_list
1898 return arg_list
1899
1899
1900 # vi:set sr et ts=4 sw=4 ft=python :
1900 # vi:set sr et ts=4 sw=4 ft=python :
@@ -1,727 +1,728 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16
17
17 import bdb
18 import bdb
18 import os
19 import os
19 import re
20 import re
20 import sys
21 import sys
21 import textwrap
22 import textwrap
22
23
23 # We need to use nested to support python 2.6, once we move to >=2.7, we can
24 # We need to use nested to support python 2.6, once we move to >=2.7, we can
24 # use the with keyword's new builtin support for nested managers
25 # use the with keyword's new builtin support for nested managers
25 try:
26 try:
26 from contextlib import nested
27 from contextlib import nested
27 except:
28 except:
28 from IPython.utils.nested_context import nested
29 from IPython.utils.nested_context import nested
29
30
30 from IPython.core.error import TryNext, UsageError
31 from IPython.core.error import TryNext, UsageError
31 from IPython.core.usage import interactive_usage, default_banner
32 from IPython.core.usage import interactive_usage, default_banner
32 from IPython.core.inputsplitter import IPythonInputSplitter
33 from IPython.core.inputsplitter import IPythonInputSplitter
33 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
34 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
34 from IPython.core.magic import Magics, magics_class, line_magic
35 from IPython.core.magic import Magics, magics_class, line_magic
35 from IPython.testing.skipdoctest import skip_doctest
36 from IPython.testing.skipdoctest import skip_doctest
36 from IPython.utils.encoding import get_stream_enc
37 from IPython.utils.encoding import get_stream_enc
37 from IPython.utils import py3compat
38 from IPython.utils import py3compat
38 from IPython.utils.terminal import toggle_set_term_title, set_term_title
39 from IPython.utils.terminal import toggle_set_term_title, set_term_title
39 from IPython.utils.process import abbrev_cwd
40 from IPython.utils.process import abbrev_cwd
40 from IPython.utils.warn import warn, error
41 from IPython.utils.warn import warn, error
41 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
42 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
42 from IPython.utils.traitlets import Integer, CBool, Unicode
43 from IPython.utils.traitlets import Integer, CBool, Unicode
43
44
44 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
45 # Utilities
46 # Utilities
46 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
47
48
48 def get_default_editor():
49 def get_default_editor():
49 try:
50 try:
50 ed = os.environ['EDITOR']
51 ed = os.environ['EDITOR']
51 except KeyError:
52 except KeyError:
52 if os.name == 'posix':
53 if os.name == 'posix':
53 ed = 'vi' # the only one guaranteed to be there!
54 ed = 'vi' # the only one guaranteed to be there!
54 else:
55 else:
55 ed = 'notepad' # same in Windows!
56 ed = 'notepad' # same in Windows!
56 return ed
57 return ed
57
58
58
59
59 def get_pasted_lines(sentinel, l_input=py3compat.input):
60 def get_pasted_lines(sentinel, l_input=py3compat.input):
60 """ Yield pasted lines until the user enters the given sentinel value.
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 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
63 % sentinel
64 % sentinel)
64 while True:
65 while True:
65 try:
66 try:
66 l = l_input(':')
67 l = l_input(':')
67 if l == sentinel:
68 if l == sentinel:
68 return
69 return
69 else:
70 else:
70 yield l
71 yield l
71 except EOFError:
72 except EOFError:
72 print '<EOF>'
73 print('<EOF>')
73 return
74 return
74
75
75
76
76 #------------------------------------------------------------------------
77 #------------------------------------------------------------------------
77 # Terminal-specific magics
78 # Terminal-specific magics
78 #------------------------------------------------------------------------
79 #------------------------------------------------------------------------
79
80
80 @magics_class
81 @magics_class
81 class TerminalMagics(Magics):
82 class TerminalMagics(Magics):
82 def __init__(self, shell):
83 def __init__(self, shell):
83 super(TerminalMagics, self).__init__(shell)
84 super(TerminalMagics, self).__init__(shell)
84 self.input_splitter = IPythonInputSplitter(input_mode='line')
85 self.input_splitter = IPythonInputSplitter(input_mode='line')
85
86
86 def cleanup_input(self, block):
87 def cleanup_input(self, block):
87 """Apply all possible IPython cleanups to an input block.
88 """Apply all possible IPython cleanups to an input block.
88
89
89 This means:
90 This means:
90
91
91 - remove any global leading whitespace (dedent)
92 - remove any global leading whitespace (dedent)
92 - remove any email quotes ('>') if they are present in *all* lines
93 - remove any email quotes ('>') if they are present in *all* lines
93 - apply all static inputsplitter transforms and break into sub-blocks
94 - apply all static inputsplitter transforms and break into sub-blocks
94 - apply prefilter() to each sub-block that is a single line.
95 - apply prefilter() to each sub-block that is a single line.
95
96
96 Parameters
97 Parameters
97 ----------
98 ----------
98 block : str
99 block : str
99 A possibly multiline input string of code.
100 A possibly multiline input string of code.
100
101
101 Returns
102 Returns
102 -------
103 -------
103 transformed block : str
104 transformed block : str
104 The input, with all transformations above applied.
105 The input, with all transformations above applied.
105 """
106 """
106 # We have to effectively implement client-side the loop that is done by
107 # We have to effectively implement client-side the loop that is done by
107 # the terminal frontend, and furthermore do it on a block that can
108 # the terminal frontend, and furthermore do it on a block that can
108 # possibly contain multiple statments pasted in one go.
109 # possibly contain multiple statments pasted in one go.
109
110
110 # First, run the input through the block splitting code. We should
111 # First, run the input through the block splitting code. We should
111 # eventually make this a self-contained method in the inputsplitter.
112 # eventually make this a self-contained method in the inputsplitter.
112 isp = self.input_splitter
113 isp = self.input_splitter
113 isp.reset()
114 isp.reset()
114 b = textwrap.dedent(block)
115 b = textwrap.dedent(block)
115
116
116 # Remove email quotes first. These must be consistently applied to
117 # Remove email quotes first. These must be consistently applied to
117 # *all* lines to be removed
118 # *all* lines to be removed
118 b = strip_email_quotes(b)
119 b = strip_email_quotes(b)
119
120
120 # Split the input into independent sub-blocks so we can later do
121 # Split the input into independent sub-blocks so we can later do
121 # prefiltering (which must be done *only* to single-line inputs)
122 # prefiltering (which must be done *only* to single-line inputs)
122 blocks = []
123 blocks = []
123 last_block = []
124 last_block = []
124 for line in b.splitlines():
125 for line in b.splitlines():
125 isp.push(line)
126 isp.push(line)
126 last_block.append(line)
127 last_block.append(line)
127 if not isp.push_accepts_more():
128 if not isp.push_accepts_more():
128 blocks.append(isp.source_reset())
129 blocks.append(isp.source_reset())
129 last_block = []
130 last_block = []
130 if last_block:
131 if last_block:
131 blocks.append('\n'.join(last_block))
132 blocks.append('\n'.join(last_block))
132
133
133 # Now, apply prefiltering to any one-line block to match the behavior
134 # Now, apply prefiltering to any one-line block to match the behavior
134 # of the interactive terminal
135 # of the interactive terminal
135 final_blocks = []
136 final_blocks = []
136 for block in blocks:
137 for block in blocks:
137 lines = block.splitlines()
138 lines = block.splitlines()
138 if len(lines) == 1:
139 if len(lines) == 1:
139 final_blocks.append(self.shell.prefilter(lines[0]))
140 final_blocks.append(self.shell.prefilter(lines[0]))
140 else:
141 else:
141 final_blocks.append(block)
142 final_blocks.append(block)
142
143
143 # We now have the final version of the input code as a list of blocks,
144 # We now have the final version of the input code as a list of blocks,
144 # with all inputsplitter transformations applied and single-line blocks
145 # with all inputsplitter transformations applied and single-line blocks
145 # run through prefilter. For further processing, turn into a single
146 # run through prefilter. For further processing, turn into a single
146 # string as the rest of our apis use string inputs.
147 # string as the rest of our apis use string inputs.
147 return '\n'.join(final_blocks)
148 return '\n'.join(final_blocks)
148
149
149 def store_or_execute(self, block, name):
150 def store_or_execute(self, block, name):
150 """ Execute a block, or store it in a variable, per the user's request.
151 """ Execute a block, or store it in a variable, per the user's request.
151 """
152 """
152 b = self.cleanup_input(block)
153 b = self.cleanup_input(block)
153 if name:
154 if name:
154 # If storing it for further editing
155 # If storing it for further editing
155 self.shell.user_ns[name] = SList(b.splitlines())
156 self.shell.user_ns[name] = SList(b.splitlines())
156 print "Block assigned to '%s'" % name
157 print("Block assigned to '%s'" % name)
157 else:
158 else:
158 self.shell.user_ns['pasted_block'] = b
159 self.shell.user_ns['pasted_block'] = b
159 self.shell.run_cell(b)
160 self.shell.run_cell(b)
160
161
161 def rerun_pasted(self, name='pasted_block'):
162 def rerun_pasted(self, name='pasted_block'):
162 """ Rerun a previously pasted command.
163 """ Rerun a previously pasted command.
163 """
164 """
164 b = self.shell.user_ns.get(name)
165 b = self.shell.user_ns.get(name)
165
166
166 # Sanity checks
167 # Sanity checks
167 if b is None:
168 if b is None:
168 raise UsageError('No previous pasted block available')
169 raise UsageError('No previous pasted block available')
169 if not isinstance(b, basestring):
170 if not isinstance(b, basestring):
170 raise UsageError(
171 raise UsageError(
171 "Variable 'pasted_block' is not a string, can't execute")
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 self.shell.run_cell(b)
175 self.shell.run_cell(b)
175
176
176 @line_magic
177 @line_magic
177 def autoindent(self, parameter_s = ''):
178 def autoindent(self, parameter_s = ''):
178 """Toggle autoindent on/off (if available)."""
179 """Toggle autoindent on/off (if available)."""
179
180
180 self.shell.set_autoindent()
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 @skip_doctest
184 @skip_doctest
184 @line_magic
185 @line_magic
185 def cpaste(self, parameter_s=''):
186 def cpaste(self, parameter_s=''):
186 """Paste & execute a pre-formatted code block from clipboard.
187 """Paste & execute a pre-formatted code block from clipboard.
187
188
188 You must terminate the block with '--' (two minus-signs) or Ctrl-D
189 You must terminate the block with '--' (two minus-signs) or Ctrl-D
189 alone on the line. You can also provide your own sentinel with '%paste
190 alone on the line. You can also provide your own sentinel with '%paste
190 -s %%' ('%%' is the new sentinel for this operation)
191 -s %%' ('%%' is the new sentinel for this operation)
191
192
192 The block is dedented prior to execution to enable execution of method
193 The block is dedented prior to execution to enable execution of method
193 definitions. '>' and '+' characters at the beginning of a line are
194 definitions. '>' and '+' characters at the beginning of a line are
194 ignored, to allow pasting directly from e-mails, diff files and
195 ignored, to allow pasting directly from e-mails, diff files and
195 doctests (the '...' continuation prompt is also stripped). The
196 doctests (the '...' continuation prompt is also stripped). The
196 executed block is also assigned to variable named 'pasted_block' for
197 executed block is also assigned to variable named 'pasted_block' for
197 later editing with '%edit pasted_block'.
198 later editing with '%edit pasted_block'.
198
199
199 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
200 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
200 This assigns the pasted block to variable 'foo' as string, without
201 This assigns the pasted block to variable 'foo' as string, without
201 dedenting or executing it (preceding >>> and + is still stripped)
202 dedenting or executing it (preceding >>> and + is still stripped)
202
203
203 '%cpaste -r' re-executes the block previously entered by cpaste.
204 '%cpaste -r' re-executes the block previously entered by cpaste.
204
205
205 Do not be alarmed by garbled output on Windows (it's a readline bug).
206 Do not be alarmed by garbled output on Windows (it's a readline bug).
206 Just press enter and type -- (and press enter again) and the block
207 Just press enter and type -- (and press enter again) and the block
207 will be what was just pasted.
208 will be what was just pasted.
208
209
209 IPython statements (magics, shell escapes) are not supported (yet).
210 IPython statements (magics, shell escapes) are not supported (yet).
210
211
211 See also
212 See also
212 --------
213 --------
213 paste: automatically pull code from clipboard.
214 paste: automatically pull code from clipboard.
214
215
215 Examples
216 Examples
216 --------
217 --------
217 ::
218 ::
218
219
219 In [8]: %cpaste
220 In [8]: %cpaste
220 Pasting code; enter '--' alone on the line to stop.
221 Pasting code; enter '--' alone on the line to stop.
221 :>>> a = ["world!", "Hello"]
222 :>>> a = ["world!", "Hello"]
222 :>>> print " ".join(sorted(a))
223 :>>> print " ".join(sorted(a))
223 :--
224 :--
224 Hello world!
225 Hello world!
225 """
226 """
226 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
227 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
227 if 'r' in opts:
228 if 'r' in opts:
228 self.rerun_pasted()
229 self.rerun_pasted()
229 return
230 return
230
231
231 sentinel = opts.get('s', '--')
232 sentinel = opts.get('s', '--')
232 block = '\n'.join(get_pasted_lines(sentinel))
233 block = '\n'.join(get_pasted_lines(sentinel))
233 self.store_or_execute(block, name)
234 self.store_or_execute(block, name)
234
235
235 @line_magic
236 @line_magic
236 def paste(self, parameter_s=''):
237 def paste(self, parameter_s=''):
237 """Paste & execute a pre-formatted code block from clipboard.
238 """Paste & execute a pre-formatted code block from clipboard.
238
239
239 The text is pulled directly from the clipboard without user
240 The text is pulled directly from the clipboard without user
240 intervention and printed back on the screen before execution (unless
241 intervention and printed back on the screen before execution (unless
241 the -q flag is given to force quiet mode).
242 the -q flag is given to force quiet mode).
242
243
243 The block is dedented prior to execution to enable execution of method
244 The block is dedented prior to execution to enable execution of method
244 definitions. '>' and '+' characters at the beginning of a line are
245 definitions. '>' and '+' characters at the beginning of a line are
245 ignored, to allow pasting directly from e-mails, diff files and
246 ignored, to allow pasting directly from e-mails, diff files and
246 doctests (the '...' continuation prompt is also stripped). The
247 doctests (the '...' continuation prompt is also stripped). The
247 executed block is also assigned to variable named 'pasted_block' for
248 executed block is also assigned to variable named 'pasted_block' for
248 later editing with '%edit pasted_block'.
249 later editing with '%edit pasted_block'.
249
250
250 You can also pass a variable name as an argument, e.g. '%paste foo'.
251 You can also pass a variable name as an argument, e.g. '%paste foo'.
251 This assigns the pasted block to variable 'foo' as string, without
252 This assigns the pasted block to variable 'foo' as string, without
252 executing it (preceding >>> and + is still stripped).
253 executing it (preceding >>> and + is still stripped).
253
254
254 Options
255 Options
255 -------
256 -------
256
257
257 -r: re-executes the block previously entered by cpaste.
258 -r: re-executes the block previously entered by cpaste.
258
259
259 -q: quiet mode: do not echo the pasted text back to the terminal.
260 -q: quiet mode: do not echo the pasted text back to the terminal.
260
261
261 IPython statements (magics, shell escapes) are not supported (yet).
262 IPython statements (magics, shell escapes) are not supported (yet).
262
263
263 See also
264 See also
264 --------
265 --------
265 cpaste: manually paste code into terminal until you mark its end.
266 cpaste: manually paste code into terminal until you mark its end.
266 """
267 """
267 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
268 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
268 if 'r' in opts:
269 if 'r' in opts:
269 self.rerun_pasted()
270 self.rerun_pasted()
270 return
271 return
271 try:
272 try:
272 block = self.shell.hooks.clipboard_get()
273 block = self.shell.hooks.clipboard_get()
273 except TryNext as clipboard_exc:
274 except TryNext as clipboard_exc:
274 message = getattr(clipboard_exc, 'args')
275 message = getattr(clipboard_exc, 'args')
275 if message:
276 if message:
276 error(message[0])
277 error(message[0])
277 else:
278 else:
278 error('Could not get text from the clipboard.')
279 error('Could not get text from the clipboard.')
279 return
280 return
280
281
281 # By default, echo back to terminal unless quiet mode is requested
282 # By default, echo back to terminal unless quiet mode is requested
282 if 'q' not in opts:
283 if 'q' not in opts:
283 write = self.shell.write
284 write = self.shell.write
284 write(self.shell.pycolorize(block))
285 write(self.shell.pycolorize(block))
285 if not block.endswith('\n'):
286 if not block.endswith('\n'):
286 write('\n')
287 write('\n')
287 write("## -- End pasted text --\n")
288 write("## -- End pasted text --\n")
288
289
289 self.store_or_execute(block, name)
290 self.store_or_execute(block, name)
290
291
291 # Class-level: add a '%cls' magic only on Windows
292 # Class-level: add a '%cls' magic only on Windows
292 if sys.platform == 'win32':
293 if sys.platform == 'win32':
293 @line_magic
294 @line_magic
294 def cls(self, s):
295 def cls(self, s):
295 """Clear screen.
296 """Clear screen.
296 """
297 """
297 os.system("cls")
298 os.system("cls")
298
299
299 #-----------------------------------------------------------------------------
300 #-----------------------------------------------------------------------------
300 # Main class
301 # Main class
301 #-----------------------------------------------------------------------------
302 #-----------------------------------------------------------------------------
302
303
303 class TerminalInteractiveShell(InteractiveShell):
304 class TerminalInteractiveShell(InteractiveShell):
304
305
305 autoedit_syntax = CBool(False, config=True,
306 autoedit_syntax = CBool(False, config=True,
306 help="auto editing of files with syntax errors.")
307 help="auto editing of files with syntax errors.")
307 banner = Unicode('')
308 banner = Unicode('')
308 banner1 = Unicode(default_banner, config=True,
309 banner1 = Unicode(default_banner, config=True,
309 help="""The part of the banner to be printed before the profile"""
310 help="""The part of the banner to be printed before the profile"""
310 )
311 )
311 banner2 = Unicode('', config=True,
312 banner2 = Unicode('', config=True,
312 help="""The part of the banner to be printed after the profile"""
313 help="""The part of the banner to be printed after the profile"""
313 )
314 )
314 confirm_exit = CBool(True, config=True,
315 confirm_exit = CBool(True, config=True,
315 help="""
316 help="""
316 Set to confirm when you try to exit IPython with an EOF (Control-D
317 Set to confirm when you try to exit IPython with an EOF (Control-D
317 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
318 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
318 you can force a direct exit without any confirmation.""",
319 you can force a direct exit without any confirmation.""",
319 )
320 )
320 # This display_banner only controls whether or not self.show_banner()
321 # This display_banner only controls whether or not self.show_banner()
321 # is called when mainloop/interact are called. The default is False
322 # is called when mainloop/interact are called. The default is False
322 # because for the terminal based application, the banner behavior
323 # because for the terminal based application, the banner behavior
323 # is controlled by Global.display_banner, which IPythonApp looks at
324 # is controlled by Global.display_banner, which IPythonApp looks at
324 # to determine if *it* should call show_banner() by hand or not.
325 # to determine if *it* should call show_banner() by hand or not.
325 display_banner = CBool(False) # This isn't configurable!
326 display_banner = CBool(False) # This isn't configurable!
326 embedded = CBool(False)
327 embedded = CBool(False)
327 embedded_active = CBool(False)
328 embedded_active = CBool(False)
328 editor = Unicode(get_default_editor(), config=True,
329 editor = Unicode(get_default_editor(), config=True,
329 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
330 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
330 )
331 )
331 pager = Unicode('less', config=True,
332 pager = Unicode('less', config=True,
332 help="The shell program to be used for paging.")
333 help="The shell program to be used for paging.")
333
334
334 screen_length = Integer(0, config=True,
335 screen_length = Integer(0, config=True,
335 help=
336 help=
336 """Number of lines of your screen, used to control printing of very
337 """Number of lines of your screen, used to control printing of very
337 long strings. Strings longer than this number of lines will be sent
338 long strings. Strings longer than this number of lines will be sent
338 through a pager instead of directly printed. The default value for
339 through a pager instead of directly printed. The default value for
339 this is 0, which means IPython will auto-detect your screen size every
340 this is 0, which means IPython will auto-detect your screen size every
340 time it needs to print certain potentially long strings (this doesn't
341 time it needs to print certain potentially long strings (this doesn't
341 change the behavior of the 'print' keyword, it's only triggered
342 change the behavior of the 'print' keyword, it's only triggered
342 internally). If for some reason this isn't working well (it needs
343 internally). If for some reason this isn't working well (it needs
343 curses support), specify it yourself. Otherwise don't change the
344 curses support), specify it yourself. Otherwise don't change the
344 default.""",
345 default.""",
345 )
346 )
346 term_title = CBool(False, config=True,
347 term_title = CBool(False, config=True,
347 help="Enable auto setting the terminal title."
348 help="Enable auto setting the terminal title."
348 )
349 )
349
350
350 # In the terminal, GUI control is done via PyOS_InputHook
351 # In the terminal, GUI control is done via PyOS_InputHook
351 from IPython.lib.inputhook import enable_gui
352 from IPython.lib.inputhook import enable_gui
352 enable_gui = staticmethod(enable_gui)
353 enable_gui = staticmethod(enable_gui)
353
354
354 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
355 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
355 user_ns=None, user_module=None, custom_exceptions=((),None),
356 user_ns=None, user_module=None, custom_exceptions=((),None),
356 usage=None, banner1=None, banner2=None, display_banner=None):
357 usage=None, banner1=None, banner2=None, display_banner=None):
357
358
358 super(TerminalInteractiveShell, self).__init__(
359 super(TerminalInteractiveShell, self).__init__(
359 config=config, profile_dir=profile_dir, user_ns=user_ns,
360 config=config, profile_dir=profile_dir, user_ns=user_ns,
360 user_module=user_module, custom_exceptions=custom_exceptions
361 user_module=user_module, custom_exceptions=custom_exceptions
361 )
362 )
362 # use os.system instead of utils.process.system by default,
363 # use os.system instead of utils.process.system by default,
363 # because piped system doesn't make sense in the Terminal:
364 # because piped system doesn't make sense in the Terminal:
364 self.system = self.system_raw
365 self.system = self.system_raw
365
366
366 self.init_term_title()
367 self.init_term_title()
367 self.init_usage(usage)
368 self.init_usage(usage)
368 self.init_banner(banner1, banner2, display_banner)
369 self.init_banner(banner1, banner2, display_banner)
369
370
370 #-------------------------------------------------------------------------
371 #-------------------------------------------------------------------------
371 # Things related to the terminal
372 # Things related to the terminal
372 #-------------------------------------------------------------------------
373 #-------------------------------------------------------------------------
373
374
374 @property
375 @property
375 def usable_screen_length(self):
376 def usable_screen_length(self):
376 if self.screen_length == 0:
377 if self.screen_length == 0:
377 return 0
378 return 0
378 else:
379 else:
379 num_lines_bot = self.separate_in.count('\n')+1
380 num_lines_bot = self.separate_in.count('\n')+1
380 return self.screen_length - num_lines_bot
381 return self.screen_length - num_lines_bot
381
382
382 def init_term_title(self):
383 def init_term_title(self):
383 # Enable or disable the terminal title.
384 # Enable or disable the terminal title.
384 if self.term_title:
385 if self.term_title:
385 toggle_set_term_title(True)
386 toggle_set_term_title(True)
386 set_term_title('IPython: ' + abbrev_cwd())
387 set_term_title('IPython: ' + abbrev_cwd())
387 else:
388 else:
388 toggle_set_term_title(False)
389 toggle_set_term_title(False)
389
390
390 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
391 # Things related to aliases
392 # Things related to aliases
392 #-------------------------------------------------------------------------
393 #-------------------------------------------------------------------------
393
394
394 def init_alias(self):
395 def init_alias(self):
395 # The parent class defines aliases that can be safely used with any
396 # The parent class defines aliases that can be safely used with any
396 # frontend.
397 # frontend.
397 super(TerminalInteractiveShell, self).init_alias()
398 super(TerminalInteractiveShell, self).init_alias()
398
399
399 # Now define aliases that only make sense on the terminal, because they
400 # Now define aliases that only make sense on the terminal, because they
400 # need direct access to the console in a way that we can't emulate in
401 # need direct access to the console in a way that we can't emulate in
401 # GUI or web frontend
402 # GUI or web frontend
402 if os.name == 'posix':
403 if os.name == 'posix':
403 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
404 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
404 ('man', 'man')]
405 ('man', 'man')]
405 elif os.name == 'nt':
406 elif os.name == 'nt':
406 aliases = [('cls', 'cls')]
407 aliases = [('cls', 'cls')]
407
408
408
409
409 for name, cmd in aliases:
410 for name, cmd in aliases:
410 self.alias_manager.define_alias(name, cmd)
411 self.alias_manager.define_alias(name, cmd)
411
412
412 #-------------------------------------------------------------------------
413 #-------------------------------------------------------------------------
413 # Things related to the banner and usage
414 # Things related to the banner and usage
414 #-------------------------------------------------------------------------
415 #-------------------------------------------------------------------------
415
416
416 def _banner1_changed(self):
417 def _banner1_changed(self):
417 self.compute_banner()
418 self.compute_banner()
418
419
419 def _banner2_changed(self):
420 def _banner2_changed(self):
420 self.compute_banner()
421 self.compute_banner()
421
422
422 def _term_title_changed(self, name, new_value):
423 def _term_title_changed(self, name, new_value):
423 self.init_term_title()
424 self.init_term_title()
424
425
425 def init_banner(self, banner1, banner2, display_banner):
426 def init_banner(self, banner1, banner2, display_banner):
426 if banner1 is not None:
427 if banner1 is not None:
427 self.banner1 = banner1
428 self.banner1 = banner1
428 if banner2 is not None:
429 if banner2 is not None:
429 self.banner2 = banner2
430 self.banner2 = banner2
430 if display_banner is not None:
431 if display_banner is not None:
431 self.display_banner = display_banner
432 self.display_banner = display_banner
432 self.compute_banner()
433 self.compute_banner()
433
434
434 def show_banner(self, banner=None):
435 def show_banner(self, banner=None):
435 if banner is None:
436 if banner is None:
436 banner = self.banner
437 banner = self.banner
437 self.write(banner)
438 self.write(banner)
438
439
439 def compute_banner(self):
440 def compute_banner(self):
440 self.banner = self.banner1
441 self.banner = self.banner1
441 if self.profile and self.profile != 'default':
442 if self.profile and self.profile != 'default':
442 self.banner += '\nIPython profile: %s\n' % self.profile
443 self.banner += '\nIPython profile: %s\n' % self.profile
443 if self.banner2:
444 if self.banner2:
444 self.banner += '\n' + self.banner2
445 self.banner += '\n' + self.banner2
445
446
446 def init_usage(self, usage=None):
447 def init_usage(self, usage=None):
447 if usage is None:
448 if usage is None:
448 self.usage = interactive_usage
449 self.usage = interactive_usage
449 else:
450 else:
450 self.usage = usage
451 self.usage = usage
451
452
452 #-------------------------------------------------------------------------
453 #-------------------------------------------------------------------------
453 # Mainloop and code execution logic
454 # Mainloop and code execution logic
454 #-------------------------------------------------------------------------
455 #-------------------------------------------------------------------------
455
456
456 def mainloop(self, display_banner=None):
457 def mainloop(self, display_banner=None):
457 """Start the mainloop.
458 """Start the mainloop.
458
459
459 If an optional banner argument is given, it will override the
460 If an optional banner argument is given, it will override the
460 internally created default banner.
461 internally created default banner.
461 """
462 """
462
463
463 with nested(self.builtin_trap, self.display_trap):
464 with nested(self.builtin_trap, self.display_trap):
464
465
465 while 1:
466 while 1:
466 try:
467 try:
467 self.interact(display_banner=display_banner)
468 self.interact(display_banner=display_banner)
468 #self.interact_with_readline()
469 #self.interact_with_readline()
469 # XXX for testing of a readline-decoupled repl loop, call
470 # XXX for testing of a readline-decoupled repl loop, call
470 # interact_with_readline above
471 # interact_with_readline above
471 break
472 break
472 except KeyboardInterrupt:
473 except KeyboardInterrupt:
473 # this should not be necessary, but KeyboardInterrupt
474 # this should not be necessary, but KeyboardInterrupt
474 # handling seems rather unpredictable...
475 # handling seems rather unpredictable...
475 self.write("\nKeyboardInterrupt in interact()\n")
476 self.write("\nKeyboardInterrupt in interact()\n")
476
477
477 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
478 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
478 """Store multiple lines as a single entry in history"""
479 """Store multiple lines as a single entry in history"""
479
480
480 # do nothing without readline or disabled multiline
481 # do nothing without readline or disabled multiline
481 if not self.has_readline or not self.multiline_history:
482 if not self.has_readline or not self.multiline_history:
482 return hlen_before_cell
483 return hlen_before_cell
483
484
484 # windows rl has no remove_history_item
485 # windows rl has no remove_history_item
485 if not hasattr(self.readline, "remove_history_item"):
486 if not hasattr(self.readline, "remove_history_item"):
486 return hlen_before_cell
487 return hlen_before_cell
487
488
488 # skip empty cells
489 # skip empty cells
489 if not source_raw.rstrip():
490 if not source_raw.rstrip():
490 return hlen_before_cell
491 return hlen_before_cell
491
492
492 # nothing changed do nothing, e.g. when rl removes consecutive dups
493 # nothing changed do nothing, e.g. when rl removes consecutive dups
493 hlen = self.readline.get_current_history_length()
494 hlen = self.readline.get_current_history_length()
494 if hlen == hlen_before_cell:
495 if hlen == hlen_before_cell:
495 return hlen_before_cell
496 return hlen_before_cell
496
497
497 for i in range(hlen - hlen_before_cell):
498 for i in range(hlen - hlen_before_cell):
498 self.readline.remove_history_item(hlen - i - 1)
499 self.readline.remove_history_item(hlen - i - 1)
499 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
500 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
500 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
501 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
501 stdin_encoding))
502 stdin_encoding))
502 return self.readline.get_current_history_length()
503 return self.readline.get_current_history_length()
503
504
504 def interact(self, display_banner=None):
505 def interact(self, display_banner=None):
505 """Closely emulate the interactive Python console."""
506 """Closely emulate the interactive Python console."""
506
507
507 # batch run -> do not interact
508 # batch run -> do not interact
508 if self.exit_now:
509 if self.exit_now:
509 return
510 return
510
511
511 if display_banner is None:
512 if display_banner is None:
512 display_banner = self.display_banner
513 display_banner = self.display_banner
513
514
514 if isinstance(display_banner, basestring):
515 if isinstance(display_banner, basestring):
515 self.show_banner(display_banner)
516 self.show_banner(display_banner)
516 elif display_banner:
517 elif display_banner:
517 self.show_banner()
518 self.show_banner()
518
519
519 more = False
520 more = False
520
521
521 if self.has_readline:
522 if self.has_readline:
522 self.readline_startup_hook(self.pre_readline)
523 self.readline_startup_hook(self.pre_readline)
523 hlen_b4_cell = self.readline.get_current_history_length()
524 hlen_b4_cell = self.readline.get_current_history_length()
524 else:
525 else:
525 hlen_b4_cell = 0
526 hlen_b4_cell = 0
526 # exit_now is set by a call to %Exit or %Quit, through the
527 # exit_now is set by a call to %Exit or %Quit, through the
527 # ask_exit callback.
528 # ask_exit callback.
528
529
529 while not self.exit_now:
530 while not self.exit_now:
530 self.hooks.pre_prompt_hook()
531 self.hooks.pre_prompt_hook()
531 if more:
532 if more:
532 try:
533 try:
533 prompt = self.prompt_manager.render('in2')
534 prompt = self.prompt_manager.render('in2')
534 except:
535 except:
535 self.showtraceback()
536 self.showtraceback()
536 if self.autoindent:
537 if self.autoindent:
537 self.rl_do_indent = True
538 self.rl_do_indent = True
538
539
539 else:
540 else:
540 try:
541 try:
541 prompt = self.separate_in + self.prompt_manager.render('in')
542 prompt = self.separate_in + self.prompt_manager.render('in')
542 except:
543 except:
543 self.showtraceback()
544 self.showtraceback()
544 try:
545 try:
545 line = self.raw_input(prompt)
546 line = self.raw_input(prompt)
546 if self.exit_now:
547 if self.exit_now:
547 # quick exit on sys.std[in|out] close
548 # quick exit on sys.std[in|out] close
548 break
549 break
549 if self.autoindent:
550 if self.autoindent:
550 self.rl_do_indent = False
551 self.rl_do_indent = False
551
552
552 except KeyboardInterrupt:
553 except KeyboardInterrupt:
553 #double-guard against keyboardinterrupts during kbdint handling
554 #double-guard against keyboardinterrupts during kbdint handling
554 try:
555 try:
555 self.write('\nKeyboardInterrupt\n')
556 self.write('\nKeyboardInterrupt\n')
556 source_raw = self.input_splitter.source_raw_reset()[1]
557 source_raw = self.input_splitter.source_raw_reset()[1]
557 hlen_b4_cell = \
558 hlen_b4_cell = \
558 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
559 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
559 more = False
560 more = False
560 except KeyboardInterrupt:
561 except KeyboardInterrupt:
561 pass
562 pass
562 except EOFError:
563 except EOFError:
563 if self.autoindent:
564 if self.autoindent:
564 self.rl_do_indent = False
565 self.rl_do_indent = False
565 if self.has_readline:
566 if self.has_readline:
566 self.readline_startup_hook(None)
567 self.readline_startup_hook(None)
567 self.write('\n')
568 self.write('\n')
568 self.exit()
569 self.exit()
569 except bdb.BdbQuit:
570 except bdb.BdbQuit:
570 warn('The Python debugger has exited with a BdbQuit exception.\n'
571 warn('The Python debugger has exited with a BdbQuit exception.\n'
571 'Because of how pdb handles the stack, it is impossible\n'
572 'Because of how pdb handles the stack, it is impossible\n'
572 'for IPython to properly format this particular exception.\n'
573 'for IPython to properly format this particular exception.\n'
573 'IPython will resume normal operation.')
574 'IPython will resume normal operation.')
574 except:
575 except:
575 # exceptions here are VERY RARE, but they can be triggered
576 # exceptions here are VERY RARE, but they can be triggered
576 # asynchronously by signal handlers, for example.
577 # asynchronously by signal handlers, for example.
577 self.showtraceback()
578 self.showtraceback()
578 else:
579 else:
579 self.input_splitter.push(line)
580 self.input_splitter.push(line)
580 more = self.input_splitter.push_accepts_more()
581 more = self.input_splitter.push_accepts_more()
581 if (self.SyntaxTB.last_syntax_error and
582 if (self.SyntaxTB.last_syntax_error and
582 self.autoedit_syntax):
583 self.autoedit_syntax):
583 self.edit_syntax_error()
584 self.edit_syntax_error()
584 if not more:
585 if not more:
585 source_raw = self.input_splitter.source_raw_reset()[1]
586 source_raw = self.input_splitter.source_raw_reset()[1]
586 self.run_cell(source_raw, store_history=True)
587 self.run_cell(source_raw, store_history=True)
587 hlen_b4_cell = \
588 hlen_b4_cell = \
588 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
589 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
589
590
590 # Turn off the exit flag, so the mainloop can be restarted if desired
591 # Turn off the exit flag, so the mainloop can be restarted if desired
591 self.exit_now = False
592 self.exit_now = False
592
593
593 def raw_input(self, prompt=''):
594 def raw_input(self, prompt=''):
594 """Write a prompt and read a line.
595 """Write a prompt and read a line.
595
596
596 The returned line does not include the trailing newline.
597 The returned line does not include the trailing newline.
597 When the user enters the EOF key sequence, EOFError is raised.
598 When the user enters the EOF key sequence, EOFError is raised.
598
599
599 Optional inputs:
600 Optional inputs:
600
601
601 - prompt(''): a string to be printed to prompt the user.
602 - prompt(''): a string to be printed to prompt the user.
602
603
603 - continue_prompt(False): whether this line is the first one or a
604 - continue_prompt(False): whether this line is the first one or a
604 continuation in a sequence of inputs.
605 continuation in a sequence of inputs.
605 """
606 """
606 # Code run by the user may have modified the readline completer state.
607 # Code run by the user may have modified the readline completer state.
607 # We must ensure that our completer is back in place.
608 # We must ensure that our completer is back in place.
608
609
609 if self.has_readline:
610 if self.has_readline:
610 self.set_readline_completer()
611 self.set_readline_completer()
611
612
612 # raw_input expects str, but we pass it unicode sometimes
613 # raw_input expects str, but we pass it unicode sometimes
613 prompt = py3compat.cast_bytes_py2(prompt)
614 prompt = py3compat.cast_bytes_py2(prompt)
614
615
615 try:
616 try:
616 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
617 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
617 except ValueError:
618 except ValueError:
618 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
619 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
619 " or sys.stdout.close()!\nExiting IPython!\n")
620 " or sys.stdout.close()!\nExiting IPython!\n")
620 self.ask_exit()
621 self.ask_exit()
621 return ""
622 return ""
622
623
623 # Try to be reasonably smart about not re-indenting pasted input more
624 # Try to be reasonably smart about not re-indenting pasted input more
624 # than necessary. We do this by trimming out the auto-indent initial
625 # than necessary. We do this by trimming out the auto-indent initial
625 # spaces, if the user's actual input started itself with whitespace.
626 # spaces, if the user's actual input started itself with whitespace.
626 if self.autoindent:
627 if self.autoindent:
627 if num_ini_spaces(line) > self.indent_current_nsp:
628 if num_ini_spaces(line) > self.indent_current_nsp:
628 line = line[self.indent_current_nsp:]
629 line = line[self.indent_current_nsp:]
629 self.indent_current_nsp = 0
630 self.indent_current_nsp = 0
630
631
631 return line
632 return line
632
633
633 #-------------------------------------------------------------------------
634 #-------------------------------------------------------------------------
634 # Methods to support auto-editing of SyntaxErrors.
635 # Methods to support auto-editing of SyntaxErrors.
635 #-------------------------------------------------------------------------
636 #-------------------------------------------------------------------------
636
637
637 def edit_syntax_error(self):
638 def edit_syntax_error(self):
638 """The bottom half of the syntax error handler called in the main loop.
639 """The bottom half of the syntax error handler called in the main loop.
639
640
640 Loop until syntax error is fixed or user cancels.
641 Loop until syntax error is fixed or user cancels.
641 """
642 """
642
643
643 while self.SyntaxTB.last_syntax_error:
644 while self.SyntaxTB.last_syntax_error:
644 # copy and clear last_syntax_error
645 # copy and clear last_syntax_error
645 err = self.SyntaxTB.clear_err_state()
646 err = self.SyntaxTB.clear_err_state()
646 if not self._should_recompile(err):
647 if not self._should_recompile(err):
647 return
648 return
648 try:
649 try:
649 # may set last_syntax_error again if a SyntaxError is raised
650 # may set last_syntax_error again if a SyntaxError is raised
650 self.safe_execfile(err.filename,self.user_ns)
651 self.safe_execfile(err.filename,self.user_ns)
651 except:
652 except:
652 self.showtraceback()
653 self.showtraceback()
653 else:
654 else:
654 try:
655 try:
655 f = open(err.filename)
656 f = open(err.filename)
656 try:
657 try:
657 # This should be inside a display_trap block and I
658 # This should be inside a display_trap block and I
658 # think it is.
659 # think it is.
659 sys.displayhook(f.read())
660 sys.displayhook(f.read())
660 finally:
661 finally:
661 f.close()
662 f.close()
662 except:
663 except:
663 self.showtraceback()
664 self.showtraceback()
664
665
665 def _should_recompile(self,e):
666 def _should_recompile(self,e):
666 """Utility routine for edit_syntax_error"""
667 """Utility routine for edit_syntax_error"""
667
668
668 if e.filename in ('<ipython console>','<input>','<string>',
669 if e.filename in ('<ipython console>','<input>','<string>',
669 '<console>','<BackgroundJob compilation>',
670 '<console>','<BackgroundJob compilation>',
670 None):
671 None):
671
672
672 return False
673 return False
673 try:
674 try:
674 if (self.autoedit_syntax and
675 if (self.autoedit_syntax and
675 not self.ask_yes_no('Return to editor to correct syntax error? '
676 not self.ask_yes_no('Return to editor to correct syntax error? '
676 '[Y/n] ','y')):
677 '[Y/n] ','y')):
677 return False
678 return False
678 except EOFError:
679 except EOFError:
679 return False
680 return False
680
681
681 def int0(x):
682 def int0(x):
682 try:
683 try:
683 return int(x)
684 return int(x)
684 except TypeError:
685 except TypeError:
685 return 0
686 return 0
686 # always pass integer line and offset values to editor hook
687 # always pass integer line and offset values to editor hook
687 try:
688 try:
688 self.hooks.fix_error_editor(e.filename,
689 self.hooks.fix_error_editor(e.filename,
689 int0(e.lineno),int0(e.offset),e.msg)
690 int0(e.lineno),int0(e.offset),e.msg)
690 except TryNext:
691 except TryNext:
691 warn('Could not open editor')
692 warn('Could not open editor')
692 return False
693 return False
693 return True
694 return True
694
695
695 #-------------------------------------------------------------------------
696 #-------------------------------------------------------------------------
696 # Things related to exiting
697 # Things related to exiting
697 #-------------------------------------------------------------------------
698 #-------------------------------------------------------------------------
698
699
699 def ask_exit(self):
700 def ask_exit(self):
700 """ Ask the shell to exit. Can be overiden and used as a callback. """
701 """ Ask the shell to exit. Can be overiden and used as a callback. """
701 self.exit_now = True
702 self.exit_now = True
702
703
703 def exit(self):
704 def exit(self):
704 """Handle interactive exit.
705 """Handle interactive exit.
705
706
706 This method calls the ask_exit callback."""
707 This method calls the ask_exit callback."""
707 if self.confirm_exit:
708 if self.confirm_exit:
708 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
709 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
709 self.ask_exit()
710 self.ask_exit()
710 else:
711 else:
711 self.ask_exit()
712 self.ask_exit()
712
713
713 #-------------------------------------------------------------------------
714 #-------------------------------------------------------------------------
714 # Things related to magics
715 # Things related to magics
715 #-------------------------------------------------------------------------
716 #-------------------------------------------------------------------------
716
717
717 def init_magics(self):
718 def init_magics(self):
718 super(TerminalInteractiveShell, self).init_magics()
719 super(TerminalInteractiveShell, self).init_magics()
719 self.register_magics(TerminalMagics)
720 self.register_magics(TerminalMagics)
720
721
721 def showindentationerror(self):
722 def showindentationerror(self):
722 super(TerminalInteractiveShell, self).showindentationerror()
723 super(TerminalInteractiveShell, self).showindentationerror()
723 print("If you want to paste code into IPython, try the "
724 print("If you want to paste code into IPython, try the "
724 "%paste and %cpaste magic functions.")
725 "%paste and %cpaste magic functions.")
725
726
726
727
727 InteractiveShellABC.register(TerminalInteractiveShell)
728 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,484 +1,483 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Manage background (threaded) jobs conveniently from an interactive shell.
2 """Manage background (threaded) jobs conveniently from an interactive shell.
3
3
4 This module provides a BackgroundJobManager class. This is the main class
4 This module provides a BackgroundJobManager class. This is the main class
5 meant for public usage, it implements an object which can create and manage
5 meant for public usage, it implements an object which can create and manage
6 new background jobs.
6 new background jobs.
7
7
8 It also provides the actual job classes managed by these BackgroundJobManager
8 It also provides the actual job classes managed by these BackgroundJobManager
9 objects, see their docstrings below.
9 objects, see their docstrings below.
10
10
11
11
12 This system was inspired by discussions with B. Granger and the
12 This system was inspired by discussions with B. Granger and the
13 BackgroundCommand class described in the book Python Scripting for
13 BackgroundCommand class described in the book Python Scripting for
14 Computational Science, by H. P. Langtangen:
14 Computational Science, by H. P. Langtangen:
15
15
16 http://folk.uio.no/hpl/scripting
16 http://folk.uio.no/hpl/scripting
17
17
18 (although ultimately no code from this text was used, as IPython's system is a
18 (although ultimately no code from this text was used, as IPython's system is a
19 separate implementation).
19 separate implementation).
20
20
21 An example notebook is provided in our documentation illustrating interactive
21 An example notebook is provided in our documentation illustrating interactive
22 use of the system.
22 use of the system.
23 """
23 """
24
24
25 #*****************************************************************************
25 #*****************************************************************************
26 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
26 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
27 #
27 #
28 # Distributed under the terms of the BSD License. The full license is in
28 # Distributed under the terms of the BSD License. The full license is in
29 # the file COPYING, distributed as part of this software.
29 # the file COPYING, distributed as part of this software.
30 #*****************************************************************************
30 #*****************************************************************************
31
31
32 # Code begins
32 # Code begins
33 import sys
33 import sys
34 import threading
34 import threading
35
35
36 from IPython.core.ultratb import AutoFormattedTB
36 from IPython.core.ultratb import AutoFormattedTB
37 from IPython.utils.warn import warn, error
37 from IPython.utils.warn import warn, error
38
38
39
39
40 class BackgroundJobManager(object):
40 class BackgroundJobManager(object):
41 """Class to manage a pool of backgrounded threaded jobs.
41 """Class to manage a pool of backgrounded threaded jobs.
42
42
43 Below, we assume that 'jobs' is a BackgroundJobManager instance.
43 Below, we assume that 'jobs' is a BackgroundJobManager instance.
44
44
45 Usage summary (see the method docstrings for details):
45 Usage summary (see the method docstrings for details):
46
46
47 jobs.new(...) -> start a new job
47 jobs.new(...) -> start a new job
48
48
49 jobs() or jobs.status() -> print status summary of all jobs
49 jobs() or jobs.status() -> print status summary of all jobs
50
50
51 jobs[N] -> returns job number N.
51 jobs[N] -> returns job number N.
52
52
53 foo = jobs[N].result -> assign to variable foo the result of job N
53 foo = jobs[N].result -> assign to variable foo the result of job N
54
54
55 jobs[N].traceback() -> print the traceback of dead job N
55 jobs[N].traceback() -> print the traceback of dead job N
56
56
57 jobs.remove(N) -> remove (finished) job N
57 jobs.remove(N) -> remove (finished) job N
58
58
59 jobs.flush() -> remove all finished jobs
59 jobs.flush() -> remove all finished jobs
60
60
61 As a convenience feature, BackgroundJobManager instances provide the
61 As a convenience feature, BackgroundJobManager instances provide the
62 utility result and traceback methods which retrieve the corresponding
62 utility result and traceback methods which retrieve the corresponding
63 information from the jobs list:
63 information from the jobs list:
64
64
65 jobs.result(N) <--> jobs[N].result
65 jobs.result(N) <--> jobs[N].result
66 jobs.traceback(N) <--> jobs[N].traceback()
66 jobs.traceback(N) <--> jobs[N].traceback()
67
67
68 While this appears minor, it allows you to use tab completion
68 While this appears minor, it allows you to use tab completion
69 interactively on the job manager instance.
69 interactively on the job manager instance.
70 """
70 """
71
71
72 def __init__(self):
72 def __init__(self):
73 # Lists for job management, accessed via a property to ensure they're
73 # Lists for job management, accessed via a property to ensure they're
74 # up to date.x
74 # up to date.x
75 self._running = []
75 self._running = []
76 self._completed = []
76 self._completed = []
77 self._dead = []
77 self._dead = []
78 # A dict of all jobs, so users can easily access any of them
78 # A dict of all jobs, so users can easily access any of them
79 self.all = {}
79 self.all = {}
80 # For reporting
80 # For reporting
81 self._comp_report = []
81 self._comp_report = []
82 self._dead_report = []
82 self._dead_report = []
83 # Store status codes locally for fast lookups
83 # Store status codes locally for fast lookups
84 self._s_created = BackgroundJobBase.stat_created_c
84 self._s_created = BackgroundJobBase.stat_created_c
85 self._s_running = BackgroundJobBase.stat_running_c
85 self._s_running = BackgroundJobBase.stat_running_c
86 self._s_completed = BackgroundJobBase.stat_completed_c
86 self._s_completed = BackgroundJobBase.stat_completed_c
87 self._s_dead = BackgroundJobBase.stat_dead_c
87 self._s_dead = BackgroundJobBase.stat_dead_c
88
88
89 @property
89 @property
90 def running(self):
90 def running(self):
91 self._update_status()
91 self._update_status()
92 return self._running
92 return self._running
93
93
94 @property
94 @property
95 def dead(self):
95 def dead(self):
96 self._update_status()
96 self._update_status()
97 return self._dead
97 return self._dead
98
98
99 @property
99 @property
100 def completed(self):
100 def completed(self):
101 self._update_status()
101 self._update_status()
102 return self._completed
102 return self._completed
103
103
104 def new(self, func_or_exp, *args, **kwargs):
104 def new(self, func_or_exp, *args, **kwargs):
105 """Add a new background job and start it in a separate thread.
105 """Add a new background job and start it in a separate thread.
106
106
107 There are two types of jobs which can be created:
107 There are two types of jobs which can be created:
108
108
109 1. Jobs based on expressions which can be passed to an eval() call.
109 1. Jobs based on expressions which can be passed to an eval() call.
110 The expression must be given as a string. For example:
110 The expression must be given as a string. For example:
111
111
112 job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
112 job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
113
113
114 The given expression is passed to eval(), along with the optional
114 The given expression is passed to eval(), along with the optional
115 global/local dicts provided. If no dicts are given, they are
115 global/local dicts provided. If no dicts are given, they are
116 extracted automatically from the caller's frame.
116 extracted automatically from the caller's frame.
117
117
118 A Python statement is NOT a valid eval() expression. Basically, you
118 A Python statement is NOT a valid eval() expression. Basically, you
119 can only use as an eval() argument something which can go on the right
119 can only use as an eval() argument something which can go on the right
120 of an '=' sign and be assigned to a variable.
120 of an '=' sign and be assigned to a variable.
121
121
122 For example,"print 'hello'" is not valid, but '2+3' is.
122 For example,"print 'hello'" is not valid, but '2+3' is.
123
123
124 2. Jobs given a function object, optionally passing additional
124 2. Jobs given a function object, optionally passing additional
125 positional arguments:
125 positional arguments:
126
126
127 job_manager.new(myfunc, x, y)
127 job_manager.new(myfunc, x, y)
128
128
129 The function is called with the given arguments.
129 The function is called with the given arguments.
130
130
131 If you need to pass keyword arguments to your function, you must
131 If you need to pass keyword arguments to your function, you must
132 supply them as a dict named kw:
132 supply them as a dict named kw:
133
133
134 job_manager.new(myfunc, x, y, kw=dict(z=1))
134 job_manager.new(myfunc, x, y, kw=dict(z=1))
135
135
136 The reason for this assymmetry is that the new() method needs to
136 The reason for this assymmetry is that the new() method needs to
137 maintain access to its own keywords, and this prevents name collisions
137 maintain access to its own keywords, and this prevents name collisions
138 between arguments to new() and arguments to your own functions.
138 between arguments to new() and arguments to your own functions.
139
139
140 In both cases, the result is stored in the job.result field of the
140 In both cases, the result is stored in the job.result field of the
141 background job object.
141 background job object.
142
142
143 You can set `daemon` attribute of the thread by giving the keyword
143 You can set `daemon` attribute of the thread by giving the keyword
144 argument `daemon`.
144 argument `daemon`.
145
145
146 Notes and caveats:
146 Notes and caveats:
147
147
148 1. All threads running share the same standard output. Thus, if your
148 1. All threads running share the same standard output. Thus, if your
149 background jobs generate output, it will come out on top of whatever
149 background jobs generate output, it will come out on top of whatever
150 you are currently writing. For this reason, background jobs are best
150 you are currently writing. For this reason, background jobs are best
151 used with silent functions which simply return their output.
151 used with silent functions which simply return their output.
152
152
153 2. Threads also all work within the same global namespace, and this
153 2. Threads also all work within the same global namespace, and this
154 system does not lock interactive variables. So if you send job to the
154 system does not lock interactive variables. So if you send job to the
155 background which operates on a mutable object for a long time, and
155 background which operates on a mutable object for a long time, and
156 start modifying that same mutable object interactively (or in another
156 start modifying that same mutable object interactively (or in another
157 backgrounded job), all sorts of bizarre behaviour will occur.
157 backgrounded job), all sorts of bizarre behaviour will occur.
158
158
159 3. If a background job is spending a lot of time inside a C extension
159 3. If a background job is spending a lot of time inside a C extension
160 module which does not release the Python Global Interpreter Lock
160 module which does not release the Python Global Interpreter Lock
161 (GIL), this will block the IPython prompt. This is simply because the
161 (GIL), this will block the IPython prompt. This is simply because the
162 Python interpreter can only switch between threads at Python
162 Python interpreter can only switch between threads at Python
163 bytecodes. While the execution is inside C code, the interpreter must
163 bytecodes. While the execution is inside C code, the interpreter must
164 simply wait unless the extension module releases the GIL.
164 simply wait unless the extension module releases the GIL.
165
165
166 4. There is no way, due to limitations in the Python threads library,
166 4. There is no way, due to limitations in the Python threads library,
167 to kill a thread once it has started."""
167 to kill a thread once it has started."""
168
168
169 if callable(func_or_exp):
169 if callable(func_or_exp):
170 kw = kwargs.get('kw',{})
170 kw = kwargs.get('kw',{})
171 job = BackgroundJobFunc(func_or_exp,*args,**kw)
171 job = BackgroundJobFunc(func_or_exp,*args,**kw)
172 elif isinstance(func_or_exp, basestring):
172 elif isinstance(func_or_exp, basestring):
173 if not args:
173 if not args:
174 frame = sys._getframe(1)
174 frame = sys._getframe(1)
175 glob, loc = frame.f_globals, frame.f_locals
175 glob, loc = frame.f_globals, frame.f_locals
176 elif len(args)==1:
176 elif len(args)==1:
177 glob = loc = args[0]
177 glob = loc = args[0]
178 elif len(args)==2:
178 elif len(args)==2:
179 glob,loc = args
179 glob,loc = args
180 else:
180 else:
181 raise ValueError(
181 raise ValueError(
182 'Expression jobs take at most 2 args (globals,locals)')
182 'Expression jobs take at most 2 args (globals,locals)')
183 job = BackgroundJobExpr(func_or_exp, glob, loc)
183 job = BackgroundJobExpr(func_or_exp, glob, loc)
184 else:
184 else:
185 raise TypeError('invalid args for new job')
185 raise TypeError('invalid args for new job')
186
186
187 if kwargs.get('daemon', False):
187 if kwargs.get('daemon', False):
188 job.daemon = True
188 job.daemon = True
189 job.num = len(self.all)+1 if self.all else 0
189 job.num = len(self.all)+1 if self.all else 0
190 self.running.append(job)
190 self.running.append(job)
191 self.all[job.num] = job
191 self.all[job.num] = job
192 print 'Starting job # %s in a separate thread.' % job.num
192 print 'Starting job # %s in a separate thread.' % job.num
193 job.start()
193 job.start()
194 return job
194 return job
195
195
196 def __getitem__(self, job_key):
196 def __getitem__(self, job_key):
197 num = job_key if isinstance(job_key, int) else job_key.num
197 num = job_key if isinstance(job_key, int) else job_key.num
198 return self.all[num]
198 return self.all[num]
199
199
200 def __call__(self):
200 def __call__(self):
201 """An alias to self.status(),
201 """An alias to self.status(),
202
202
203 This allows you to simply call a job manager instance much like the
203 This allows you to simply call a job manager instance much like the
204 Unix `jobs` shell command."""
204 Unix `jobs` shell command."""
205
205
206 return self.status()
206 return self.status()
207
207
208 def _update_status(self):
208 def _update_status(self):
209 """Update the status of the job lists.
209 """Update the status of the job lists.
210
210
211 This method moves finished jobs to one of two lists:
211 This method moves finished jobs to one of two lists:
212 - self.completed: jobs which completed successfully
212 - self.completed: jobs which completed successfully
213 - self.dead: jobs which finished but died.
213 - self.dead: jobs which finished but died.
214
214
215 It also copies those jobs to corresponding _report lists. These lists
215 It also copies those jobs to corresponding _report lists. These lists
216 are used to report jobs completed/dead since the last update, and are
216 are used to report jobs completed/dead since the last update, and are
217 then cleared by the reporting function after each call."""
217 then cleared by the reporting function after each call."""
218
218
219 # Status codes
219 # Status codes
220 srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
220 srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
221 # State lists, use the actual lists b/c the public names are properties
221 # State lists, use the actual lists b/c the public names are properties
222 # that call this very function on access
222 # that call this very function on access
223 running, completed, dead = self._running, self._completed, self._dead
223 running, completed, dead = self._running, self._completed, self._dead
224
224
225 # Now, update all state lists
225 # Now, update all state lists
226 for num, job in enumerate(running):
226 for num, job in enumerate(running):
227 stat = job.stat_code
227 stat = job.stat_code
228 if stat == srun:
228 if stat == srun:
229 continue
229 continue
230 elif stat == scomp:
230 elif stat == scomp:
231 completed.append(job)
231 completed.append(job)
232 self._comp_report.append(job)
232 self._comp_report.append(job)
233 running[num] = False
233 running[num] = False
234 elif stat == sdead:
234 elif stat == sdead:
235 dead.append(job)
235 dead.append(job)
236 self._dead_report.append(job)
236 self._dead_report.append(job)
237 running[num] = False
237 running[num] = False
238 # Remove dead/completed jobs from running list
238 # Remove dead/completed jobs from running list
239 running[:] = filter(None, running)
239 running[:] = filter(None, running)
240
240
241 def _group_report(self,group,name):
241 def _group_report(self,group,name):
242 """Report summary for a given job group.
242 """Report summary for a given job group.
243
243
244 Return True if the group had any elements."""
244 Return True if the group had any elements."""
245
245
246 if group:
246 if group:
247 print '%s jobs:' % name
247 print '%s jobs:' % name
248 for job in group:
248 for job in group:
249 print '%s : %s' % (job.num,job)
249 print '%s : %s' % (job.num,job)
250 print
250 print
251 return True
251 return True
252
252
253 def _group_flush(self,group,name):
253 def _group_flush(self,group,name):
254 """Flush a given job group
254 """Flush a given job group
255
255
256 Return True if the group had any elements."""
256 Return True if the group had any elements."""
257
257
258 njobs = len(group)
258 njobs = len(group)
259 if njobs:
259 if njobs:
260 plural = {1:''}.setdefault(njobs,'s')
260 plural = {1:''}.setdefault(njobs,'s')
261 print 'Flushing %s %s job%s.' % (njobs,name,plural)
261 print 'Flushing %s %s job%s.' % (njobs,name,plural)
262 group[:] = []
262 group[:] = []
263 return True
263 return True
264
264
265 def _status_new(self):
265 def _status_new(self):
266 """Print the status of newly finished jobs.
266 """Print the status of newly finished jobs.
267
267
268 Return True if any new jobs are reported.
268 Return True if any new jobs are reported.
269
269
270 This call resets its own state every time, so it only reports jobs
270 This call resets its own state every time, so it only reports jobs
271 which have finished since the last time it was called."""
271 which have finished since the last time it was called."""
272
272
273 self._update_status()
273 self._update_status()
274 new_comp = self._group_report(self._comp_report, 'Completed')
274 new_comp = self._group_report(self._comp_report, 'Completed')
275 new_dead = self._group_report(self._dead_report,
275 new_dead = self._group_report(self._dead_report,
276 'Dead, call jobs.traceback() for details')
276 'Dead, call jobs.traceback() for details')
277 self._comp_report[:] = []
277 self._comp_report[:] = []
278 self._dead_report[:] = []
278 self._dead_report[:] = []
279 return new_comp or new_dead
279 return new_comp or new_dead
280
280
281 def status(self,verbose=0):
281 def status(self,verbose=0):
282 """Print a status of all jobs currently being managed."""
282 """Print a status of all jobs currently being managed."""
283
283
284 self._update_status()
284 self._update_status()
285 self._group_report(self.running,'Running')
285 self._group_report(self.running,'Running')
286 self._group_report(self.completed,'Completed')
286 self._group_report(self.completed,'Completed')
287 self._group_report(self.dead,'Dead')
287 self._group_report(self.dead,'Dead')
288 # Also flush the report queues
288 # Also flush the report queues
289 self._comp_report[:] = []
289 self._comp_report[:] = []
290 self._dead_report[:] = []
290 self._dead_report[:] = []
291
291
292 def remove(self,num):
292 def remove(self,num):
293 """Remove a finished (completed or dead) job."""
293 """Remove a finished (completed or dead) job."""
294
294
295 try:
295 try:
296 job = self.all[num]
296 job = self.all[num]
297 except KeyError:
297 except KeyError:
298 error('Job #%s not found' % num)
298 error('Job #%s not found' % num)
299 else:
299 else:
300 stat_code = job.stat_code
300 stat_code = job.stat_code
301 if stat_code == self._s_running:
301 if stat_code == self._s_running:
302 error('Job #%s is still running, it can not be removed.' % num)
302 error('Job #%s is still running, it can not be removed.' % num)
303 return
303 return
304 elif stat_code == self._s_completed:
304 elif stat_code == self._s_completed:
305 self.completed.remove(job)
305 self.completed.remove(job)
306 elif stat_code == self._s_dead:
306 elif stat_code == self._s_dead:
307 self.dead.remove(job)
307 self.dead.remove(job)
308
308
309 def flush(self):
309 def flush(self):
310 """Flush all finished jobs (completed and dead) from lists.
310 """Flush all finished jobs (completed and dead) from lists.
311
311
312 Running jobs are never flushed.
312 Running jobs are never flushed.
313
313
314 It first calls _status_new(), to update info. If any jobs have
314 It first calls _status_new(), to update info. If any jobs have
315 completed since the last _status_new() call, the flush operation
315 completed since the last _status_new() call, the flush operation
316 aborts."""
316 aborts."""
317
317
318 # Remove the finished jobs from the master dict
318 # Remove the finished jobs from the master dict
319 alljobs = self.all
319 alljobs = self.all
320 for job in self.completed+self.dead:
320 for job in self.completed+self.dead:
321 del(alljobs[job.num])
321 del(alljobs[job.num])
322
322
323 # Now flush these lists completely
323 # Now flush these lists completely
324 fl_comp = self._group_flush(self.completed, 'Completed')
324 fl_comp = self._group_flush(self.completed, 'Completed')
325 fl_dead = self._group_flush(self.dead, 'Dead')
325 fl_dead = self._group_flush(self.dead, 'Dead')
326 if not (fl_comp or fl_dead):
326 if not (fl_comp or fl_dead):
327 print 'No jobs to flush.'
327 print 'No jobs to flush.'
328
328
329 def result(self,num):
329 def result(self,num):
330 """result(N) -> return the result of job N."""
330 """result(N) -> return the result of job N."""
331 try:
331 try:
332 return self.all[num].result
332 return self.all[num].result
333 except KeyError:
333 except KeyError:
334 error('Job #%s not found' % num)
334 error('Job #%s not found' % num)
335
335
336 def _traceback(self, job):
336 def _traceback(self, job):
337 num = job if isinstance(job, int) else job.num
337 num = job if isinstance(job, int) else job.num
338 try:
338 try:
339 self.all[num].traceback()
339 self.all[num].traceback()
340 except KeyError:
340 except KeyError:
341 error('Job #%s not found' % num)
341 error('Job #%s not found' % num)
342
342
343 def traceback(self, job=None):
343 def traceback(self, job=None):
344 if job is None:
344 if job is None:
345 self._update_status()
345 self._update_status()
346 for deadjob in self.dead:
346 for deadjob in self.dead:
347 print "Traceback for: %r" % deadjob
347 print "Traceback for: %r" % deadjob
348 self._traceback(deadjob)
348 self._traceback(deadjob)
349 print
349 print
350 else:
350 else:
351 self._traceback(job)
351 self._traceback(job)
352
352
353
353
354 class BackgroundJobBase(threading.Thread):
354 class BackgroundJobBase(threading.Thread):
355 """Base class to build BackgroundJob classes.
355 """Base class to build BackgroundJob classes.
356
356
357 The derived classes must implement:
357 The derived classes must implement:
358
358
359 - Their own __init__, since the one here raises NotImplementedError. The
359 - Their own __init__, since the one here raises NotImplementedError. The
360 derived constructor must call self._init() at the end, to provide common
360 derived constructor must call self._init() at the end, to provide common
361 initialization.
361 initialization.
362
362
363 - A strform attribute used in calls to __str__.
363 - A strform attribute used in calls to __str__.
364
364
365 - A call() method, which will make the actual execution call and must
365 - A call() method, which will make the actual execution call and must
366 return a value to be held in the 'result' field of the job object."""
366 return a value to be held in the 'result' field of the job object."""
367
367
368 # Class constants for status, in string and as numerical codes (when
368 # Class constants for status, in string and as numerical codes (when
369 # updating jobs lists, we don't want to do string comparisons). This will
369 # updating jobs lists, we don't want to do string comparisons). This will
370 # be done at every user prompt, so it has to be as fast as possible
370 # be done at every user prompt, so it has to be as fast as possible
371 stat_created = 'Created'; stat_created_c = 0
371 stat_created = 'Created'; stat_created_c = 0
372 stat_running = 'Running'; stat_running_c = 1
372 stat_running = 'Running'; stat_running_c = 1
373 stat_completed = 'Completed'; stat_completed_c = 2
373 stat_completed = 'Completed'; stat_completed_c = 2
374 stat_dead = 'Dead (Exception), call jobs.traceback() for details'
374 stat_dead = 'Dead (Exception), call jobs.traceback() for details'
375 stat_dead_c = -1
375 stat_dead_c = -1
376
376
377 def __init__(self):
377 def __init__(self):
378 raise NotImplementedError, \
378 raise NotImplementedError("This class can not be instantiated directly.")
379 "This class can not be instantiated directly."
380
379
381 def _init(self):
380 def _init(self):
382 """Common initialization for all BackgroundJob objects"""
381 """Common initialization for all BackgroundJob objects"""
383
382
384 for attr in ['call','strform']:
383 for attr in ['call','strform']:
385 assert hasattr(self,attr), "Missing attribute <%s>" % attr
384 assert hasattr(self,attr), "Missing attribute <%s>" % attr
386
385
387 # The num tag can be set by an external job manager
386 # The num tag can be set by an external job manager
388 self.num = None
387 self.num = None
389
388
390 self.status = BackgroundJobBase.stat_created
389 self.status = BackgroundJobBase.stat_created
391 self.stat_code = BackgroundJobBase.stat_created_c
390 self.stat_code = BackgroundJobBase.stat_created_c
392 self.finished = False
391 self.finished = False
393 self.result = '<BackgroundJob has not completed>'
392 self.result = '<BackgroundJob has not completed>'
394
393
395 # reuse the ipython traceback handler if we can get to it, otherwise
394 # reuse the ipython traceback handler if we can get to it, otherwise
396 # make a new one
395 # make a new one
397 try:
396 try:
398 make_tb = get_ipython().InteractiveTB.text
397 make_tb = get_ipython().InteractiveTB.text
399 except:
398 except:
400 make_tb = AutoFormattedTB(mode = 'Context',
399 make_tb = AutoFormattedTB(mode = 'Context',
401 color_scheme='NoColor',
400 color_scheme='NoColor',
402 tb_offset = 1).text
401 tb_offset = 1).text
403 # Note that the actual API for text() requires the three args to be
402 # Note that the actual API for text() requires the three args to be
404 # passed in, so we wrap it in a simple lambda.
403 # passed in, so we wrap it in a simple lambda.
405 self._make_tb = lambda : make_tb(None, None, None)
404 self._make_tb = lambda : make_tb(None, None, None)
406
405
407 # Hold a formatted traceback if one is generated.
406 # Hold a formatted traceback if one is generated.
408 self._tb = None
407 self._tb = None
409
408
410 threading.Thread.__init__(self)
409 threading.Thread.__init__(self)
411
410
412 def __str__(self):
411 def __str__(self):
413 return self.strform
412 return self.strform
414
413
415 def __repr__(self):
414 def __repr__(self):
416 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
415 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
417
416
418 def traceback(self):
417 def traceback(self):
419 print self._tb
418 print self._tb
420
419
421 def run(self):
420 def run(self):
422 try:
421 try:
423 self.status = BackgroundJobBase.stat_running
422 self.status = BackgroundJobBase.stat_running
424 self.stat_code = BackgroundJobBase.stat_running_c
423 self.stat_code = BackgroundJobBase.stat_running_c
425 self.result = self.call()
424 self.result = self.call()
426 except:
425 except:
427 self.status = BackgroundJobBase.stat_dead
426 self.status = BackgroundJobBase.stat_dead
428 self.stat_code = BackgroundJobBase.stat_dead_c
427 self.stat_code = BackgroundJobBase.stat_dead_c
429 self.finished = None
428 self.finished = None
430 self.result = ('<BackgroundJob died, call jobs.traceback() for details>')
429 self.result = ('<BackgroundJob died, call jobs.traceback() for details>')
431 self._tb = self._make_tb()
430 self._tb = self._make_tb()
432 else:
431 else:
433 self.status = BackgroundJobBase.stat_completed
432 self.status = BackgroundJobBase.stat_completed
434 self.stat_code = BackgroundJobBase.stat_completed_c
433 self.stat_code = BackgroundJobBase.stat_completed_c
435 self.finished = True
434 self.finished = True
436
435
437
436
438 class BackgroundJobExpr(BackgroundJobBase):
437 class BackgroundJobExpr(BackgroundJobBase):
439 """Evaluate an expression as a background job (uses a separate thread)."""
438 """Evaluate an expression as a background job (uses a separate thread)."""
440
439
441 def __init__(self, expression, glob=None, loc=None):
440 def __init__(self, expression, glob=None, loc=None):
442 """Create a new job from a string which can be fed to eval().
441 """Create a new job from a string which can be fed to eval().
443
442
444 global/locals dicts can be provided, which will be passed to the eval
443 global/locals dicts can be provided, which will be passed to the eval
445 call."""
444 call."""
446
445
447 # fail immediately if the given expression can't be compiled
446 # fail immediately if the given expression can't be compiled
448 self.code = compile(expression,'<BackgroundJob compilation>','eval')
447 self.code = compile(expression,'<BackgroundJob compilation>','eval')
449
448
450 glob = {} if glob is None else glob
449 glob = {} if glob is None else glob
451 loc = {} if loc is None else loc
450 loc = {} if loc is None else loc
452 self.expression = self.strform = expression
451 self.expression = self.strform = expression
453 self.glob = glob
452 self.glob = glob
454 self.loc = loc
453 self.loc = loc
455 self._init()
454 self._init()
456
455
457 def call(self):
456 def call(self):
458 return eval(self.code,self.glob,self.loc)
457 return eval(self.code,self.glob,self.loc)
459
458
460
459
461 class BackgroundJobFunc(BackgroundJobBase):
460 class BackgroundJobFunc(BackgroundJobBase):
462 """Run a function call as a background job (uses a separate thread)."""
461 """Run a function call as a background job (uses a separate thread)."""
463
462
464 def __init__(self, func, *args, **kwargs):
463 def __init__(self, func, *args, **kwargs):
465 """Create a new job from a callable object.
464 """Create a new job from a callable object.
466
465
467 Any positional arguments and keyword args given to this constructor
466 Any positional arguments and keyword args given to this constructor
468 after the initial callable are passed directly to it."""
467 after the initial callable are passed directly to it."""
469
468
470 if not callable(func):
469 if not callable(func):
471 raise TypeError(
470 raise TypeError(
472 'first argument to BackgroundJobFunc must be callable')
471 'first argument to BackgroundJobFunc must be callable')
473
472
474 self.func = func
473 self.func = func
475 self.args = args
474 self.args = args
476 self.kwargs = kwargs
475 self.kwargs = kwargs
477 # The string form will only include the function passed, because
476 # The string form will only include the function passed, because
478 # generating string representations of the arguments is a potentially
477 # generating string representations of the arguments is a potentially
479 # _very_ expensive operation (e.g. with large arrays).
478 # _very_ expensive operation (e.g. with large arrays).
480 self.strform = str(func)
479 self.strform = str(func)
481 self._init()
480 self._init()
482
481
483 def call(self):
482 def call(self):
484 return self.func(*self.args, **self.kwargs)
483 return self.func(*self.args, **self.kwargs)
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
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