##// END OF EJS Templates
- Made the internal crash handler very customizable for end-user apps based...
fptest -
Show More

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

@@ -1,111 +1,227 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: 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 $Id: CrashHandler.py 1326 2006-05-25 02:07:11Z fperez $"""
4 $Id: CrashHandler.py 1828 2006-10-16 02:04:33Z fptest $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
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 from IPython import Release
13 from IPython import Release
14 __author__ = '%s <%s>' % Release.authors['Fernando']
14 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __license__ = Release.license
15 __license__ = Release.license
16 __version__ = Release.version
16 __version__ = Release.version
17
17
18 #****************************************************************************
18 #****************************************************************************
19 # Required modules
19 # Required modules
20
20
21 # From the standard library
21 # From the standard library
22 import os
22 import os
23 import sys
23 import sys
24 from pprint import pprint,pformat
24 from pprint import pprint,pformat
25
25
26 # Homebrewed
26 # Homebrewed
27 from IPython.Itpl import Itpl,itpl,printpl
27 from IPython.Itpl import Itpl,itpl,printpl
28 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
28 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
29 from IPython import ultraTB
29 from IPython import ultraTB
30 from IPython.genutils import *
30 from IPython.genutils import *
31
31
32 #****************************************************************************
32 #****************************************************************************
33 class CrashHandler:
33 class CrashHandler:
34 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
34 """Customizable crash handlers for IPython-based systems.
35
35
36 def __init__(self,IP):
36 Instances of this class provide a __call__ method which can be used as a
37 sys.excepthook, i.e., the __call__ signature is:
38
39 def __call__(self,etype, evalue, etb)
40
41 """
42
43 def __init__(self,IP,app_name,contact_name,contact_email,
44 bug_tracker,crash_report_fname,
45 show_crash_traceback=True):
46 """New crash handler.
47
48 Inputs:
49
50 - IP: a running IPython instance, which will be queried at crash time
51 for internal information.
52
53 - app_name: a string containing the name of your application.
54
55 - contact_name: a string with the name of the person to contact.
56
57 - contact_email: a string with the email address of the contact.
58
59 - bug_tracker: a string with the URL for your project's bug tracker.
60
61 - crash_report_fname: a string with the filename for the crash report
62 to be saved in. These reports are left in the ipython user directory
63 as determined by the running IPython instance.
64
65 Optional inputs:
66
67 - show_crash_traceback(True): if false, don't print the crash
68 traceback on stderr, only generate the on-disk report
69
70
71 Non-argument instance attributes:
72
73 These instances contain some non-argument attributes which allow for
74 further customization of the crash handler's behavior. Please see the
75 source for further details.
76 """
77
78 # apply args into instance
37 self.IP = IP # IPython instance
79 self.IP = IP # IPython instance
38 self.bug_contact = Release.authors['Ville'][0]
80 self.app_name = app_name
39 self.mailto = Release.authors['Ville'][1]
81 self.contact_name = contact_name
82 self.contact_email = contact_email
83 self.bug_tracker = bug_tracker
84 self.crash_report_fname = crash_report_fname
85 self.show_crash_traceback = show_crash_traceback
86
87 # Hardcoded defaults, which can be overridden either by subclasses or
88 # at runtime for the instance.
89
90 # Template for the user message. Subclasses which completely override
91 # this, or user apps, can modify it to suit their tastes. It gets
92 # expanded using itpl, so calls of the kind $self.foo are valid.
93 self.user_message_template = """
94 Oops, $self.app_name crashed. We do our best to make it stable, but...
95
96 A crash report was automatically generated with the following information:
97 - A verbatim copy of the crash traceback.
98 - A copy of your input history during this session.
99 - Data on your current $self.app_name configuration.
100
101 It was left in the file named:
102 \t'$self.crash_report_fname'
103 If you can email this file to the developers, the information in it will help
104 them in understanding and correcting the problem.
105
106 You can mail it to: $self.contact_name at $self.contact_email
107 with the subject '$self.app_name Crash Report'.
108
109 If you want to do it now, the following command will work (under Unix):
110 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
111
112 To ensure accurate tracking of this issue, please file a report about it at:
113 $self.bug_tracker
114 """
40
115
41 def __call__(self,etype, evalue, etb):
116 def __call__(self,etype, evalue, etb):
117 """Handle an exception, call for compatible with sys.excepthook"""
42
118
43 # Report tracebacks shouldn't use color in general (safer for users)
119 # Report tracebacks shouldn't use color in general (safer for users)
44 color_scheme = 'NoColor'
120 color_scheme = 'NoColor'
45
121
46 # Use this ONLY for developer debugging (keep commented out for release)
122 # Use this ONLY for developer debugging (keep commented out for release)
47 #color_scheme = 'Linux' # dbg
123 #color_scheme = 'Linux' # dbg
48
124
49 try:
125 try:
50 rptdir = self.IP.rc.ipythondir
126 rptdir = self.IP.rc.ipythondir
51 except:
127 except:
52 rptdir = os.getcwd()
128 rptdir = os.getcwd()
53 if not os.path.isdir(rptdir):
129 if not os.path.isdir(rptdir):
54 rptdir = os.getcwd()
130 rptdir = os.getcwd()
55 self.report_name = os.path.join(rptdir,'IPython_crash_report.txt')
131 report_name = os.path.join(rptdir,self.crash_report_fname)
56 self.TBhandler = ultraTB.VerboseTB(color_scheme=color_scheme,long_header=1)
132 # write the report filename into the instance dict so it can get
57 traceback = self.TBhandler.text(etype,evalue,etb,context=31)
133 # properly expanded out in the user message template
134 self.crash_report_fname = report_name
135 TBhandler = ultraTB.VerboseTB(color_scheme=color_scheme,
136 long_header=1)
137 traceback = TBhandler.text(etype,evalue,etb,context=31)
58
138
59 # print traceback to screen
139 # print traceback to screen
60 print >> sys.stderr, traceback
140 if self.show_crash_traceback:
141 print >> sys.stderr, traceback
61
142
62 # and generate a complete report on disk
143 # and generate a complete report on disk
63 try:
144 try:
64 report = open(self.report_name,'w')
145 report = open(report_name,'w')
65 except:
146 except:
66 print >> sys.stderr, 'Could not create crash report on disk.'
147 print >> sys.stderr, 'Could not create crash report on disk.'
67 return
148 return
68
149
69 msg = itpl('\n'+'*'*70+'\n'
150 # Inform user on stderr of what happened
70 """
151 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
71 Oops, IPython crashed. We do our best to make it stable, but...
152 print >> sys.stderr, msg
72
153
73 A crash report was automatically generated with the following information:
154 # Construct report on disk
74 - A verbatim copy of the traceback above this text.
155 report.write(self.make_report(traceback))
75 - A copy of your input history during this session.
156 report.close()
76 - Data on your current IPython configuration.
77
157
78 It was left in the file named:
158 def make_report(self,traceback):
79 \t'$self.report_name'
159 """Return a string containing a crash report."""
80 If you can email this file to the developers, the information in it will help
81 them in understanding and correcting the problem.
82
160
83 You can mail it to $self.bug_contact at $self.mailto
161 sec_sep = '\n\n'+'*'*75+'\n\n'
84 with the subject 'IPython Crash Report'.
85
162
86 If you want to do it now, the following command will work (under Unix):
163 report = []
87 mail -s 'IPython Crash Report' $self.mailto < $self.report_name
164 rpt_add = report.append
165
166 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
167 rpt_add('IPython version: %s \n\n' % Release.version)
168 rpt_add('SVN revision : %s \n\n' % Release.revision)
169 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
170 (os.name,sys.platform) )
171 rpt_add(sec_sep+'Current user configuration structure:\n\n')
172 rpt_add(pformat(self.IP.rc.dict()))
173 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
174 try:
175 rpt_add(sec_sep+"History of session input:")
176 for line in self.IP.user_ns['_ih']:
177 rpt_add(line)
178 rpt_add('\n*** Last line of input (may not be in above history):\n')
179 rpt_add(self.IP._last_input_line+'\n')
180 except:
181 pass
88
182
89 To ensure accurate tracking of this issue, please file a report about it at:
183 return ''.join(report)
90 http://projects.scipy.org/ipython/ipython/report
184
91 """)
185 class IPythonCrashHandler(CrashHandler):
92 print >> sys.stderr, msg
186 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
187
188 def __init__(self,IP):
189
190 # Set here which of the IPython authors should be listed as contact
191 AUTHOR_CONTACT = 'Ville'
192
193 # Set argument defaults
194 app_name = 'IPython'
195 bug_tracker = 'http://projects.scipy.org/ipython/ipython/report'
196 contact_name,contact_email = Release.authors[AUTHOR_CONTACT][:2]
197 crash_report_fname = 'IPython_crash_report.txt'
198 # Call parent constructor
199 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
200 bug_tracker,crash_report_fname)
201
202 def make_report(self,traceback):
203 """Return a string containing a crash report."""
93
204
94 sec_sep = '\n\n'+'*'*75+'\n\n'
205 sec_sep = '\n\n'+'*'*75+'\n\n'
95 report.write('*'*75+'\n\n'+'IPython post-mortem report\n\n')
206
96 report.write('IPython version: %s \n\n' % Release.version)
207 report = []
97 report.write('SVN revision : %s \n\n' % Release.revision)
208 rpt_add = report.append
98 report.write('Platform info : os.name -> %s, sys.platform -> %s' %
209
210 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
211 rpt_add('IPython version: %s \n\n' % Release.version)
212 rpt_add('SVN revision : %s \n\n' % Release.revision)
213 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
99 (os.name,sys.platform) )
214 (os.name,sys.platform) )
100 report.write(sec_sep+'Current user configuration structure:\n\n')
215 rpt_add(sec_sep+'Current user configuration structure:\n\n')
101 report.write(pformat(self.IP.rc.dict()))
216 rpt_add(pformat(self.IP.rc.dict()))
102 report.write(sec_sep+'Crash traceback:\n\n' + traceback)
217 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
103 try:
218 try:
104 report.write(sec_sep+"History of session input:")
219 rpt_add(sec_sep+"History of session input:")
105 for line in self.IP.user_ns['_ih']:
220 for line in self.IP.user_ns['_ih']:
106 report.write(line)
221 rpt_add(line)
107 report.write('\n*** Last line of input (may not be in above history):\n')
222 rpt_add('\n*** Last line of input (may not be in above history):\n')
108 report.write(self.IP._last_input_line+'\n')
223 rpt_add(self.IP._last_input_line+'\n')
109 except:
224 except:
110 pass
225 pass
111 report.close()
226
227 return ''.join(report)
@@ -1,328 +1,330 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29 ip = IPython.ipapi.get()
30
30
31 def ankka_f(self, arg):
31 def ankka_f(self, arg):
32 print "Ankka",self,"says uppercase:",arg.upper()
32 print "Ankka",self,"says uppercase:",arg.upper()
33
33
34 ip.expose_magic("ankka",ankka_f)
34 ip.expose_magic("ankka",ankka_f)
35
35
36 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
37 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
38 ip.system('pwd')
39
39
40 ip.ex('import re')
40 ip.ex('import re')
41 ip.ex("""
41 ip.ex("""
42 def funcci(a,b):
42 def funcci(a,b):
43 print a+b
43 print a+b
44 print funcci(3,4)
44 print funcci(3,4)
45 """)
45 """)
46 ip.ex("funcci(348,9)")
46 ip.ex("funcci(348,9)")
47
47
48 def jed_editor(self,filename, linenum=None):
48 def jed_editor(self,filename, linenum=None):
49 print "Calling my own editor, jed ... via hook!"
49 print "Calling my own editor, jed ... via hook!"
50 import os
50 import os
51 if linenum is None: linenum = 0
51 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
52 os.system('jed +%d %s' % (linenum, filename))
53 print "exiting jed"
53 print "exiting jed"
54
54
55 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
56
56
57 o = ip.options
57 o = ip.options
58 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
59
59
60 print "done!"
60 print "done!"
61 '''
61 '''
62
62
63 # stdlib imports
63 # stdlib imports
64 import __builtin__
64 import __builtin__
65 import sys
65 import sys
66
66
67 # our own
67 # our own
68 from IPython.genutils import warn,error
68 from IPython.genutils import warn,error
69
69
70 class TryNext(Exception):
70 class TryNext(Exception):
71 """Try next hook exception.
71 """Try next hook exception.
72
72
73 Raise this in your hook function to indicate that the next hook handler
73 Raise this in your hook function to indicate that the next hook handler
74 should be used to handle the operation. If you pass arguments to the
74 should be used to handle the operation. If you pass arguments to the
75 constructor those arguments will be used by the next hook instead of the
75 constructor those arguments will be used by the next hook instead of the
76 original ones.
76 original ones.
77 """
77 """
78
78
79 def __init__(self, *args, **kwargs):
79 def __init__(self, *args, **kwargs):
80 self.args = args
80 self.args = args
81 self.kwargs = kwargs
81 self.kwargs = kwargs
82
82
83 # contains the most recently instantiated IPApi
83 # contains the most recently instantiated IPApi
84
84
85 class IPythonNotRunning:
85 class IPythonNotRunning:
86 """Dummy do-nothing class.
86 """Dummy do-nothing class.
87
87
88 Instances of this class return a dummy attribute on all accesses, which
88 Instances of this class return a dummy attribute on all accesses, which
89 can be called and warns. This makes it easier to write scripts which use
89 can be called and warns. This makes it easier to write scripts which use
90 the ipapi.get() object for informational purposes to operate both with and
90 the ipapi.get() object for informational purposes to operate both with and
91 without ipython. Obviously code which uses the ipython object for
91 without ipython. Obviously code which uses the ipython object for
92 computations will not work, but this allows a wider range of code to
92 computations will not work, but this allows a wider range of code to
93 transparently work whether ipython is being used or not."""
93 transparently work whether ipython is being used or not."""
94
94
95 def __str__(self):
95 def __str__(self):
96 return "<IPythonNotRunning>"
96 return "<IPythonNotRunning>"
97
97
98 __repr__ = __str__
98 __repr__ = __str__
99
99
100 def __getattr__(self,name):
100 def __getattr__(self,name):
101 return self.dummy
101 return self.dummy
102
102
103 def dummy(self,*args,**kw):
103 def dummy(self,*args,**kw):
104 """Dummy function, which doesn't do anything but warn."""
104 """Dummy function, which doesn't do anything but warn."""
105 warn("IPython is not running, this is a dummy no-op function")
105 warn("IPython is not running, this is a dummy no-op function")
106
106
107 _recent = None
107 _recent = None
108
108
109
109
110 def get(allow_dummy=False):
110 def get(allow_dummy=False):
111 """Get an IPApi object.
111 """Get an IPApi object.
112
112
113 If allow_dummy is true, returns an instance of IPythonNotRunning
113 If allow_dummy is true, returns an instance of IPythonNotRunning
114 instead of None if not running under IPython.
114 instead of None if not running under IPython.
115
115
116 Running this should be the first thing you do when writing extensions that
116 Running this should be the first thing you do when writing extensions that
117 can be imported as normal modules. You can then direct all the
117 can be imported as normal modules. You can then direct all the
118 configuration operations against the returned object.
118 configuration operations against the returned object.
119 """
119 """
120 global _recent
120 global _recent
121 if allow_dummy and not _recent:
121 if allow_dummy and not _recent:
122 _recent = IPythonNotRunning()
122 _recent = IPythonNotRunning()
123 return _recent
123 return _recent
124
124
125 class IPApi:
125 class IPApi:
126 """ The actual API class for configuring IPython
126 """ The actual API class for configuring IPython
127
127
128 You should do all of the IPython configuration by getting an IPApi object
128 You should do all of the IPython configuration by getting an IPApi object
129 with IPython.ipapi.get() and using the attributes and methods of the
129 with IPython.ipapi.get() and using the attributes and methods of the
130 returned object."""
130 returned object."""
131
131
132 def __init__(self,ip):
132 def __init__(self,ip):
133
133
134 # All attributes exposed here are considered to be the public API of
134 # All attributes exposed here are considered to be the public API of
135 # IPython. As needs dictate, some of these may be wrapped as
135 # IPython. As needs dictate, some of these may be wrapped as
136 # properties.
136 # properties.
137
137
138 self.magic = ip.ipmagic
138 self.magic = ip.ipmagic
139
139
140 self.system = ip.ipsystem
140 self.system = ip.ipsystem
141
141
142 self.set_hook = ip.set_hook
142 self.set_hook = ip.set_hook
143
143
144 self.set_custom_exc = ip.set_custom_exc
144 self.set_custom_exc = ip.set_custom_exc
145
145
146 self.user_ns = ip.user_ns
146 self.user_ns = ip.user_ns
147
147
148 self.set_crash_handler = ip.set_crash_handler
149
148 # Session-specific data store, which can be used to store
150 # Session-specific data store, which can be used to store
149 # data that should persist through the ipython session.
151 # data that should persist through the ipython session.
150 self.meta = ip.meta
152 self.meta = ip.meta
151
153
152 # The ipython instance provided
154 # The ipython instance provided
153 self.IP = ip
155 self.IP = ip
154
156
155 global _recent
157 global _recent
156 _recent = self
158 _recent = self
157
159
158 # Use a property for some things which are added to the instance very
160 # Use a property for some things which are added to the instance very
159 # late. I don't have time right now to disentangle the initialization
161 # late. I don't have time right now to disentangle the initialization
160 # order issues, so a property lets us delay item extraction while
162 # order issues, so a property lets us delay item extraction while
161 # providing a normal attribute API.
163 # providing a normal attribute API.
162 def get_db(self):
164 def get_db(self):
163 """A handle to persistent dict-like database (a PickleShareDB object)"""
165 """A handle to persistent dict-like database (a PickleShareDB object)"""
164 return self.IP.db
166 return self.IP.db
165
167
166 db = property(get_db,None,None,get_db.__doc__)
168 db = property(get_db,None,None,get_db.__doc__)
167
169
168 def get_options(self):
170 def get_options(self):
169 """All configurable variables."""
171 """All configurable variables."""
170 return self.IP.rc
172 return self.IP.rc
171
173
172 options = property(get_options,None,None,get_options.__doc__)
174 options = property(get_options,None,None,get_options.__doc__)
173
175
174 def expose_magic(self,magicname, func):
176 def expose_magic(self,magicname, func):
175 ''' Expose own function as magic function for ipython
177 ''' Expose own function as magic function for ipython
176
178
177 def foo_impl(self,parameter_s=''):
179 def foo_impl(self,parameter_s=''):
178 """My very own magic!. (Use docstrings, IPython reads them)."""
180 """My very own magic!. (Use docstrings, IPython reads them)."""
179 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
181 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
180 print 'The self object is:',self
182 print 'The self object is:',self
181
183
182 ipapi.expose_magic("foo",foo_impl)
184 ipapi.expose_magic("foo",foo_impl)
183 '''
185 '''
184
186
185 import new
187 import new
186 im = new.instancemethod(func,self.IP, self.IP.__class__)
188 im = new.instancemethod(func,self.IP, self.IP.__class__)
187 setattr(self.IP, "magic_" + magicname, im)
189 setattr(self.IP, "magic_" + magicname, im)
188
190
189 def ex(self,cmd):
191 def ex(self,cmd):
190 """ Execute a normal python statement in user namespace """
192 """ Execute a normal python statement in user namespace """
191 exec cmd in self.user_ns
193 exec cmd in self.user_ns
192
194
193 def ev(self,expr):
195 def ev(self,expr):
194 """ Evaluate python expression expr in user namespace
196 """ Evaluate python expression expr in user namespace
195
197
196 Returns the result of evaluation"""
198 Returns the result of evaluation"""
197 return eval(expr,self.user_ns)
199 return eval(expr,self.user_ns)
198
200
199 def runlines(self,lines):
201 def runlines(self,lines):
200 """ Run the specified lines in interpreter, honoring ipython directives.
202 """ Run the specified lines in interpreter, honoring ipython directives.
201
203
202 This allows %magic and !shell escape notations.
204 This allows %magic and !shell escape notations.
203
205
204 Takes either all lines in one string or list of lines.
206 Takes either all lines in one string or list of lines.
205 """
207 """
206 if isinstance(lines,basestring):
208 if isinstance(lines,basestring):
207 self.IP.runlines(lines)
209 self.IP.runlines(lines)
208 else:
210 else:
209 self.IP.runlines('\n'.join(lines))
211 self.IP.runlines('\n'.join(lines))
210
212
211 def to_user_ns(self,vars):
213 def to_user_ns(self,vars):
212 """Inject a group of variables into the IPython user namespace.
214 """Inject a group of variables into the IPython user namespace.
213
215
214 Inputs:
216 Inputs:
215
217
216 - vars: string with variable names separated by whitespace
218 - vars: string with variable names separated by whitespace
217
219
218 This utility routine is meant to ease interactive debugging work,
220 This utility routine is meant to ease interactive debugging work,
219 where you want to easily propagate some internal variable in your code
221 where you want to easily propagate some internal variable in your code
220 up to the interactive namespace for further exploration.
222 up to the interactive namespace for further exploration.
221
223
222 When you run code via %run, globals in your script become visible at
224 When you run code via %run, globals in your script become visible at
223 the interactive prompt, but this doesn't happen for locals inside your
225 the interactive prompt, but this doesn't happen for locals inside your
224 own functions and methods. Yet when debugging, it is common to want
226 own functions and methods. Yet when debugging, it is common to want
225 to explore some internal variables further at the interactive propmt.
227 to explore some internal variables further at the interactive propmt.
226
228
227 Examples:
229 Examples:
228
230
229 To use this, you first must obtain a handle on the ipython object as
231 To use this, you first must obtain a handle on the ipython object as
230 indicated above, via:
232 indicated above, via:
231
233
232 import IPython.ipapi
234 import IPython.ipapi
233 ip = IPython.ipapi.get()
235 ip = IPython.ipapi.get()
234
236
235 Once this is done, inside a routine foo() where you want to expose
237 Once this is done, inside a routine foo() where you want to expose
236 variables x and y, you do the following:
238 variables x and y, you do the following:
237
239
238 def foo():
240 def foo():
239 ...
241 ...
240 x = your_computation()
242 x = your_computation()
241 y = something_else()
243 y = something_else()
242
244
243 # This pushes x and y to the interactive prompt immediately, even
245 # This pushes x and y to the interactive prompt immediately, even
244 # if this routine crashes on the next line after:
246 # if this routine crashes on the next line after:
245 ip.to_user_ns('x y')
247 ip.to_user_ns('x y')
246 ...
248 ...
247 # return
249 # return
248
250
249 If you need to rename variables, just use ip.user_ns with dict
251 If you need to rename variables, just use ip.user_ns with dict
250 and update:
252 and update:
251
253
252 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
254 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
253 # user namespace
255 # user namespace
254 ip.user_ns.update(dict(x=foo,y=bar))
256 ip.user_ns.update(dict(x=foo,y=bar))
255 """
257 """
256
258
257 # print 'vars given:',vars # dbg
259 # print 'vars given:',vars # dbg
258 # Get the caller's frame to evaluate the given names in
260 # Get the caller's frame to evaluate the given names in
259 cf = sys._getframe(1)
261 cf = sys._getframe(1)
260
262
261 user_ns = self.user_ns
263 user_ns = self.user_ns
262
264
263 for name in vars.split():
265 for name in vars.split():
264 try:
266 try:
265 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
267 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
266 except:
268 except:
267 error('could not get var. %s from %s' %
269 error('could not get var. %s from %s' %
268 (name,cf.f_code.co_name))
270 (name,cf.f_code.co_name))
269
271
270 def launch_new_instance(user_ns = None):
272 def launch_new_instance(user_ns = None):
271 """ Make and start a new ipython instance.
273 """ Make and start a new ipython instance.
272
274
273 This can be called even without having an already initialized
275 This can be called even without having an already initialized
274 ipython session running.
276 ipython session running.
275
277
276 This is also used as the egg entry point for the 'ipython' script.
278 This is also used as the egg entry point for the 'ipython' script.
277
279
278 """
280 """
279 ses = make_session(user_ns)
281 ses = make_session(user_ns)
280 ses.mainloop()
282 ses.mainloop()
281
283
282
284
283 def make_user_ns(user_ns = None):
285 def make_user_ns(user_ns = None):
284 """Return a valid user interactive namespace.
286 """Return a valid user interactive namespace.
285
287
286 This builds a dict with the minimal information needed to operate as a
288 This builds a dict with the minimal information needed to operate as a
287 valid IPython user namespace, which you can pass to the various embedding
289 valid IPython user namespace, which you can pass to the various embedding
288 classes in ipython.
290 classes in ipython.
289 """
291 """
290
292
291 if user_ns is None:
293 if user_ns is None:
292 # Set __name__ to __main__ to better match the behavior of the
294 # Set __name__ to __main__ to better match the behavior of the
293 # normal interpreter.
295 # normal interpreter.
294 user_ns = {'__name__' :'__main__',
296 user_ns = {'__name__' :'__main__',
295 '__builtins__' : __builtin__,
297 '__builtins__' : __builtin__,
296 }
298 }
297 else:
299 else:
298 user_ns.setdefault('__name__','__main__')
300 user_ns.setdefault('__name__','__main__')
299 user_ns.setdefault('__builtins__',__builtin__)
301 user_ns.setdefault('__builtins__',__builtin__)
300
302
301 return user_ns
303 return user_ns
302
304
303
305
304 def make_user_global_ns(ns = None):
306 def make_user_global_ns(ns = None):
305 """Return a valid user global namespace.
307 """Return a valid user global namespace.
306
308
307 Similar to make_user_ns(), but global namespaces are really only needed in
309 Similar to make_user_ns(), but global namespaces are really only needed in
308 embedded applications, where there is a distinction between the user's
310 embedded applications, where there is a distinction between the user's
309 interactive namespace and the global one where ipython is running."""
311 interactive namespace and the global one where ipython is running."""
310
312
311 if ns is None: ns = {}
313 if ns is None: ns = {}
312 return ns
314 return ns
313
315
314
316
315 def make_session(user_ns = None):
317 def make_session(user_ns = None):
316 """Makes, but does not launch an IPython session.
318 """Makes, but does not launch an IPython session.
317
319
318 Later on you can call obj.mainloop() on the returned object.
320 Later on you can call obj.mainloop() on the returned object.
319
321
320 Inputs:
322 Inputs:
321
323
322 - user_ns(None): a dict to be used as the user's namespace with initial
324 - user_ns(None): a dict to be used as the user's namespace with initial
323 data.
325 data.
324
326
325 WARNING: This should *not* be run when a session exists already."""
327 WARNING: This should *not* be run when a session exists already."""
326
328
327 import IPython
329 import IPython
328 return IPython.Shell.start(user_ns)
330 return IPython.Shell.start(user_ns)
@@ -1,2421 +1,2432 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 1822 2006-10-12 21:38:00Z vivainio $
9 $Id: iplib.py 1828 2006-10-16 02:04:33Z fptest $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pdb
50 import pdb
51 import pydoc
51 import pydoc
52 import re
52 import re
53 import shutil
53 import shutil
54 import string
54 import string
55 import sys
55 import sys
56 import tempfile
56 import tempfile
57 import traceback
57 import traceback
58 import types
58 import types
59 import pickleshare
59 import pickleshare
60 from sets import Set
60 from sets import Set
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class Quitter(object):
129 class Quitter(object):
130 """Simple class to handle exit, similar to Python 2.5's.
130 """Simple class to handle exit, similar to Python 2.5's.
131
131
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 doesn't do (obviously, since it doesn't know about ipython)."""
133 doesn't do (obviously, since it doesn't know about ipython)."""
134
134
135 def __init__(self,shell,name):
135 def __init__(self,shell,name):
136 self.shell = shell
136 self.shell = shell
137 self.name = name
137 self.name = name
138
138
139 def __repr__(self):
139 def __repr__(self):
140 return 'Type %s() to exit.' % self.name
140 return 'Type %s() to exit.' % self.name
141 __str__ = __repr__
141 __str__ = __repr__
142
142
143 def __call__(self):
143 def __call__(self):
144 self.shell.exit()
144 self.shell.exit()
145
145
146 class InputList(list):
146 class InputList(list):
147 """Class to store user input.
147 """Class to store user input.
148
148
149 It's basically a list, but slices return a string instead of a list, thus
149 It's basically a list, but slices return a string instead of a list, thus
150 allowing things like (assuming 'In' is an instance):
150 allowing things like (assuming 'In' is an instance):
151
151
152 exec In[4:7]
152 exec In[4:7]
153
153
154 or
154 or
155
155
156 exec In[5:9] + In[14] + In[21:25]"""
156 exec In[5:9] + In[14] + In[21:25]"""
157
157
158 def __getslice__(self,i,j):
158 def __getslice__(self,i,j):
159 return ''.join(list.__getslice__(self,i,j))
159 return ''.join(list.__getslice__(self,i,j))
160
160
161 class SyntaxTB(ultraTB.ListTB):
161 class SyntaxTB(ultraTB.ListTB):
162 """Extension which holds some state: the last exception value"""
162 """Extension which holds some state: the last exception value"""
163
163
164 def __init__(self,color_scheme = 'NoColor'):
164 def __init__(self,color_scheme = 'NoColor'):
165 ultraTB.ListTB.__init__(self,color_scheme)
165 ultraTB.ListTB.__init__(self,color_scheme)
166 self.last_syntax_error = None
166 self.last_syntax_error = None
167
167
168 def __call__(self, etype, value, elist):
168 def __call__(self, etype, value, elist):
169 self.last_syntax_error = value
169 self.last_syntax_error = value
170 ultraTB.ListTB.__call__(self,etype,value,elist)
170 ultraTB.ListTB.__call__(self,etype,value,elist)
171
171
172 def clear_err_state(self):
172 def clear_err_state(self):
173 """Return the current error state and clear it"""
173 """Return the current error state and clear it"""
174 e = self.last_syntax_error
174 e = self.last_syntax_error
175 self.last_syntax_error = None
175 self.last_syntax_error = None
176 return e
176 return e
177
177
178 #****************************************************************************
178 #****************************************************************************
179 # Main IPython class
179 # Main IPython class
180
180
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 # until a full rewrite is made. I've cleaned all cross-class uses of
182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 # attributes and methods, but too much user code out there relies on the
183 # attributes and methods, but too much user code out there relies on the
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 #
185 #
186 # But at least now, all the pieces have been separated and we could, in
186 # But at least now, all the pieces have been separated and we could, in
187 # principle, stop using the mixin. This will ease the transition to the
187 # principle, stop using the mixin. This will ease the transition to the
188 # chainsaw branch.
188 # chainsaw branch.
189
189
190 # For reference, the following is the list of 'self.foo' uses in the Magic
190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 # class, to prevent clashes.
192 # class, to prevent clashes.
193
193
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 # 'self.value']
197 # 'self.value']
198
198
199 class InteractiveShell(object,Magic):
199 class InteractiveShell(object,Magic):
200 """An enhanced console for Python."""
200 """An enhanced console for Python."""
201
201
202 # class attribute to indicate whether the class supports threads or not.
202 # class attribute to indicate whether the class supports threads or not.
203 # Subclasses with thread support should override this as needed.
203 # Subclasses with thread support should override this as needed.
204 isthreaded = False
204 isthreaded = False
205
205
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 user_ns = None,user_global_ns=None,banner2='',
207 user_ns = None,user_global_ns=None,banner2='',
208 custom_exceptions=((),None),embedded=False):
208 custom_exceptions=((),None),embedded=False):
209
209
210 # log system
210 # log system
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212
212
213 # some minimal strict typechecks. For some core data structures, I
213 # some minimal strict typechecks. For some core data structures, I
214 # want actual basic python types, not just anything that looks like
214 # want actual basic python types, not just anything that looks like
215 # one. This is especially true for namespaces.
215 # one. This is especially true for namespaces.
216 for ns in (user_ns,user_global_ns):
216 for ns in (user_ns,user_global_ns):
217 if ns is not None and type(ns) != types.DictType:
217 if ns is not None and type(ns) != types.DictType:
218 raise TypeError,'namespace must be a dictionary'
218 raise TypeError,'namespace must be a dictionary'
219
219
220 # Job manager (for jobs run as background threads)
220 # Job manager (for jobs run as background threads)
221 self.jobs = BackgroundJobManager()
221 self.jobs = BackgroundJobManager()
222
222
223 # Store the actual shell's name
223 # Store the actual shell's name
224 self.name = name
224 self.name = name
225
225
226 # We need to know whether the instance is meant for embedding, since
226 # We need to know whether the instance is meant for embedding, since
227 # global/local namespaces need to be handled differently in that case
227 # global/local namespaces need to be handled differently in that case
228 self.embedded = embedded
228 self.embedded = embedded
229
229
230 # command compiler
230 # command compiler
231 self.compile = codeop.CommandCompiler()
231 self.compile = codeop.CommandCompiler()
232
232
233 # User input buffer
233 # User input buffer
234 self.buffer = []
234 self.buffer = []
235
235
236 # Default name given in compilation of code
236 # Default name given in compilation of code
237 self.filename = '<ipython console>'
237 self.filename = '<ipython console>'
238
238
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 __builtin__.exit = Quitter(self,'exit')
241 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.quit = Quitter(self,'quit')
242 __builtin__.quit = Quitter(self,'quit')
243
243
244 # Make an empty namespace, which extension writers can rely on both
244 # Make an empty namespace, which extension writers can rely on both
245 # existing and NEVER being used by ipython itself. This gives them a
245 # existing and NEVER being used by ipython itself. This gives them a
246 # convenient location for storing additional information and state
246 # convenient location for storing additional information and state
247 # their extensions may require, without fear of collisions with other
247 # their extensions may require, without fear of collisions with other
248 # ipython names that may develop later.
248 # ipython names that may develop later.
249 self.meta = Struct()
249 self.meta = Struct()
250
250
251 # Create the namespace where the user will operate. user_ns is
251 # Create the namespace where the user will operate. user_ns is
252 # normally the only one used, and it is passed to the exec calls as
252 # normally the only one used, and it is passed to the exec calls as
253 # the locals argument. But we do carry a user_global_ns namespace
253 # the locals argument. But we do carry a user_global_ns namespace
254 # given as the exec 'globals' argument, This is useful in embedding
254 # given as the exec 'globals' argument, This is useful in embedding
255 # situations where the ipython shell opens in a context where the
255 # situations where the ipython shell opens in a context where the
256 # distinction between locals and globals is meaningful.
256 # distinction between locals and globals is meaningful.
257
257
258 # FIXME. For some strange reason, __builtins__ is showing up at user
258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 # level as a dict instead of a module. This is a manual fix, but I
259 # level as a dict instead of a module. This is a manual fix, but I
260 # should really track down where the problem is coming from. Alex
260 # should really track down where the problem is coming from. Alex
261 # Schmolck reported this problem first.
261 # Schmolck reported this problem first.
262
262
263 # A useful post by Alex Martelli on this topic:
263 # A useful post by Alex Martelli on this topic:
264 # Re: inconsistent value from __builtins__
264 # Re: inconsistent value from __builtins__
265 # Von: Alex Martelli <aleaxit@yahoo.com>
265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 # Gruppen: comp.lang.python
267 # Gruppen: comp.lang.python
268
268
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 # > <type 'dict'>
271 # > <type 'dict'>
272 # > >>> print type(__builtins__)
272 # > >>> print type(__builtins__)
273 # > <type 'module'>
273 # > <type 'module'>
274 # > Is this difference in return value intentional?
274 # > Is this difference in return value intentional?
275
275
276 # Well, it's documented that '__builtins__' can be either a dictionary
276 # Well, it's documented that '__builtins__' can be either a dictionary
277 # or a module, and it's been that way for a long time. Whether it's
277 # or a module, and it's been that way for a long time. Whether it's
278 # intentional (or sensible), I don't know. In any case, the idea is
278 # intentional (or sensible), I don't know. In any case, the idea is
279 # that if you need to access the built-in namespace directly, you
279 # that if you need to access the built-in namespace directly, you
280 # should start with "import __builtin__" (note, no 's') which will
280 # should start with "import __builtin__" (note, no 's') which will
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282
282
283 # These routines return properly built dicts as needed by the rest of
283 # These routines return properly built dicts as needed by the rest of
284 # the code, and can also be used by extension writers to generate
284 # the code, and can also be used by extension writers to generate
285 # properly initialized namespaces.
285 # properly initialized namespaces.
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288
288
289 # Assign namespaces
289 # Assign namespaces
290 # This is the namespace where all normal user variables live
290 # This is the namespace where all normal user variables live
291 self.user_ns = user_ns
291 self.user_ns = user_ns
292 # Embedded instances require a separate namespace for globals.
292 # Embedded instances require a separate namespace for globals.
293 # Normally this one is unused by non-embedded instances.
293 # Normally this one is unused by non-embedded instances.
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312
312
313 # The user namespace MUST have a pointer to the shell itself.
313 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
314 self.user_ns[name] = self
315
315
316 # We need to insert into sys.modules something that looks like a
316 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
317 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
318 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
319 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
320 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
321 # everything into __main__.
322
322
323 # note, however, that we should only do this for non-embedded
323 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
324 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
325 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
326 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
327 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
328 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
329 # embedded in).
330
330
331 if not embedded:
331 if not embedded:
332 try:
332 try:
333 main_name = self.user_ns['__name__']
333 main_name = self.user_ns['__name__']
334 except KeyError:
334 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
336 else:
337 #print "pickle hack in place" # dbg
337 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
338 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
339 sys.modules[main_name] = FakeModule(self.user_ns)
340
340
341 # List of input with multi-line handling.
341 # List of input with multi-line handling.
342 # Fill its zero entry, user counter starts at 1
342 # Fill its zero entry, user counter starts at 1
343 self.input_hist = InputList(['\n'])
343 self.input_hist = InputList(['\n'])
344 # This one will hold the 'raw' input history, without any
344 # This one will hold the 'raw' input history, without any
345 # pre-processing. This will allow users to retrieve the input just as
345 # pre-processing. This will allow users to retrieve the input just as
346 # it was exactly typed in by the user, with %hist -r.
346 # it was exactly typed in by the user, with %hist -r.
347 self.input_hist_raw = InputList(['\n'])
347 self.input_hist_raw = InputList(['\n'])
348
348
349 # list of visited directories
349 # list of visited directories
350 try:
350 try:
351 self.dir_hist = [os.getcwd()]
351 self.dir_hist = [os.getcwd()]
352 except IOError, e:
352 except IOError, e:
353 self.dir_hist = []
353 self.dir_hist = []
354
354
355 # dict of output history
355 # dict of output history
356 self.output_hist = {}
356 self.output_hist = {}
357
357
358 # dict of things NOT to alias (keywords, builtins and some magics)
358 # dict of things NOT to alias (keywords, builtins and some magics)
359 no_alias = {}
359 no_alias = {}
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 for key in keyword.kwlist + no_alias_magics:
361 for key in keyword.kwlist + no_alias_magics:
362 no_alias[key] = 1
362 no_alias[key] = 1
363 no_alias.update(__builtin__.__dict__)
363 no_alias.update(__builtin__.__dict__)
364 self.no_alias = no_alias
364 self.no_alias = no_alias
365
365
366 # make global variables for user access to these
366 # make global variables for user access to these
367 self.user_ns['_ih'] = self.input_hist
367 self.user_ns['_ih'] = self.input_hist
368 self.user_ns['_oh'] = self.output_hist
368 self.user_ns['_oh'] = self.output_hist
369 self.user_ns['_dh'] = self.dir_hist
369 self.user_ns['_dh'] = self.dir_hist
370
370
371 # user aliases to input and output histories
371 # user aliases to input and output histories
372 self.user_ns['In'] = self.input_hist
372 self.user_ns['In'] = self.input_hist
373 self.user_ns['Out'] = self.output_hist
373 self.user_ns['Out'] = self.output_hist
374
374
375 # Object variable to store code object waiting execution. This is
375 # Object variable to store code object waiting execution. This is
376 # used mainly by the multithreaded shells, but it can come in handy in
376 # used mainly by the multithreaded shells, but it can come in handy in
377 # other situations. No need to use a Queue here, since it's a single
377 # other situations. No need to use a Queue here, since it's a single
378 # item which gets cleared once run.
378 # item which gets cleared once run.
379 self.code_to_run = None
379 self.code_to_run = None
380
380
381 # escapes for automatic behavior on the command line
381 # escapes for automatic behavior on the command line
382 self.ESC_SHELL = '!'
382 self.ESC_SHELL = '!'
383 self.ESC_HELP = '?'
383 self.ESC_HELP = '?'
384 self.ESC_MAGIC = '%'
384 self.ESC_MAGIC = '%'
385 self.ESC_QUOTE = ','
385 self.ESC_QUOTE = ','
386 self.ESC_QUOTE2 = ';'
386 self.ESC_QUOTE2 = ';'
387 self.ESC_PAREN = '/'
387 self.ESC_PAREN = '/'
388
388
389 # And their associated handlers
389 # And their associated handlers
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
393 self.ESC_MAGIC : self.handle_magic,
393 self.ESC_MAGIC : self.handle_magic,
394 self.ESC_HELP : self.handle_help,
394 self.ESC_HELP : self.handle_help,
395 self.ESC_SHELL : self.handle_shell_escape,
395 self.ESC_SHELL : self.handle_shell_escape,
396 }
396 }
397
397
398 # class initializations
398 # class initializations
399 Magic.__init__(self,self)
399 Magic.__init__(self,self)
400
400
401 # Python source parser/formatter for syntax highlighting
401 # Python source parser/formatter for syntax highlighting
402 pyformat = PyColorize.Parser().format
402 pyformat = PyColorize.Parser().format
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404
404
405 # hooks holds pointers used for user-side customizations
405 # hooks holds pointers used for user-side customizations
406 self.hooks = Struct()
406 self.hooks = Struct()
407
407
408 # Set all default hooks, defined in the IPython.hooks module.
408 # Set all default hooks, defined in the IPython.hooks module.
409 hooks = IPython.hooks
409 hooks = IPython.hooks
410 for hook_name in hooks.__all__:
410 for hook_name in hooks.__all__:
411 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
411 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
412 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
412 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
413 #print "bound hook",hook_name
413 #print "bound hook",hook_name
414
414
415 # Flag to mark unconditional exit
415 # Flag to mark unconditional exit
416 self.exit_now = False
416 self.exit_now = False
417
417
418 self.usage_min = """\
418 self.usage_min = """\
419 An enhanced console for Python.
419 An enhanced console for Python.
420 Some of its features are:
420 Some of its features are:
421 - Readline support if the readline library is present.
421 - Readline support if the readline library is present.
422 - Tab completion in the local namespace.
422 - Tab completion in the local namespace.
423 - Logging of input, see command-line options.
423 - Logging of input, see command-line options.
424 - System shell escape via ! , eg !ls.
424 - System shell escape via ! , eg !ls.
425 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
425 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
426 - Keeps track of locally defined variables via %who, %whos.
426 - Keeps track of locally defined variables via %who, %whos.
427 - Show object information with a ? eg ?x or x? (use ?? for more info).
427 - Show object information with a ? eg ?x or x? (use ?? for more info).
428 """
428 """
429 if usage: self.usage = usage
429 if usage: self.usage = usage
430 else: self.usage = self.usage_min
430 else: self.usage = self.usage_min
431
431
432 # Storage
432 # Storage
433 self.rc = rc # This will hold all configuration information
433 self.rc = rc # This will hold all configuration information
434 self.pager = 'less'
434 self.pager = 'less'
435 # temporary files used for various purposes. Deleted at exit.
435 # temporary files used for various purposes. Deleted at exit.
436 self.tempfiles = []
436 self.tempfiles = []
437
437
438 # Keep track of readline usage (later set by init_readline)
438 # Keep track of readline usage (later set by init_readline)
439 self.has_readline = False
439 self.has_readline = False
440
440
441 # template for logfile headers. It gets resolved at runtime by the
441 # template for logfile headers. It gets resolved at runtime by the
442 # logstart method.
442 # logstart method.
443 self.loghead_tpl = \
443 self.loghead_tpl = \
444 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
444 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
445 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
445 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
446 #log# opts = %s
446 #log# opts = %s
447 #log# args = %s
447 #log# args = %s
448 #log# It is safe to make manual edits below here.
448 #log# It is safe to make manual edits below here.
449 #log#-----------------------------------------------------------------------
449 #log#-----------------------------------------------------------------------
450 """
450 """
451 # for pushd/popd management
451 # for pushd/popd management
452 try:
452 try:
453 self.home_dir = get_home_dir()
453 self.home_dir = get_home_dir()
454 except HomeDirError,msg:
454 except HomeDirError,msg:
455 fatal(msg)
455 fatal(msg)
456
456
457 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
457 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
458
458
459 # Functions to call the underlying shell.
459 # Functions to call the underlying shell.
460
460
461 # utility to expand user variables via Itpl
461 # utility to expand user variables via Itpl
462 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
462 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
463 self.user_ns))
463 self.user_ns))
464 # The first is similar to os.system, but it doesn't return a value,
464 # The first is similar to os.system, but it doesn't return a value,
465 # and it allows interpolation of variables in the user's namespace.
465 # and it allows interpolation of variables in the user's namespace.
466 self.system = lambda cmd: shell(self.var_expand(cmd),
466 self.system = lambda cmd: shell(self.var_expand(cmd),
467 header='IPython system call: ',
467 header='IPython system call: ',
468 verbose=self.rc.system_verbose)
468 verbose=self.rc.system_verbose)
469 # These are for getoutput and getoutputerror:
469 # These are for getoutput and getoutputerror:
470 self.getoutput = lambda cmd: \
470 self.getoutput = lambda cmd: \
471 getoutput(self.var_expand(cmd),
471 getoutput(self.var_expand(cmd),
472 header='IPython system call: ',
472 header='IPython system call: ',
473 verbose=self.rc.system_verbose)
473 verbose=self.rc.system_verbose)
474 self.getoutputerror = lambda cmd: \
474 self.getoutputerror = lambda cmd: \
475 getoutputerror(self.var_expand(cmd),
475 getoutputerror(self.var_expand(cmd),
476 header='IPython system call: ',
476 header='IPython system call: ',
477 verbose=self.rc.system_verbose)
477 verbose=self.rc.system_verbose)
478
478
479 # RegExp for splitting line contents into pre-char//first
479 # RegExp for splitting line contents into pre-char//first
480 # word-method//rest. For clarity, each group in on one line.
480 # word-method//rest. For clarity, each group in on one line.
481
481
482 # WARNING: update the regexp if the above escapes are changed, as they
482 # WARNING: update the regexp if the above escapes are changed, as they
483 # are hardwired in.
483 # are hardwired in.
484
484
485 # Don't get carried away with trying to make the autocalling catch too
485 # Don't get carried away with trying to make the autocalling catch too
486 # much: it's better to be conservative rather than to trigger hidden
486 # much: it's better to be conservative rather than to trigger hidden
487 # evals() somewhere and end up causing side effects.
487 # evals() somewhere and end up causing side effects.
488
488
489 self.line_split = re.compile(r'^([\s*,;/])'
489 self.line_split = re.compile(r'^([\s*,;/])'
490 r'([\?\w\.]+\w*\s*)'
490 r'([\?\w\.]+\w*\s*)'
491 r'(\(?.*$)')
491 r'(\(?.*$)')
492
492
493 # Original re, keep around for a while in case changes break something
493 # Original re, keep around for a while in case changes break something
494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
495 # r'(\s*[\?\w\.]+\w*\s*)'
495 # r'(\s*[\?\w\.]+\w*\s*)'
496 # r'(\(?.*$)')
496 # r'(\(?.*$)')
497
497
498 # RegExp to identify potential function names
498 # RegExp to identify potential function names
499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
500
500
501 # RegExp to exclude strings with this start from autocalling. In
501 # RegExp to exclude strings with this start from autocalling. In
502 # particular, all binary operators should be excluded, so that if foo
502 # particular, all binary operators should be excluded, so that if foo
503 # is callable, foo OP bar doesn't become foo(OP bar), which is
503 # is callable, foo OP bar doesn't become foo(OP bar), which is
504 # invalid. The characters '!=()' don't need to be checked for, as the
504 # invalid. The characters '!=()' don't need to be checked for, as the
505 # _prefilter routine explicitely does so, to catch direct calls and
505 # _prefilter routine explicitely does so, to catch direct calls and
506 # rebindings of existing names.
506 # rebindings of existing names.
507
507
508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
509 # it affects the rest of the group in square brackets.
509 # it affects the rest of the group in square brackets.
510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
511 '|^is |^not |^in |^and |^or ')
511 '|^is |^not |^in |^and |^or ')
512
512
513 # try to catch also methods for stuff in lists/tuples/dicts: off
513 # try to catch also methods for stuff in lists/tuples/dicts: off
514 # (experimental). For this to work, the line_split regexp would need
514 # (experimental). For this to work, the line_split regexp would need
515 # to be modified so it wouldn't break things at '['. That line is
515 # to be modified so it wouldn't break things at '['. That line is
516 # nasty enough that I shouldn't change it until I can test it _well_.
516 # nasty enough that I shouldn't change it until I can test it _well_.
517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
518
518
519 # keep track of where we started running (mainly for crash post-mortem)
519 # keep track of where we started running (mainly for crash post-mortem)
520 self.starting_dir = os.getcwd()
520 self.starting_dir = os.getcwd()
521
521
522 # Various switches which can be set
522 # Various switches which can be set
523 self.CACHELENGTH = 5000 # this is cheap, it's just text
523 self.CACHELENGTH = 5000 # this is cheap, it's just text
524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
525 self.banner2 = banner2
525 self.banner2 = banner2
526
526
527 # TraceBack handlers:
527 # TraceBack handlers:
528
528
529 # Syntax error handler.
529 # Syntax error handler.
530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
531
531
532 # The interactive one is initialized with an offset, meaning we always
532 # The interactive one is initialized with an offset, meaning we always
533 # want to remove the topmost item in the traceback, which is our own
533 # want to remove the topmost item in the traceback, which is our own
534 # internal code. Valid modes: ['Plain','Context','Verbose']
534 # internal code. Valid modes: ['Plain','Context','Verbose']
535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
536 color_scheme='NoColor',
536 color_scheme='NoColor',
537 tb_offset = 1)
537 tb_offset = 1)
538
538
539 # IPython itself shouldn't crash. This will produce a detailed
539 # IPython itself shouldn't crash. This will produce a detailed
540 # post-mortem if it does. But we only install the crash handler for
540 # post-mortem if it does. But we only install the crash handler for
541 # non-threaded shells, the threaded ones use a normal verbose reporter
541 # non-threaded shells, the threaded ones use a normal verbose reporter
542 # and lose the crash handler. This is because exceptions in the main
542 # and lose the crash handler. This is because exceptions in the main
543 # thread (such as in GUI code) propagate directly to sys.excepthook,
543 # thread (such as in GUI code) propagate directly to sys.excepthook,
544 # and there's no point in printing crash dumps for every user exception.
544 # and there's no point in printing crash dumps for every user exception.
545 if self.isthreaded:
545 if self.isthreaded:
546 sys.excepthook = ultraTB.FormattedTB()
546 ipCrashHandler = ultraTB.FormattedTB()
547 else:
547 else:
548 from IPython import CrashHandler
548 from IPython import CrashHandler
549 sys.excepthook = CrashHandler.CrashHandler(self)
549 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
550
550 self.set_crash_handler(ipCrashHandler)
551 # The instance will store a pointer to this, so that runtime code
552 # (such as magics) can access it. This is because during the
553 # read-eval loop, it gets temporarily overwritten (to deal with GUI
554 # frameworks).
555 self.sys_excepthook = sys.excepthook
556
551
557 # and add any custom exception handlers the user may have specified
552 # and add any custom exception handlers the user may have specified
558 self.set_custom_exc(*custom_exceptions)
553 self.set_custom_exc(*custom_exceptions)
559
554
560 # indentation management
555 # indentation management
561 self.autoindent = False
556 self.autoindent = False
562 self.indent_current_nsp = 0
557 self.indent_current_nsp = 0
563
558
564 # Make some aliases automatically
559 # Make some aliases automatically
565 # Prepare list of shell aliases to auto-define
560 # Prepare list of shell aliases to auto-define
566 if os.name == 'posix':
561 if os.name == 'posix':
567 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
562 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
568 'mv mv -i','rm rm -i','cp cp -i',
563 'mv mv -i','rm rm -i','cp cp -i',
569 'cat cat','less less','clear clear',
564 'cat cat','less less','clear clear',
570 # a better ls
565 # a better ls
571 'ls ls -F',
566 'ls ls -F',
572 # long ls
567 # long ls
573 'll ls -lF')
568 'll ls -lF')
574 # Extra ls aliases with color, which need special treatment on BSD
569 # Extra ls aliases with color, which need special treatment on BSD
575 # variants
570 # variants
576 ls_extra = ( # color ls
571 ls_extra = ( # color ls
577 'lc ls -F -o --color',
572 'lc ls -F -o --color',
578 # ls normal files only
573 # ls normal files only
579 'lf ls -F -o --color %l | grep ^-',
574 'lf ls -F -o --color %l | grep ^-',
580 # ls symbolic links
575 # ls symbolic links
581 'lk ls -F -o --color %l | grep ^l',
576 'lk ls -F -o --color %l | grep ^l',
582 # directories or links to directories,
577 # directories or links to directories,
583 'ldir ls -F -o --color %l | grep /$',
578 'ldir ls -F -o --color %l | grep /$',
584 # things which are executable
579 # things which are executable
585 'lx ls -F -o --color %l | grep ^-..x',
580 'lx ls -F -o --color %l | grep ^-..x',
586 )
581 )
587 # The BSDs don't ship GNU ls, so they don't understand the
582 # The BSDs don't ship GNU ls, so they don't understand the
588 # --color switch out of the box
583 # --color switch out of the box
589 if 'bsd' in sys.platform:
584 if 'bsd' in sys.platform:
590 ls_extra = ( # ls normal files only
585 ls_extra = ( # ls normal files only
591 'lf ls -lF | grep ^-',
586 'lf ls -lF | grep ^-',
592 # ls symbolic links
587 # ls symbolic links
593 'lk ls -lF | grep ^l',
588 'lk ls -lF | grep ^l',
594 # directories or links to directories,
589 # directories or links to directories,
595 'ldir ls -lF | grep /$',
590 'ldir ls -lF | grep /$',
596 # things which are executable
591 # things which are executable
597 'lx ls -lF | grep ^-..x',
592 'lx ls -lF | grep ^-..x',
598 )
593 )
599 auto_alias = auto_alias + ls_extra
594 auto_alias = auto_alias + ls_extra
600 elif os.name in ['nt','dos']:
595 elif os.name in ['nt','dos']:
601 auto_alias = ('dir dir /on', 'ls dir /on',
596 auto_alias = ('dir dir /on', 'ls dir /on',
602 'ddir dir /ad /on', 'ldir dir /ad /on',
597 'ddir dir /ad /on', 'ldir dir /ad /on',
603 'mkdir mkdir','rmdir rmdir','echo echo',
598 'mkdir mkdir','rmdir rmdir','echo echo',
604 'ren ren','cls cls','copy copy')
599 'ren ren','cls cls','copy copy')
605 else:
600 else:
606 auto_alias = ()
601 auto_alias = ()
607 self.auto_alias = [s.split(None,1) for s in auto_alias]
602 self.auto_alias = [s.split(None,1) for s in auto_alias]
608 # Call the actual (public) initializer
603 # Call the actual (public) initializer
609 self.init_auto_alias()
604 self.init_auto_alias()
610
605
611 # Produce a public API instance
606 # Produce a public API instance
612 self.api = IPython.ipapi.IPApi(self)
607 self.api = IPython.ipapi.IPApi(self)
613
608
614 # track which builtins we add, so we can clean up later
609 # track which builtins we add, so we can clean up later
615 self.builtins_added = {}
610 self.builtins_added = {}
616 # This method will add the necessary builtins for operation, but
611 # This method will add the necessary builtins for operation, but
617 # tracking what it did via the builtins_added dict.
612 # tracking what it did via the builtins_added dict.
618 self.add_builtins()
613 self.add_builtins()
619
614
620 # end __init__
615 # end __init__
621
616
622 def pre_config_initialization(self):
617 def pre_config_initialization(self):
623 """Pre-configuration init method
618 """Pre-configuration init method
624
619
625 This is called before the configuration files are processed to
620 This is called before the configuration files are processed to
626 prepare the services the config files might need.
621 prepare the services the config files might need.
627
622
628 self.rc already has reasonable default values at this point.
623 self.rc already has reasonable default values at this point.
629 """
624 """
630 rc = self.rc
625 rc = self.rc
631
626
632 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
627 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
633
628
634 def post_config_initialization(self):
629 def post_config_initialization(self):
635 """Post configuration init method
630 """Post configuration init method
636
631
637 This is called after the configuration files have been processed to
632 This is called after the configuration files have been processed to
638 'finalize' the initialization."""
633 'finalize' the initialization."""
639
634
640 rc = self.rc
635 rc = self.rc
641
636
642 # Object inspector
637 # Object inspector
643 self.inspector = OInspect.Inspector(OInspect.InspectColors,
638 self.inspector = OInspect.Inspector(OInspect.InspectColors,
644 PyColorize.ANSICodeColors,
639 PyColorize.ANSICodeColors,
645 'NoColor',
640 'NoColor',
646 rc.object_info_string_level)
641 rc.object_info_string_level)
647
642
648 # Load readline proper
643 # Load readline proper
649 if rc.readline:
644 if rc.readline:
650 self.init_readline()
645 self.init_readline()
651
646
652 # local shortcut, this is used a LOT
647 # local shortcut, this is used a LOT
653 self.log = self.logger.log
648 self.log = self.logger.log
654
649
655 # Initialize cache, set in/out prompts and printing system
650 # Initialize cache, set in/out prompts and printing system
656 self.outputcache = CachedOutput(self,
651 self.outputcache = CachedOutput(self,
657 rc.cache_size,
652 rc.cache_size,
658 rc.pprint,
653 rc.pprint,
659 input_sep = rc.separate_in,
654 input_sep = rc.separate_in,
660 output_sep = rc.separate_out,
655 output_sep = rc.separate_out,
661 output_sep2 = rc.separate_out2,
656 output_sep2 = rc.separate_out2,
662 ps1 = rc.prompt_in1,
657 ps1 = rc.prompt_in1,
663 ps2 = rc.prompt_in2,
658 ps2 = rc.prompt_in2,
664 ps_out = rc.prompt_out,
659 ps_out = rc.prompt_out,
665 pad_left = rc.prompts_pad_left)
660 pad_left = rc.prompts_pad_left)
666
661
667 # user may have over-ridden the default print hook:
662 # user may have over-ridden the default print hook:
668 try:
663 try:
669 self.outputcache.__class__.display = self.hooks.display
664 self.outputcache.__class__.display = self.hooks.display
670 except AttributeError:
665 except AttributeError:
671 pass
666 pass
672
667
673 # I don't like assigning globally to sys, because it means when embedding
668 # I don't like assigning globally to sys, because it means when embedding
674 # instances, each embedded instance overrides the previous choice. But
669 # instances, each embedded instance overrides the previous choice. But
675 # sys.displayhook seems to be called internally by exec, so I don't see a
670 # sys.displayhook seems to be called internally by exec, so I don't see a
676 # way around it.
671 # way around it.
677 sys.displayhook = self.outputcache
672 sys.displayhook = self.outputcache
678
673
679 # Set user colors (don't do it in the constructor above so that it
674 # Set user colors (don't do it in the constructor above so that it
680 # doesn't crash if colors option is invalid)
675 # doesn't crash if colors option is invalid)
681 self.magic_colors(rc.colors)
676 self.magic_colors(rc.colors)
682
677
683 # Set calling of pdb on exceptions
678 # Set calling of pdb on exceptions
684 self.call_pdb = rc.pdb
679 self.call_pdb = rc.pdb
685
680
686 # Load user aliases
681 # Load user aliases
687 for alias in rc.alias:
682 for alias in rc.alias:
688 self.magic_alias(alias)
683 self.magic_alias(alias)
689 self.hooks.late_startup_hook()
684 self.hooks.late_startup_hook()
690
685
691 batchrun = False
686 batchrun = False
692 for batchfile in [path(arg) for arg in self.rc.args
687 for batchfile in [path(arg) for arg in self.rc.args
693 if arg.lower().endswith('.ipy')]:
688 if arg.lower().endswith('.ipy')]:
694 if not batchfile.isfile():
689 if not batchfile.isfile():
695 print "No such batch file:", batchfile
690 print "No such batch file:", batchfile
696 continue
691 continue
697 self.api.runlines(batchfile.text())
692 self.api.runlines(batchfile.text())
698 batchrun = True
693 batchrun = True
699 if batchrun:
694 if batchrun:
700 self.exit_now = True
695 self.exit_now = True
701
696
702 def add_builtins(self):
697 def add_builtins(self):
703 """Store ipython references into the builtin namespace.
698 """Store ipython references into the builtin namespace.
704
699
705 Some parts of ipython operate via builtins injected here, which hold a
700 Some parts of ipython operate via builtins injected here, which hold a
706 reference to IPython itself."""
701 reference to IPython itself."""
707
702
708 # TODO: deprecate all except _ip; 'jobs' should be installed
703 # TODO: deprecate all except _ip; 'jobs' should be installed
709 # by an extension and the rest are under _ip, ipalias is redundant
704 # by an extension and the rest are under _ip, ipalias is redundant
710 builtins_new = dict(__IPYTHON__ = self,
705 builtins_new = dict(__IPYTHON__ = self,
711 ip_set_hook = self.set_hook,
706 ip_set_hook = self.set_hook,
712 jobs = self.jobs,
707 jobs = self.jobs,
713 ipmagic = self.ipmagic,
708 ipmagic = self.ipmagic,
714 ipalias = self.ipalias,
709 ipalias = self.ipalias,
715 ipsystem = self.ipsystem,
710 ipsystem = self.ipsystem,
716 _ip = self.api
711 _ip = self.api
717 )
712 )
718 for biname,bival in builtins_new.items():
713 for biname,bival in builtins_new.items():
719 try:
714 try:
720 # store the orignal value so we can restore it
715 # store the orignal value so we can restore it
721 self.builtins_added[biname] = __builtin__.__dict__[biname]
716 self.builtins_added[biname] = __builtin__.__dict__[biname]
722 except KeyError:
717 except KeyError:
723 # or mark that it wasn't defined, and we'll just delete it at
718 # or mark that it wasn't defined, and we'll just delete it at
724 # cleanup
719 # cleanup
725 self.builtins_added[biname] = Undefined
720 self.builtins_added[biname] = Undefined
726 __builtin__.__dict__[biname] = bival
721 __builtin__.__dict__[biname] = bival
727
722
728 # Keep in the builtins a flag for when IPython is active. We set it
723 # Keep in the builtins a flag for when IPython is active. We set it
729 # with setdefault so that multiple nested IPythons don't clobber one
724 # with setdefault so that multiple nested IPythons don't clobber one
730 # another. Each will increase its value by one upon being activated,
725 # another. Each will increase its value by one upon being activated,
731 # which also gives us a way to determine the nesting level.
726 # which also gives us a way to determine the nesting level.
732 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
727 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
733
728
734 def clean_builtins(self):
729 def clean_builtins(self):
735 """Remove any builtins which might have been added by add_builtins, or
730 """Remove any builtins which might have been added by add_builtins, or
736 restore overwritten ones to their previous values."""
731 restore overwritten ones to their previous values."""
737 for biname,bival in self.builtins_added.items():
732 for biname,bival in self.builtins_added.items():
738 if bival is Undefined:
733 if bival is Undefined:
739 del __builtin__.__dict__[biname]
734 del __builtin__.__dict__[biname]
740 else:
735 else:
741 __builtin__.__dict__[biname] = bival
736 __builtin__.__dict__[biname] = bival
742 self.builtins_added.clear()
737 self.builtins_added.clear()
743
738
744 def set_hook(self,name,hook, priority = 50):
739 def set_hook(self,name,hook, priority = 50):
745 """set_hook(name,hook) -> sets an internal IPython hook.
740 """set_hook(name,hook) -> sets an internal IPython hook.
746
741
747 IPython exposes some of its internal API as user-modifiable hooks. By
742 IPython exposes some of its internal API as user-modifiable hooks. By
748 adding your function to one of these hooks, you can modify IPython's
743 adding your function to one of these hooks, you can modify IPython's
749 behavior to call at runtime your own routines."""
744 behavior to call at runtime your own routines."""
750
745
751 # At some point in the future, this should validate the hook before it
746 # At some point in the future, this should validate the hook before it
752 # accepts it. Probably at least check that the hook takes the number
747 # accepts it. Probably at least check that the hook takes the number
753 # of args it's supposed to.
748 # of args it's supposed to.
754 dp = getattr(self.hooks, name, None)
749 dp = getattr(self.hooks, name, None)
755 if name not in IPython.hooks.__all__:
750 if name not in IPython.hooks.__all__:
756 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
751 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
757 if not dp:
752 if not dp:
758 dp = IPython.hooks.CommandChainDispatcher()
753 dp = IPython.hooks.CommandChainDispatcher()
759
754
760 f = new.instancemethod(hook,self,self.__class__)
755 f = new.instancemethod(hook,self,self.__class__)
761 try:
756 try:
762 dp.add(f,priority)
757 dp.add(f,priority)
763 except AttributeError:
758 except AttributeError:
764 # it was not commandchain, plain old func - replace
759 # it was not commandchain, plain old func - replace
765 dp = f
760 dp = f
766
761
767 setattr(self.hooks,name, dp)
762 setattr(self.hooks,name, dp)
768
763
769
764
770 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
765 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
771
766
767 def set_crash_handler(self,crashHandler):
768 """Set the IPython crash handler.
769
770 This must be a callable with a signature suitable for use as
771 sys.excepthook."""
772
773 # Install the given crash handler as the Python exception hook
774 sys.excepthook = crashHandler
775
776 # The instance will store a pointer to this, so that runtime code
777 # (such as magics) can access it. This is because during the
778 # read-eval loop, it gets temporarily overwritten (to deal with GUI
779 # frameworks).
780 self.sys_excepthook = sys.excepthook
781
782
772 def set_custom_exc(self,exc_tuple,handler):
783 def set_custom_exc(self,exc_tuple,handler):
773 """set_custom_exc(exc_tuple,handler)
784 """set_custom_exc(exc_tuple,handler)
774
785
775 Set a custom exception handler, which will be called if any of the
786 Set a custom exception handler, which will be called if any of the
776 exceptions in exc_tuple occur in the mainloop (specifically, in the
787 exceptions in exc_tuple occur in the mainloop (specifically, in the
777 runcode() method.
788 runcode() method.
778
789
779 Inputs:
790 Inputs:
780
791
781 - exc_tuple: a *tuple* of valid exceptions to call the defined
792 - exc_tuple: a *tuple* of valid exceptions to call the defined
782 handler for. It is very important that you use a tuple, and NOT A
793 handler for. It is very important that you use a tuple, and NOT A
783 LIST here, because of the way Python's except statement works. If
794 LIST here, because of the way Python's except statement works. If
784 you only want to trap a single exception, use a singleton tuple:
795 you only want to trap a single exception, use a singleton tuple:
785
796
786 exc_tuple == (MyCustomException,)
797 exc_tuple == (MyCustomException,)
787
798
788 - handler: this must be defined as a function with the following
799 - handler: this must be defined as a function with the following
789 basic interface: def my_handler(self,etype,value,tb).
800 basic interface: def my_handler(self,etype,value,tb).
790
801
791 This will be made into an instance method (via new.instancemethod)
802 This will be made into an instance method (via new.instancemethod)
792 of IPython itself, and it will be called if any of the exceptions
803 of IPython itself, and it will be called if any of the exceptions
793 listed in the exc_tuple are caught. If the handler is None, an
804 listed in the exc_tuple are caught. If the handler is None, an
794 internal basic one is used, which just prints basic info.
805 internal basic one is used, which just prints basic info.
795
806
796 WARNING: by putting in your own exception handler into IPython's main
807 WARNING: by putting in your own exception handler into IPython's main
797 execution loop, you run a very good chance of nasty crashes. This
808 execution loop, you run a very good chance of nasty crashes. This
798 facility should only be used if you really know what you are doing."""
809 facility should only be used if you really know what you are doing."""
799
810
800 assert type(exc_tuple)==type(()) , \
811 assert type(exc_tuple)==type(()) , \
801 "The custom exceptions must be given AS A TUPLE."
812 "The custom exceptions must be given AS A TUPLE."
802
813
803 def dummy_handler(self,etype,value,tb):
814 def dummy_handler(self,etype,value,tb):
804 print '*** Simple custom exception handler ***'
815 print '*** Simple custom exception handler ***'
805 print 'Exception type :',etype
816 print 'Exception type :',etype
806 print 'Exception value:',value
817 print 'Exception value:',value
807 print 'Traceback :',tb
818 print 'Traceback :',tb
808 print 'Source code :','\n'.join(self.buffer)
819 print 'Source code :','\n'.join(self.buffer)
809
820
810 if handler is None: handler = dummy_handler
821 if handler is None: handler = dummy_handler
811
822
812 self.CustomTB = new.instancemethod(handler,self,self.__class__)
823 self.CustomTB = new.instancemethod(handler,self,self.__class__)
813 self.custom_exceptions = exc_tuple
824 self.custom_exceptions = exc_tuple
814
825
815 def set_custom_completer(self,completer,pos=0):
826 def set_custom_completer(self,completer,pos=0):
816 """set_custom_completer(completer,pos=0)
827 """set_custom_completer(completer,pos=0)
817
828
818 Adds a new custom completer function.
829 Adds a new custom completer function.
819
830
820 The position argument (defaults to 0) is the index in the completers
831 The position argument (defaults to 0) is the index in the completers
821 list where you want the completer to be inserted."""
832 list where you want the completer to be inserted."""
822
833
823 newcomp = new.instancemethod(completer,self.Completer,
834 newcomp = new.instancemethod(completer,self.Completer,
824 self.Completer.__class__)
835 self.Completer.__class__)
825 self.Completer.matchers.insert(pos,newcomp)
836 self.Completer.matchers.insert(pos,newcomp)
826
837
827 def _get_call_pdb(self):
838 def _get_call_pdb(self):
828 return self._call_pdb
839 return self._call_pdb
829
840
830 def _set_call_pdb(self,val):
841 def _set_call_pdb(self,val):
831
842
832 if val not in (0,1,False,True):
843 if val not in (0,1,False,True):
833 raise ValueError,'new call_pdb value must be boolean'
844 raise ValueError,'new call_pdb value must be boolean'
834
845
835 # store value in instance
846 # store value in instance
836 self._call_pdb = val
847 self._call_pdb = val
837
848
838 # notify the actual exception handlers
849 # notify the actual exception handlers
839 self.InteractiveTB.call_pdb = val
850 self.InteractiveTB.call_pdb = val
840 if self.isthreaded:
851 if self.isthreaded:
841 try:
852 try:
842 self.sys_excepthook.call_pdb = val
853 self.sys_excepthook.call_pdb = val
843 except:
854 except:
844 warn('Failed to activate pdb for threaded exception handler')
855 warn('Failed to activate pdb for threaded exception handler')
845
856
846 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
857 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
847 'Control auto-activation of pdb at exceptions')
858 'Control auto-activation of pdb at exceptions')
848
859
849
860
850 # These special functions get installed in the builtin namespace, to
861 # These special functions get installed in the builtin namespace, to
851 # provide programmatic (pure python) access to magics, aliases and system
862 # provide programmatic (pure python) access to magics, aliases and system
852 # calls. This is important for logging, user scripting, and more.
863 # calls. This is important for logging, user scripting, and more.
853
864
854 # We are basically exposing, via normal python functions, the three
865 # We are basically exposing, via normal python functions, the three
855 # mechanisms in which ipython offers special call modes (magics for
866 # mechanisms in which ipython offers special call modes (magics for
856 # internal control, aliases for direct system access via pre-selected
867 # internal control, aliases for direct system access via pre-selected
857 # names, and !cmd for calling arbitrary system commands).
868 # names, and !cmd for calling arbitrary system commands).
858
869
859 def ipmagic(self,arg_s):
870 def ipmagic(self,arg_s):
860 """Call a magic function by name.
871 """Call a magic function by name.
861
872
862 Input: a string containing the name of the magic function to call and any
873 Input: a string containing the name of the magic function to call and any
863 additional arguments to be passed to the magic.
874 additional arguments to be passed to the magic.
864
875
865 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
876 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
866 prompt:
877 prompt:
867
878
868 In[1]: %name -opt foo bar
879 In[1]: %name -opt foo bar
869
880
870 To call a magic without arguments, simply use ipmagic('name').
881 To call a magic without arguments, simply use ipmagic('name').
871
882
872 This provides a proper Python function to call IPython's magics in any
883 This provides a proper Python function to call IPython's magics in any
873 valid Python code you can type at the interpreter, including loops and
884 valid Python code you can type at the interpreter, including loops and
874 compound statements. It is added by IPython to the Python builtin
885 compound statements. It is added by IPython to the Python builtin
875 namespace upon initialization."""
886 namespace upon initialization."""
876
887
877 args = arg_s.split(' ',1)
888 args = arg_s.split(' ',1)
878 magic_name = args[0]
889 magic_name = args[0]
879 magic_name = magic_name.lstrip(self.ESC_MAGIC)
890 magic_name = magic_name.lstrip(self.ESC_MAGIC)
880
891
881 try:
892 try:
882 magic_args = args[1]
893 magic_args = args[1]
883 except IndexError:
894 except IndexError:
884 magic_args = ''
895 magic_args = ''
885 fn = getattr(self,'magic_'+magic_name,None)
896 fn = getattr(self,'magic_'+magic_name,None)
886 if fn is None:
897 if fn is None:
887 error("Magic function `%s` not found." % magic_name)
898 error("Magic function `%s` not found." % magic_name)
888 else:
899 else:
889 magic_args = self.var_expand(magic_args)
900 magic_args = self.var_expand(magic_args)
890 return fn(magic_args)
901 return fn(magic_args)
891
902
892 def ipalias(self,arg_s):
903 def ipalias(self,arg_s):
893 """Call an alias by name.
904 """Call an alias by name.
894
905
895 Input: a string containing the name of the alias to call and any
906 Input: a string containing the name of the alias to call and any
896 additional arguments to be passed to the magic.
907 additional arguments to be passed to the magic.
897
908
898 ipalias('name -opt foo bar') is equivalent to typing at the ipython
909 ipalias('name -opt foo bar') is equivalent to typing at the ipython
899 prompt:
910 prompt:
900
911
901 In[1]: name -opt foo bar
912 In[1]: name -opt foo bar
902
913
903 To call an alias without arguments, simply use ipalias('name').
914 To call an alias without arguments, simply use ipalias('name').
904
915
905 This provides a proper Python function to call IPython's aliases in any
916 This provides a proper Python function to call IPython's aliases in any
906 valid Python code you can type at the interpreter, including loops and
917 valid Python code you can type at the interpreter, including loops and
907 compound statements. It is added by IPython to the Python builtin
918 compound statements. It is added by IPython to the Python builtin
908 namespace upon initialization."""
919 namespace upon initialization."""
909
920
910 args = arg_s.split(' ',1)
921 args = arg_s.split(' ',1)
911 alias_name = args[0]
922 alias_name = args[0]
912 try:
923 try:
913 alias_args = args[1]
924 alias_args = args[1]
914 except IndexError:
925 except IndexError:
915 alias_args = ''
926 alias_args = ''
916 if alias_name in self.alias_table:
927 if alias_name in self.alias_table:
917 self.call_alias(alias_name,alias_args)
928 self.call_alias(alias_name,alias_args)
918 else:
929 else:
919 error("Alias `%s` not found." % alias_name)
930 error("Alias `%s` not found." % alias_name)
920
931
921 def ipsystem(self,arg_s):
932 def ipsystem(self,arg_s):
922 """Make a system call, using IPython."""
933 """Make a system call, using IPython."""
923
934
924 self.system(arg_s)
935 self.system(arg_s)
925
936
926 def complete(self,text):
937 def complete(self,text):
927 """Return a sorted list of all possible completions on text.
938 """Return a sorted list of all possible completions on text.
928
939
929 Inputs:
940 Inputs:
930
941
931 - text: a string of text to be completed on.
942 - text: a string of text to be completed on.
932
943
933 This is a wrapper around the completion mechanism, similar to what
944 This is a wrapper around the completion mechanism, similar to what
934 readline does at the command line when the TAB key is hit. By
945 readline does at the command line when the TAB key is hit. By
935 exposing it as a method, it can be used by other non-readline
946 exposing it as a method, it can be used by other non-readline
936 environments (such as GUIs) for text completion.
947 environments (such as GUIs) for text completion.
937
948
938 Simple usage example:
949 Simple usage example:
939
950
940 In [1]: x = 'hello'
951 In [1]: x = 'hello'
941
952
942 In [2]: __IP.complete('x.l')
953 In [2]: __IP.complete('x.l')
943 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
954 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
944
955
945 complete = self.Completer.complete
956 complete = self.Completer.complete
946 state = 0
957 state = 0
947 # use a dict so we get unique keys, since ipyhton's multiple
958 # use a dict so we get unique keys, since ipyhton's multiple
948 # completers can return duplicates.
959 # completers can return duplicates.
949 comps = {}
960 comps = {}
950 while True:
961 while True:
951 newcomp = complete(text,state)
962 newcomp = complete(text,state)
952 if newcomp is None:
963 if newcomp is None:
953 break
964 break
954 comps[newcomp] = 1
965 comps[newcomp] = 1
955 state += 1
966 state += 1
956 outcomps = comps.keys()
967 outcomps = comps.keys()
957 outcomps.sort()
968 outcomps.sort()
958 return outcomps
969 return outcomps
959
970
960 def set_completer_frame(self, frame=None):
971 def set_completer_frame(self, frame=None):
961 if frame:
972 if frame:
962 self.Completer.namespace = frame.f_locals
973 self.Completer.namespace = frame.f_locals
963 self.Completer.global_namespace = frame.f_globals
974 self.Completer.global_namespace = frame.f_globals
964 else:
975 else:
965 self.Completer.namespace = self.user_ns
976 self.Completer.namespace = self.user_ns
966 self.Completer.global_namespace = self.user_global_ns
977 self.Completer.global_namespace = self.user_global_ns
967
978
968 def init_auto_alias(self):
979 def init_auto_alias(self):
969 """Define some aliases automatically.
980 """Define some aliases automatically.
970
981
971 These are ALL parameter-less aliases"""
982 These are ALL parameter-less aliases"""
972
983
973 for alias,cmd in self.auto_alias:
984 for alias,cmd in self.auto_alias:
974 self.alias_table[alias] = (0,cmd)
985 self.alias_table[alias] = (0,cmd)
975
986
976 def alias_table_validate(self,verbose=0):
987 def alias_table_validate(self,verbose=0):
977 """Update information about the alias table.
988 """Update information about the alias table.
978
989
979 In particular, make sure no Python keywords/builtins are in it."""
990 In particular, make sure no Python keywords/builtins are in it."""
980
991
981 no_alias = self.no_alias
992 no_alias = self.no_alias
982 for k in self.alias_table.keys():
993 for k in self.alias_table.keys():
983 if k in no_alias:
994 if k in no_alias:
984 del self.alias_table[k]
995 del self.alias_table[k]
985 if verbose:
996 if verbose:
986 print ("Deleting alias <%s>, it's a Python "
997 print ("Deleting alias <%s>, it's a Python "
987 "keyword or builtin." % k)
998 "keyword or builtin." % k)
988
999
989 def set_autoindent(self,value=None):
1000 def set_autoindent(self,value=None):
990 """Set the autoindent flag, checking for readline support.
1001 """Set the autoindent flag, checking for readline support.
991
1002
992 If called with no arguments, it acts as a toggle."""
1003 If called with no arguments, it acts as a toggle."""
993
1004
994 if not self.has_readline:
1005 if not self.has_readline:
995 if os.name == 'posix':
1006 if os.name == 'posix':
996 warn("The auto-indent feature requires the readline library")
1007 warn("The auto-indent feature requires the readline library")
997 self.autoindent = 0
1008 self.autoindent = 0
998 return
1009 return
999 if value is None:
1010 if value is None:
1000 self.autoindent = not self.autoindent
1011 self.autoindent = not self.autoindent
1001 else:
1012 else:
1002 self.autoindent = value
1013 self.autoindent = value
1003
1014
1004 def rc_set_toggle(self,rc_field,value=None):
1015 def rc_set_toggle(self,rc_field,value=None):
1005 """Set or toggle a field in IPython's rc config. structure.
1016 """Set or toggle a field in IPython's rc config. structure.
1006
1017
1007 If called with no arguments, it acts as a toggle.
1018 If called with no arguments, it acts as a toggle.
1008
1019
1009 If called with a non-existent field, the resulting AttributeError
1020 If called with a non-existent field, the resulting AttributeError
1010 exception will propagate out."""
1021 exception will propagate out."""
1011
1022
1012 rc_val = getattr(self.rc,rc_field)
1023 rc_val = getattr(self.rc,rc_field)
1013 if value is None:
1024 if value is None:
1014 value = not rc_val
1025 value = not rc_val
1015 setattr(self.rc,rc_field,value)
1026 setattr(self.rc,rc_field,value)
1016
1027
1017 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1028 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1018 """Install the user configuration directory.
1029 """Install the user configuration directory.
1019
1030
1020 Can be called when running for the first time or to upgrade the user's
1031 Can be called when running for the first time or to upgrade the user's
1021 .ipython/ directory with the mode parameter. Valid modes are 'install'
1032 .ipython/ directory with the mode parameter. Valid modes are 'install'
1022 and 'upgrade'."""
1033 and 'upgrade'."""
1023
1034
1024 def wait():
1035 def wait():
1025 try:
1036 try:
1026 raw_input("Please press <RETURN> to start IPython.")
1037 raw_input("Please press <RETURN> to start IPython.")
1027 except EOFError:
1038 except EOFError:
1028 print >> Term.cout
1039 print >> Term.cout
1029 print '*'*70
1040 print '*'*70
1030
1041
1031 cwd = os.getcwd() # remember where we started
1042 cwd = os.getcwd() # remember where we started
1032 glb = glob.glob
1043 glb = glob.glob
1033 print '*'*70
1044 print '*'*70
1034 if mode == 'install':
1045 if mode == 'install':
1035 print \
1046 print \
1036 """Welcome to IPython. I will try to create a personal configuration directory
1047 """Welcome to IPython. I will try to create a personal configuration directory
1037 where you can customize many aspects of IPython's functionality in:\n"""
1048 where you can customize many aspects of IPython's functionality in:\n"""
1038 else:
1049 else:
1039 print 'I am going to upgrade your configuration in:'
1050 print 'I am going to upgrade your configuration in:'
1040
1051
1041 print ipythondir
1052 print ipythondir
1042
1053
1043 rcdirend = os.path.join('IPython','UserConfig')
1054 rcdirend = os.path.join('IPython','UserConfig')
1044 cfg = lambda d: os.path.join(d,rcdirend)
1055 cfg = lambda d: os.path.join(d,rcdirend)
1045 try:
1056 try:
1046 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1057 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1047 except IOError:
1058 except IOError:
1048 warning = """
1059 warning = """
1049 Installation error. IPython's directory was not found.
1060 Installation error. IPython's directory was not found.
1050
1061
1051 Check the following:
1062 Check the following:
1052
1063
1053 The ipython/IPython directory should be in a directory belonging to your
1064 The ipython/IPython directory should be in a directory belonging to your
1054 PYTHONPATH environment variable (that is, it should be in a directory
1065 PYTHONPATH environment variable (that is, it should be in a directory
1055 belonging to sys.path). You can copy it explicitly there or just link to it.
1066 belonging to sys.path). You can copy it explicitly there or just link to it.
1056
1067
1057 IPython will proceed with builtin defaults.
1068 IPython will proceed with builtin defaults.
1058 """
1069 """
1059 warn(warning)
1070 warn(warning)
1060 wait()
1071 wait()
1061 return
1072 return
1062
1073
1063 if mode == 'install':
1074 if mode == 'install':
1064 try:
1075 try:
1065 shutil.copytree(rcdir,ipythondir)
1076 shutil.copytree(rcdir,ipythondir)
1066 os.chdir(ipythondir)
1077 os.chdir(ipythondir)
1067 rc_files = glb("ipythonrc*")
1078 rc_files = glb("ipythonrc*")
1068 for rc_file in rc_files:
1079 for rc_file in rc_files:
1069 os.rename(rc_file,rc_file+rc_suffix)
1080 os.rename(rc_file,rc_file+rc_suffix)
1070 except:
1081 except:
1071 warning = """
1082 warning = """
1072
1083
1073 There was a problem with the installation:
1084 There was a problem with the installation:
1074 %s
1085 %s
1075 Try to correct it or contact the developers if you think it's a bug.
1086 Try to correct it or contact the developers if you think it's a bug.
1076 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1087 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1077 warn(warning)
1088 warn(warning)
1078 wait()
1089 wait()
1079 return
1090 return
1080
1091
1081 elif mode == 'upgrade':
1092 elif mode == 'upgrade':
1082 try:
1093 try:
1083 os.chdir(ipythondir)
1094 os.chdir(ipythondir)
1084 except:
1095 except:
1085 print """
1096 print """
1086 Can not upgrade: changing to directory %s failed. Details:
1097 Can not upgrade: changing to directory %s failed. Details:
1087 %s
1098 %s
1088 """ % (ipythondir,sys.exc_info()[1])
1099 """ % (ipythondir,sys.exc_info()[1])
1089 wait()
1100 wait()
1090 return
1101 return
1091 else:
1102 else:
1092 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1103 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1093 for new_full_path in sources:
1104 for new_full_path in sources:
1094 new_filename = os.path.basename(new_full_path)
1105 new_filename = os.path.basename(new_full_path)
1095 if new_filename.startswith('ipythonrc'):
1106 if new_filename.startswith('ipythonrc'):
1096 new_filename = new_filename + rc_suffix
1107 new_filename = new_filename + rc_suffix
1097 # The config directory should only contain files, skip any
1108 # The config directory should only contain files, skip any
1098 # directories which may be there (like CVS)
1109 # directories which may be there (like CVS)
1099 if os.path.isdir(new_full_path):
1110 if os.path.isdir(new_full_path):
1100 continue
1111 continue
1101 if os.path.exists(new_filename):
1112 if os.path.exists(new_filename):
1102 old_file = new_filename+'.old'
1113 old_file = new_filename+'.old'
1103 if os.path.exists(old_file):
1114 if os.path.exists(old_file):
1104 os.remove(old_file)
1115 os.remove(old_file)
1105 os.rename(new_filename,old_file)
1116 os.rename(new_filename,old_file)
1106 shutil.copy(new_full_path,new_filename)
1117 shutil.copy(new_full_path,new_filename)
1107 else:
1118 else:
1108 raise ValueError,'unrecognized mode for install:',`mode`
1119 raise ValueError,'unrecognized mode for install:',`mode`
1109
1120
1110 # Fix line-endings to those native to each platform in the config
1121 # Fix line-endings to those native to each platform in the config
1111 # directory.
1122 # directory.
1112 try:
1123 try:
1113 os.chdir(ipythondir)
1124 os.chdir(ipythondir)
1114 except:
1125 except:
1115 print """
1126 print """
1116 Problem: changing to directory %s failed.
1127 Problem: changing to directory %s failed.
1117 Details:
1128 Details:
1118 %s
1129 %s
1119
1130
1120 Some configuration files may have incorrect line endings. This should not
1131 Some configuration files may have incorrect line endings. This should not
1121 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1132 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1122 wait()
1133 wait()
1123 else:
1134 else:
1124 for fname in glb('ipythonrc*'):
1135 for fname in glb('ipythonrc*'):
1125 try:
1136 try:
1126 native_line_ends(fname,backup=0)
1137 native_line_ends(fname,backup=0)
1127 except IOError:
1138 except IOError:
1128 pass
1139 pass
1129
1140
1130 if mode == 'install':
1141 if mode == 'install':
1131 print """
1142 print """
1132 Successful installation!
1143 Successful installation!
1133
1144
1134 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1145 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1135 IPython manual (there are both HTML and PDF versions supplied with the
1146 IPython manual (there are both HTML and PDF versions supplied with the
1136 distribution) to make sure that your system environment is properly configured
1147 distribution) to make sure that your system environment is properly configured
1137 to take advantage of IPython's features.
1148 to take advantage of IPython's features.
1138
1149
1139 Important note: the configuration system has changed! The old system is
1150 Important note: the configuration system has changed! The old system is
1140 still in place, but its setting may be partly overridden by the settings in
1151 still in place, but its setting may be partly overridden by the settings in
1141 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1152 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1142 if some of the new settings bother you.
1153 if some of the new settings bother you.
1143
1154
1144 """
1155 """
1145 else:
1156 else:
1146 print """
1157 print """
1147 Successful upgrade!
1158 Successful upgrade!
1148
1159
1149 All files in your directory:
1160 All files in your directory:
1150 %(ipythondir)s
1161 %(ipythondir)s
1151 which would have been overwritten by the upgrade were backed up with a .old
1162 which would have been overwritten by the upgrade were backed up with a .old
1152 extension. If you had made particular customizations in those files you may
1163 extension. If you had made particular customizations in those files you may
1153 want to merge them back into the new files.""" % locals()
1164 want to merge them back into the new files.""" % locals()
1154 wait()
1165 wait()
1155 os.chdir(cwd)
1166 os.chdir(cwd)
1156 # end user_setup()
1167 # end user_setup()
1157
1168
1158 def atexit_operations(self):
1169 def atexit_operations(self):
1159 """This will be executed at the time of exit.
1170 """This will be executed at the time of exit.
1160
1171
1161 Saving of persistent data should be performed here. """
1172 Saving of persistent data should be performed here. """
1162
1173
1163 #print '*** IPython exit cleanup ***' # dbg
1174 #print '*** IPython exit cleanup ***' # dbg
1164 # input history
1175 # input history
1165 self.savehist()
1176 self.savehist()
1166
1177
1167 # Cleanup all tempfiles left around
1178 # Cleanup all tempfiles left around
1168 for tfile in self.tempfiles:
1179 for tfile in self.tempfiles:
1169 try:
1180 try:
1170 os.unlink(tfile)
1181 os.unlink(tfile)
1171 except OSError:
1182 except OSError:
1172 pass
1183 pass
1173
1184
1174 # save the "persistent data" catch-all dictionary
1185 # save the "persistent data" catch-all dictionary
1175 self.hooks.shutdown_hook()
1186 self.hooks.shutdown_hook()
1176
1187
1177 def savehist(self):
1188 def savehist(self):
1178 """Save input history to a file (via readline library)."""
1189 """Save input history to a file (via readline library)."""
1179 try:
1190 try:
1180 self.readline.write_history_file(self.histfile)
1191 self.readline.write_history_file(self.histfile)
1181 except:
1192 except:
1182 print 'Unable to save IPython command history to file: ' + \
1193 print 'Unable to save IPython command history to file: ' + \
1183 `self.histfile`
1194 `self.histfile`
1184
1195
1185 def pre_readline(self):
1196 def pre_readline(self):
1186 """readline hook to be used at the start of each line.
1197 """readline hook to be used at the start of each line.
1187
1198
1188 Currently it handles auto-indent only."""
1199 Currently it handles auto-indent only."""
1189
1200
1190 #debugx('self.indent_current_nsp','pre_readline:')
1201 #debugx('self.indent_current_nsp','pre_readline:')
1191 self.readline.insert_text(self.indent_current_str())
1202 self.readline.insert_text(self.indent_current_str())
1192
1203
1193 def init_readline(self):
1204 def init_readline(self):
1194 """Command history completion/saving/reloading."""
1205 """Command history completion/saving/reloading."""
1195
1206
1196 import IPython.rlineimpl as readline
1207 import IPython.rlineimpl as readline
1197 if not readline.have_readline:
1208 if not readline.have_readline:
1198 self.has_readline = 0
1209 self.has_readline = 0
1199 self.readline = None
1210 self.readline = None
1200 # no point in bugging windows users with this every time:
1211 # no point in bugging windows users with this every time:
1201 warn('Readline services not available on this platform.')
1212 warn('Readline services not available on this platform.')
1202 else:
1213 else:
1203 sys.modules['readline'] = readline
1214 sys.modules['readline'] = readline
1204 import atexit
1215 import atexit
1205 from IPython.completer import IPCompleter
1216 from IPython.completer import IPCompleter
1206 self.Completer = IPCompleter(self,
1217 self.Completer = IPCompleter(self,
1207 self.user_ns,
1218 self.user_ns,
1208 self.user_global_ns,
1219 self.user_global_ns,
1209 self.rc.readline_omit__names,
1220 self.rc.readline_omit__names,
1210 self.alias_table)
1221 self.alias_table)
1211
1222
1212 # Platform-specific configuration
1223 # Platform-specific configuration
1213 if os.name == 'nt':
1224 if os.name == 'nt':
1214 self.readline_startup_hook = readline.set_pre_input_hook
1225 self.readline_startup_hook = readline.set_pre_input_hook
1215 else:
1226 else:
1216 self.readline_startup_hook = readline.set_startup_hook
1227 self.readline_startup_hook = readline.set_startup_hook
1217
1228
1218 # Load user's initrc file (readline config)
1229 # Load user's initrc file (readline config)
1219 inputrc_name = os.environ.get('INPUTRC')
1230 inputrc_name = os.environ.get('INPUTRC')
1220 if inputrc_name is None:
1231 if inputrc_name is None:
1221 home_dir = get_home_dir()
1232 home_dir = get_home_dir()
1222 if home_dir is not None:
1233 if home_dir is not None:
1223 inputrc_name = os.path.join(home_dir,'.inputrc')
1234 inputrc_name = os.path.join(home_dir,'.inputrc')
1224 if os.path.isfile(inputrc_name):
1235 if os.path.isfile(inputrc_name):
1225 try:
1236 try:
1226 readline.read_init_file(inputrc_name)
1237 readline.read_init_file(inputrc_name)
1227 except:
1238 except:
1228 warn('Problems reading readline initialization file <%s>'
1239 warn('Problems reading readline initialization file <%s>'
1229 % inputrc_name)
1240 % inputrc_name)
1230
1241
1231 self.has_readline = 1
1242 self.has_readline = 1
1232 self.readline = readline
1243 self.readline = readline
1233 # save this in sys so embedded copies can restore it properly
1244 # save this in sys so embedded copies can restore it properly
1234 sys.ipcompleter = self.Completer.complete
1245 sys.ipcompleter = self.Completer.complete
1235 readline.set_completer(self.Completer.complete)
1246 readline.set_completer(self.Completer.complete)
1236
1247
1237 # Configure readline according to user's prefs
1248 # Configure readline according to user's prefs
1238 for rlcommand in self.rc.readline_parse_and_bind:
1249 for rlcommand in self.rc.readline_parse_and_bind:
1239 readline.parse_and_bind(rlcommand)
1250 readline.parse_and_bind(rlcommand)
1240
1251
1241 # remove some chars from the delimiters list
1252 # remove some chars from the delimiters list
1242 delims = readline.get_completer_delims()
1253 delims = readline.get_completer_delims()
1243 delims = delims.translate(string._idmap,
1254 delims = delims.translate(string._idmap,
1244 self.rc.readline_remove_delims)
1255 self.rc.readline_remove_delims)
1245 readline.set_completer_delims(delims)
1256 readline.set_completer_delims(delims)
1246 # otherwise we end up with a monster history after a while:
1257 # otherwise we end up with a monster history after a while:
1247 readline.set_history_length(1000)
1258 readline.set_history_length(1000)
1248 try:
1259 try:
1249 #print '*** Reading readline history' # dbg
1260 #print '*** Reading readline history' # dbg
1250 readline.read_history_file(self.histfile)
1261 readline.read_history_file(self.histfile)
1251 except IOError:
1262 except IOError:
1252 pass # It doesn't exist yet.
1263 pass # It doesn't exist yet.
1253
1264
1254 atexit.register(self.atexit_operations)
1265 atexit.register(self.atexit_operations)
1255 del atexit
1266 del atexit
1256
1267
1257 # Configure auto-indent for all platforms
1268 # Configure auto-indent for all platforms
1258 self.set_autoindent(self.rc.autoindent)
1269 self.set_autoindent(self.rc.autoindent)
1259
1270
1260 def ask_yes_no(self,prompt,default=True):
1271 def ask_yes_no(self,prompt,default=True):
1261 if self.rc.quiet:
1272 if self.rc.quiet:
1262 return True
1273 return True
1263 return ask_yes_no(prompt,default)
1274 return ask_yes_no(prompt,default)
1264
1275
1265 def _should_recompile(self,e):
1276 def _should_recompile(self,e):
1266 """Utility routine for edit_syntax_error"""
1277 """Utility routine for edit_syntax_error"""
1267
1278
1268 if e.filename in ('<ipython console>','<input>','<string>',
1279 if e.filename in ('<ipython console>','<input>','<string>',
1269 '<console>','<BackgroundJob compilation>',
1280 '<console>','<BackgroundJob compilation>',
1270 None):
1281 None):
1271
1282
1272 return False
1283 return False
1273 try:
1284 try:
1274 if (self.rc.autoedit_syntax and
1285 if (self.rc.autoedit_syntax and
1275 not self.ask_yes_no('Return to editor to correct syntax error? '
1286 not self.ask_yes_no('Return to editor to correct syntax error? '
1276 '[Y/n] ','y')):
1287 '[Y/n] ','y')):
1277 return False
1288 return False
1278 except EOFError:
1289 except EOFError:
1279 return False
1290 return False
1280
1291
1281 def int0(x):
1292 def int0(x):
1282 try:
1293 try:
1283 return int(x)
1294 return int(x)
1284 except TypeError:
1295 except TypeError:
1285 return 0
1296 return 0
1286 # always pass integer line and offset values to editor hook
1297 # always pass integer line and offset values to editor hook
1287 self.hooks.fix_error_editor(e.filename,
1298 self.hooks.fix_error_editor(e.filename,
1288 int0(e.lineno),int0(e.offset),e.msg)
1299 int0(e.lineno),int0(e.offset),e.msg)
1289 return True
1300 return True
1290
1301
1291 def edit_syntax_error(self):
1302 def edit_syntax_error(self):
1292 """The bottom half of the syntax error handler called in the main loop.
1303 """The bottom half of the syntax error handler called in the main loop.
1293
1304
1294 Loop until syntax error is fixed or user cancels.
1305 Loop until syntax error is fixed or user cancels.
1295 """
1306 """
1296
1307
1297 while self.SyntaxTB.last_syntax_error:
1308 while self.SyntaxTB.last_syntax_error:
1298 # copy and clear last_syntax_error
1309 # copy and clear last_syntax_error
1299 err = self.SyntaxTB.clear_err_state()
1310 err = self.SyntaxTB.clear_err_state()
1300 if not self._should_recompile(err):
1311 if not self._should_recompile(err):
1301 return
1312 return
1302 try:
1313 try:
1303 # may set last_syntax_error again if a SyntaxError is raised
1314 # may set last_syntax_error again if a SyntaxError is raised
1304 self.safe_execfile(err.filename,self.user_ns)
1315 self.safe_execfile(err.filename,self.user_ns)
1305 except:
1316 except:
1306 self.showtraceback()
1317 self.showtraceback()
1307 else:
1318 else:
1308 try:
1319 try:
1309 f = file(err.filename)
1320 f = file(err.filename)
1310 try:
1321 try:
1311 sys.displayhook(f.read())
1322 sys.displayhook(f.read())
1312 finally:
1323 finally:
1313 f.close()
1324 f.close()
1314 except:
1325 except:
1315 self.showtraceback()
1326 self.showtraceback()
1316
1327
1317 def showsyntaxerror(self, filename=None):
1328 def showsyntaxerror(self, filename=None):
1318 """Display the syntax error that just occurred.
1329 """Display the syntax error that just occurred.
1319
1330
1320 This doesn't display a stack trace because there isn't one.
1331 This doesn't display a stack trace because there isn't one.
1321
1332
1322 If a filename is given, it is stuffed in the exception instead
1333 If a filename is given, it is stuffed in the exception instead
1323 of what was there before (because Python's parser always uses
1334 of what was there before (because Python's parser always uses
1324 "<string>" when reading from a string).
1335 "<string>" when reading from a string).
1325 """
1336 """
1326 etype, value, last_traceback = sys.exc_info()
1337 etype, value, last_traceback = sys.exc_info()
1327
1338
1328 # See note about these variables in showtraceback() below
1339 # See note about these variables in showtraceback() below
1329 sys.last_type = etype
1340 sys.last_type = etype
1330 sys.last_value = value
1341 sys.last_value = value
1331 sys.last_traceback = last_traceback
1342 sys.last_traceback = last_traceback
1332
1343
1333 if filename and etype is SyntaxError:
1344 if filename and etype is SyntaxError:
1334 # Work hard to stuff the correct filename in the exception
1345 # Work hard to stuff the correct filename in the exception
1335 try:
1346 try:
1336 msg, (dummy_filename, lineno, offset, line) = value
1347 msg, (dummy_filename, lineno, offset, line) = value
1337 except:
1348 except:
1338 # Not the format we expect; leave it alone
1349 # Not the format we expect; leave it alone
1339 pass
1350 pass
1340 else:
1351 else:
1341 # Stuff in the right filename
1352 # Stuff in the right filename
1342 try:
1353 try:
1343 # Assume SyntaxError is a class exception
1354 # Assume SyntaxError is a class exception
1344 value = SyntaxError(msg, (filename, lineno, offset, line))
1355 value = SyntaxError(msg, (filename, lineno, offset, line))
1345 except:
1356 except:
1346 # If that failed, assume SyntaxError is a string
1357 # If that failed, assume SyntaxError is a string
1347 value = msg, (filename, lineno, offset, line)
1358 value = msg, (filename, lineno, offset, line)
1348 self.SyntaxTB(etype,value,[])
1359 self.SyntaxTB(etype,value,[])
1349
1360
1350 def debugger(self):
1361 def debugger(self):
1351 """Call the pdb debugger."""
1362 """Call the pdb debugger."""
1352
1363
1353 if not self.rc.pdb:
1364 if not self.rc.pdb:
1354 return
1365 return
1355 pdb.pm()
1366 pdb.pm()
1356
1367
1357 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1368 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1358 """Display the exception that just occurred.
1369 """Display the exception that just occurred.
1359
1370
1360 If nothing is known about the exception, this is the method which
1371 If nothing is known about the exception, this is the method which
1361 should be used throughout the code for presenting user tracebacks,
1372 should be used throughout the code for presenting user tracebacks,
1362 rather than directly invoking the InteractiveTB object.
1373 rather than directly invoking the InteractiveTB object.
1363
1374
1364 A specific showsyntaxerror() also exists, but this method can take
1375 A specific showsyntaxerror() also exists, but this method can take
1365 care of calling it if needed, so unless you are explicitly catching a
1376 care of calling it if needed, so unless you are explicitly catching a
1366 SyntaxError exception, don't try to analyze the stack manually and
1377 SyntaxError exception, don't try to analyze the stack manually and
1367 simply call this method."""
1378 simply call this method."""
1368
1379
1369 # Though this won't be called by syntax errors in the input line,
1380 # Though this won't be called by syntax errors in the input line,
1370 # there may be SyntaxError cases whith imported code.
1381 # there may be SyntaxError cases whith imported code.
1371 if exc_tuple is None:
1382 if exc_tuple is None:
1372 etype, value, tb = sys.exc_info()
1383 etype, value, tb = sys.exc_info()
1373 else:
1384 else:
1374 etype, value, tb = exc_tuple
1385 etype, value, tb = exc_tuple
1375 if etype is SyntaxError:
1386 if etype is SyntaxError:
1376 self.showsyntaxerror(filename)
1387 self.showsyntaxerror(filename)
1377 else:
1388 else:
1378 # WARNING: these variables are somewhat deprecated and not
1389 # WARNING: these variables are somewhat deprecated and not
1379 # necessarily safe to use in a threaded environment, but tools
1390 # necessarily safe to use in a threaded environment, but tools
1380 # like pdb depend on their existence, so let's set them. If we
1391 # like pdb depend on their existence, so let's set them. If we
1381 # find problems in the field, we'll need to revisit their use.
1392 # find problems in the field, we'll need to revisit their use.
1382 sys.last_type = etype
1393 sys.last_type = etype
1383 sys.last_value = value
1394 sys.last_value = value
1384 sys.last_traceback = tb
1395 sys.last_traceback = tb
1385
1396
1386 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1397 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1387 if self.InteractiveTB.call_pdb and self.has_readline:
1398 if self.InteractiveTB.call_pdb and self.has_readline:
1388 # pdb mucks up readline, fix it back
1399 # pdb mucks up readline, fix it back
1389 self.readline.set_completer(self.Completer.complete)
1400 self.readline.set_completer(self.Completer.complete)
1390
1401
1391 def mainloop(self,banner=None):
1402 def mainloop(self,banner=None):
1392 """Creates the local namespace and starts the mainloop.
1403 """Creates the local namespace and starts the mainloop.
1393
1404
1394 If an optional banner argument is given, it will override the
1405 If an optional banner argument is given, it will override the
1395 internally created default banner."""
1406 internally created default banner."""
1396
1407
1397 if self.rc.c: # Emulate Python's -c option
1408 if self.rc.c: # Emulate Python's -c option
1398 self.exec_init_cmd()
1409 self.exec_init_cmd()
1399 if banner is None:
1410 if banner is None:
1400 if not self.rc.banner:
1411 if not self.rc.banner:
1401 banner = ''
1412 banner = ''
1402 # banner is string? Use it directly!
1413 # banner is string? Use it directly!
1403 elif isinstance(self.rc.banner,basestring):
1414 elif isinstance(self.rc.banner,basestring):
1404 banner = self.rc.banner
1415 banner = self.rc.banner
1405 else:
1416 else:
1406 banner = self.BANNER+self.banner2
1417 banner = self.BANNER+self.banner2
1407
1418
1408 self.interact(banner)
1419 self.interact(banner)
1409
1420
1410 def exec_init_cmd(self):
1421 def exec_init_cmd(self):
1411 """Execute a command given at the command line.
1422 """Execute a command given at the command line.
1412
1423
1413 This emulates Python's -c option."""
1424 This emulates Python's -c option."""
1414
1425
1415 #sys.argv = ['-c']
1426 #sys.argv = ['-c']
1416 self.push(self.rc.c)
1427 self.push(self.rc.c)
1417
1428
1418 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1429 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1419 """Embeds IPython into a running python program.
1430 """Embeds IPython into a running python program.
1420
1431
1421 Input:
1432 Input:
1422
1433
1423 - header: An optional header message can be specified.
1434 - header: An optional header message can be specified.
1424
1435
1425 - local_ns, global_ns: working namespaces. If given as None, the
1436 - local_ns, global_ns: working namespaces. If given as None, the
1426 IPython-initialized one is updated with __main__.__dict__, so that
1437 IPython-initialized one is updated with __main__.__dict__, so that
1427 program variables become visible but user-specific configuration
1438 program variables become visible but user-specific configuration
1428 remains possible.
1439 remains possible.
1429
1440
1430 - stack_depth: specifies how many levels in the stack to go to
1441 - stack_depth: specifies how many levels in the stack to go to
1431 looking for namespaces (when local_ns and global_ns are None). This
1442 looking for namespaces (when local_ns and global_ns are None). This
1432 allows an intermediate caller to make sure that this function gets
1443 allows an intermediate caller to make sure that this function gets
1433 the namespace from the intended level in the stack. By default (0)
1444 the namespace from the intended level in the stack. By default (0)
1434 it will get its locals and globals from the immediate caller.
1445 it will get its locals and globals from the immediate caller.
1435
1446
1436 Warning: it's possible to use this in a program which is being run by
1447 Warning: it's possible to use this in a program which is being run by
1437 IPython itself (via %run), but some funny things will happen (a few
1448 IPython itself (via %run), but some funny things will happen (a few
1438 globals get overwritten). In the future this will be cleaned up, as
1449 globals get overwritten). In the future this will be cleaned up, as
1439 there is no fundamental reason why it can't work perfectly."""
1450 there is no fundamental reason why it can't work perfectly."""
1440
1451
1441 # Get locals and globals from caller
1452 # Get locals and globals from caller
1442 if local_ns is None or global_ns is None:
1453 if local_ns is None or global_ns is None:
1443 call_frame = sys._getframe(stack_depth).f_back
1454 call_frame = sys._getframe(stack_depth).f_back
1444
1455
1445 if local_ns is None:
1456 if local_ns is None:
1446 local_ns = call_frame.f_locals
1457 local_ns = call_frame.f_locals
1447 if global_ns is None:
1458 if global_ns is None:
1448 global_ns = call_frame.f_globals
1459 global_ns = call_frame.f_globals
1449
1460
1450 # Update namespaces and fire up interpreter
1461 # Update namespaces and fire up interpreter
1451
1462
1452 # The global one is easy, we can just throw it in
1463 # The global one is easy, we can just throw it in
1453 self.user_global_ns = global_ns
1464 self.user_global_ns = global_ns
1454
1465
1455 # but the user/local one is tricky: ipython needs it to store internal
1466 # but the user/local one is tricky: ipython needs it to store internal
1456 # data, but we also need the locals. We'll copy locals in the user
1467 # data, but we also need the locals. We'll copy locals in the user
1457 # one, but will track what got copied so we can delete them at exit.
1468 # one, but will track what got copied so we can delete them at exit.
1458 # This is so that a later embedded call doesn't see locals from a
1469 # This is so that a later embedded call doesn't see locals from a
1459 # previous call (which most likely existed in a separate scope).
1470 # previous call (which most likely existed in a separate scope).
1460 local_varnames = local_ns.keys()
1471 local_varnames = local_ns.keys()
1461 self.user_ns.update(local_ns)
1472 self.user_ns.update(local_ns)
1462
1473
1463 # Patch for global embedding to make sure that things don't overwrite
1474 # Patch for global embedding to make sure that things don't overwrite
1464 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1475 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1465 # FIXME. Test this a bit more carefully (the if.. is new)
1476 # FIXME. Test this a bit more carefully (the if.. is new)
1466 if local_ns is None and global_ns is None:
1477 if local_ns is None and global_ns is None:
1467 self.user_global_ns.update(__main__.__dict__)
1478 self.user_global_ns.update(__main__.__dict__)
1468
1479
1469 # make sure the tab-completer has the correct frame information, so it
1480 # make sure the tab-completer has the correct frame information, so it
1470 # actually completes using the frame's locals/globals
1481 # actually completes using the frame's locals/globals
1471 self.set_completer_frame()
1482 self.set_completer_frame()
1472
1483
1473 # before activating the interactive mode, we need to make sure that
1484 # before activating the interactive mode, we need to make sure that
1474 # all names in the builtin namespace needed by ipython point to
1485 # all names in the builtin namespace needed by ipython point to
1475 # ourselves, and not to other instances.
1486 # ourselves, and not to other instances.
1476 self.add_builtins()
1487 self.add_builtins()
1477
1488
1478 self.interact(header)
1489 self.interact(header)
1479
1490
1480 # now, purge out the user namespace from anything we might have added
1491 # now, purge out the user namespace from anything we might have added
1481 # from the caller's local namespace
1492 # from the caller's local namespace
1482 delvar = self.user_ns.pop
1493 delvar = self.user_ns.pop
1483 for var in local_varnames:
1494 for var in local_varnames:
1484 delvar(var,None)
1495 delvar(var,None)
1485 # and clean builtins we may have overridden
1496 # and clean builtins we may have overridden
1486 self.clean_builtins()
1497 self.clean_builtins()
1487
1498
1488 def interact(self, banner=None):
1499 def interact(self, banner=None):
1489 """Closely emulate the interactive Python console.
1500 """Closely emulate the interactive Python console.
1490
1501
1491 The optional banner argument specify the banner to print
1502 The optional banner argument specify the banner to print
1492 before the first interaction; by default it prints a banner
1503 before the first interaction; by default it prints a banner
1493 similar to the one printed by the real Python interpreter,
1504 similar to the one printed by the real Python interpreter,
1494 followed by the current class name in parentheses (so as not
1505 followed by the current class name in parentheses (so as not
1495 to confuse this with the real interpreter -- since it's so
1506 to confuse this with the real interpreter -- since it's so
1496 close!).
1507 close!).
1497
1508
1498 """
1509 """
1499
1510
1500 if self.exit_now:
1511 if self.exit_now:
1501 # batch run -> do not interact
1512 # batch run -> do not interact
1502 return
1513 return
1503 cprt = 'Type "copyright", "credits" or "license" for more information.'
1514 cprt = 'Type "copyright", "credits" or "license" for more information.'
1504 if banner is None:
1515 if banner is None:
1505 self.write("Python %s on %s\n%s\n(%s)\n" %
1516 self.write("Python %s on %s\n%s\n(%s)\n" %
1506 (sys.version, sys.platform, cprt,
1517 (sys.version, sys.platform, cprt,
1507 self.__class__.__name__))
1518 self.__class__.__name__))
1508 else:
1519 else:
1509 self.write(banner)
1520 self.write(banner)
1510
1521
1511 more = 0
1522 more = 0
1512
1523
1513 # Mark activity in the builtins
1524 # Mark activity in the builtins
1514 __builtin__.__dict__['__IPYTHON__active'] += 1
1525 __builtin__.__dict__['__IPYTHON__active'] += 1
1515
1526
1516 # exit_now is set by a call to %Exit or %Quit
1527 # exit_now is set by a call to %Exit or %Quit
1517 while not self.exit_now:
1528 while not self.exit_now:
1518 if more:
1529 if more:
1519 prompt = self.hooks.generate_prompt(True)
1530 prompt = self.hooks.generate_prompt(True)
1520 if self.autoindent:
1531 if self.autoindent:
1521 self.readline_startup_hook(self.pre_readline)
1532 self.readline_startup_hook(self.pre_readline)
1522 else:
1533 else:
1523 prompt = self.hooks.generate_prompt(False)
1534 prompt = self.hooks.generate_prompt(False)
1524 try:
1535 try:
1525 line = self.raw_input(prompt,more)
1536 line = self.raw_input(prompt,more)
1526 if self.exit_now:
1537 if self.exit_now:
1527 # quick exit on sys.std[in|out] close
1538 # quick exit on sys.std[in|out] close
1528 break
1539 break
1529 if self.autoindent:
1540 if self.autoindent:
1530 self.readline_startup_hook(None)
1541 self.readline_startup_hook(None)
1531 except KeyboardInterrupt:
1542 except KeyboardInterrupt:
1532 self.write('\nKeyboardInterrupt\n')
1543 self.write('\nKeyboardInterrupt\n')
1533 self.resetbuffer()
1544 self.resetbuffer()
1534 # keep cache in sync with the prompt counter:
1545 # keep cache in sync with the prompt counter:
1535 self.outputcache.prompt_count -= 1
1546 self.outputcache.prompt_count -= 1
1536
1547
1537 if self.autoindent:
1548 if self.autoindent:
1538 self.indent_current_nsp = 0
1549 self.indent_current_nsp = 0
1539 more = 0
1550 more = 0
1540 except EOFError:
1551 except EOFError:
1541 if self.autoindent:
1552 if self.autoindent:
1542 self.readline_startup_hook(None)
1553 self.readline_startup_hook(None)
1543 self.write('\n')
1554 self.write('\n')
1544 self.exit()
1555 self.exit()
1545 except bdb.BdbQuit:
1556 except bdb.BdbQuit:
1546 warn('The Python debugger has exited with a BdbQuit exception.\n'
1557 warn('The Python debugger has exited with a BdbQuit exception.\n'
1547 'Because of how pdb handles the stack, it is impossible\n'
1558 'Because of how pdb handles the stack, it is impossible\n'
1548 'for IPython to properly format this particular exception.\n'
1559 'for IPython to properly format this particular exception.\n'
1549 'IPython will resume normal operation.')
1560 'IPython will resume normal operation.')
1550 except:
1561 except:
1551 # exceptions here are VERY RARE, but they can be triggered
1562 # exceptions here are VERY RARE, but they can be triggered
1552 # asynchronously by signal handlers, for example.
1563 # asynchronously by signal handlers, for example.
1553 self.showtraceback()
1564 self.showtraceback()
1554 else:
1565 else:
1555 more = self.push(line)
1566 more = self.push(line)
1556 if (self.SyntaxTB.last_syntax_error and
1567 if (self.SyntaxTB.last_syntax_error and
1557 self.rc.autoedit_syntax):
1568 self.rc.autoedit_syntax):
1558 self.edit_syntax_error()
1569 self.edit_syntax_error()
1559
1570
1560 # We are off again...
1571 # We are off again...
1561 __builtin__.__dict__['__IPYTHON__active'] -= 1
1572 __builtin__.__dict__['__IPYTHON__active'] -= 1
1562
1573
1563 def excepthook(self, etype, value, tb):
1574 def excepthook(self, etype, value, tb):
1564 """One more defense for GUI apps that call sys.excepthook.
1575 """One more defense for GUI apps that call sys.excepthook.
1565
1576
1566 GUI frameworks like wxPython trap exceptions and call
1577 GUI frameworks like wxPython trap exceptions and call
1567 sys.excepthook themselves. I guess this is a feature that
1578 sys.excepthook themselves. I guess this is a feature that
1568 enables them to keep running after exceptions that would
1579 enables them to keep running after exceptions that would
1569 otherwise kill their mainloop. This is a bother for IPython
1580 otherwise kill their mainloop. This is a bother for IPython
1570 which excepts to catch all of the program exceptions with a try:
1581 which excepts to catch all of the program exceptions with a try:
1571 except: statement.
1582 except: statement.
1572
1583
1573 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1584 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1574 any app directly invokes sys.excepthook, it will look to the user like
1585 any app directly invokes sys.excepthook, it will look to the user like
1575 IPython crashed. In order to work around this, we can disable the
1586 IPython crashed. In order to work around this, we can disable the
1576 CrashHandler and replace it with this excepthook instead, which prints a
1587 CrashHandler and replace it with this excepthook instead, which prints a
1577 regular traceback using our InteractiveTB. In this fashion, apps which
1588 regular traceback using our InteractiveTB. In this fashion, apps which
1578 call sys.excepthook will generate a regular-looking exception from
1589 call sys.excepthook will generate a regular-looking exception from
1579 IPython, and the CrashHandler will only be triggered by real IPython
1590 IPython, and the CrashHandler will only be triggered by real IPython
1580 crashes.
1591 crashes.
1581
1592
1582 This hook should be used sparingly, only in places which are not likely
1593 This hook should be used sparingly, only in places which are not likely
1583 to be true IPython errors.
1594 to be true IPython errors.
1584 """
1595 """
1585 self.showtraceback((etype,value,tb),tb_offset=0)
1596 self.showtraceback((etype,value,tb),tb_offset=0)
1586
1597
1587 def expand_aliases(self,fn,rest):
1598 def expand_aliases(self,fn,rest):
1588 """ Expand multiple levels of aliases:
1599 """ Expand multiple levels of aliases:
1589
1600
1590 if:
1601 if:
1591
1602
1592 alias foo bar /tmp
1603 alias foo bar /tmp
1593 alias baz foo
1604 alias baz foo
1594
1605
1595 then:
1606 then:
1596
1607
1597 baz huhhahhei -> bar /tmp huhhahhei
1608 baz huhhahhei -> bar /tmp huhhahhei
1598
1609
1599 """
1610 """
1600 line = fn + " " + rest
1611 line = fn + " " + rest
1601
1612
1602 done = Set()
1613 done = Set()
1603 while 1:
1614 while 1:
1604 pre,fn,rest = self.split_user_input(line)
1615 pre,fn,rest = self.split_user_input(line)
1605 if fn in self.alias_table:
1616 if fn in self.alias_table:
1606 if fn in done:
1617 if fn in done:
1607 warn("Cyclic alias definition, repeated '%s'" % fn)
1618 warn("Cyclic alias definition, repeated '%s'" % fn)
1608 return ""
1619 return ""
1609 done.add(fn)
1620 done.add(fn)
1610
1621
1611 l2 = self.transform_alias(fn,rest)
1622 l2 = self.transform_alias(fn,rest)
1612 # dir -> dir
1623 # dir -> dir
1613 if l2 == line:
1624 if l2 == line:
1614 break
1625 break
1615 # ls -> ls -F should not recurse forever
1626 # ls -> ls -F should not recurse forever
1616 if l2.split(None,1)[0] == line.split(None,1)[0]:
1627 if l2.split(None,1)[0] == line.split(None,1)[0]:
1617 line = l2
1628 line = l2
1618 break
1629 break
1619
1630
1620 line=l2
1631 line=l2
1621
1632
1622
1633
1623 # print "al expand to",line #dbg
1634 # print "al expand to",line #dbg
1624 else:
1635 else:
1625 break
1636 break
1626
1637
1627 return line
1638 return line
1628
1639
1629 def transform_alias(self, alias,rest=''):
1640 def transform_alias(self, alias,rest=''):
1630 """ Transform alias to system command string.
1641 """ Transform alias to system command string.
1631 """
1642 """
1632 nargs,cmd = self.alias_table[alias]
1643 nargs,cmd = self.alias_table[alias]
1633 if ' ' in cmd and os.path.isfile(cmd):
1644 if ' ' in cmd and os.path.isfile(cmd):
1634 cmd = '"%s"' % cmd
1645 cmd = '"%s"' % cmd
1635
1646
1636 # Expand the %l special to be the user's input line
1647 # Expand the %l special to be the user's input line
1637 if cmd.find('%l') >= 0:
1648 if cmd.find('%l') >= 0:
1638 cmd = cmd.replace('%l',rest)
1649 cmd = cmd.replace('%l',rest)
1639 rest = ''
1650 rest = ''
1640 if nargs==0:
1651 if nargs==0:
1641 # Simple, argument-less aliases
1652 # Simple, argument-less aliases
1642 cmd = '%s %s' % (cmd,rest)
1653 cmd = '%s %s' % (cmd,rest)
1643 else:
1654 else:
1644 # Handle aliases with positional arguments
1655 # Handle aliases with positional arguments
1645 args = rest.split(None,nargs)
1656 args = rest.split(None,nargs)
1646 if len(args)< nargs:
1657 if len(args)< nargs:
1647 error('Alias <%s> requires %s arguments, %s given.' %
1658 error('Alias <%s> requires %s arguments, %s given.' %
1648 (alias,nargs,len(args)))
1659 (alias,nargs,len(args)))
1649 return None
1660 return None
1650 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1661 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1651 # Now call the macro, evaluating in the user's namespace
1662 # Now call the macro, evaluating in the user's namespace
1652 #print 'new command: <%r>' % cmd # dbg
1663 #print 'new command: <%r>' % cmd # dbg
1653 return cmd
1664 return cmd
1654
1665
1655 def call_alias(self,alias,rest=''):
1666 def call_alias(self,alias,rest=''):
1656 """Call an alias given its name and the rest of the line.
1667 """Call an alias given its name and the rest of the line.
1657
1668
1658 This is only used to provide backwards compatibility for users of
1669 This is only used to provide backwards compatibility for users of
1659 ipalias(), use of which is not recommended for anymore."""
1670 ipalias(), use of which is not recommended for anymore."""
1660
1671
1661 # Now call the macro, evaluating in the user's namespace
1672 # Now call the macro, evaluating in the user's namespace
1662 cmd = self.transform_alias(alias, rest)
1673 cmd = self.transform_alias(alias, rest)
1663 try:
1674 try:
1664 self.system(cmd)
1675 self.system(cmd)
1665 except:
1676 except:
1666 self.showtraceback()
1677 self.showtraceback()
1667
1678
1668 def indent_current_str(self):
1679 def indent_current_str(self):
1669 """return the current level of indentation as a string"""
1680 """return the current level of indentation as a string"""
1670 return self.indent_current_nsp * ' '
1681 return self.indent_current_nsp * ' '
1671
1682
1672 def autoindent_update(self,line):
1683 def autoindent_update(self,line):
1673 """Keep track of the indent level."""
1684 """Keep track of the indent level."""
1674
1685
1675 #debugx('line')
1686 #debugx('line')
1676 #debugx('self.indent_current_nsp')
1687 #debugx('self.indent_current_nsp')
1677 if self.autoindent:
1688 if self.autoindent:
1678 if line:
1689 if line:
1679 inisp = num_ini_spaces(line)
1690 inisp = num_ini_spaces(line)
1680 if inisp < self.indent_current_nsp:
1691 if inisp < self.indent_current_nsp:
1681 self.indent_current_nsp = inisp
1692 self.indent_current_nsp = inisp
1682
1693
1683 if line[-1] == ':':
1694 if line[-1] == ':':
1684 self.indent_current_nsp += 4
1695 self.indent_current_nsp += 4
1685 elif dedent_re.match(line):
1696 elif dedent_re.match(line):
1686 self.indent_current_nsp -= 4
1697 self.indent_current_nsp -= 4
1687 else:
1698 else:
1688 self.indent_current_nsp = 0
1699 self.indent_current_nsp = 0
1689
1700
1690 def runlines(self,lines):
1701 def runlines(self,lines):
1691 """Run a string of one or more lines of source.
1702 """Run a string of one or more lines of source.
1692
1703
1693 This method is capable of running a string containing multiple source
1704 This method is capable of running a string containing multiple source
1694 lines, as if they had been entered at the IPython prompt. Since it
1705 lines, as if they had been entered at the IPython prompt. Since it
1695 exposes IPython's processing machinery, the given strings can contain
1706 exposes IPython's processing machinery, the given strings can contain
1696 magic calls (%magic), special shell access (!cmd), etc."""
1707 magic calls (%magic), special shell access (!cmd), etc."""
1697
1708
1698 # We must start with a clean buffer, in case this is run from an
1709 # We must start with a clean buffer, in case this is run from an
1699 # interactive IPython session (via a magic, for example).
1710 # interactive IPython session (via a magic, for example).
1700 self.resetbuffer()
1711 self.resetbuffer()
1701 lines = lines.split('\n')
1712 lines = lines.split('\n')
1702 more = 0
1713 more = 0
1703 for line in lines:
1714 for line in lines:
1704 # skip blank lines so we don't mess up the prompt counter, but do
1715 # skip blank lines so we don't mess up the prompt counter, but do
1705 # NOT skip even a blank line if we are in a code block (more is
1716 # NOT skip even a blank line if we are in a code block (more is
1706 # true)
1717 # true)
1707 if line or more:
1718 if line or more:
1708 more = self.push(self.prefilter(line,more))
1719 more = self.push(self.prefilter(line,more))
1709 # IPython's runsource returns None if there was an error
1720 # IPython's runsource returns None if there was an error
1710 # compiling the code. This allows us to stop processing right
1721 # compiling the code. This allows us to stop processing right
1711 # away, so the user gets the error message at the right place.
1722 # away, so the user gets the error message at the right place.
1712 if more is None:
1723 if more is None:
1713 break
1724 break
1714 # final newline in case the input didn't have it, so that the code
1725 # final newline in case the input didn't have it, so that the code
1715 # actually does get executed
1726 # actually does get executed
1716 if more:
1727 if more:
1717 self.push('\n')
1728 self.push('\n')
1718
1729
1719 def runsource(self, source, filename='<input>', symbol='single'):
1730 def runsource(self, source, filename='<input>', symbol='single'):
1720 """Compile and run some source in the interpreter.
1731 """Compile and run some source in the interpreter.
1721
1732
1722 Arguments are as for compile_command().
1733 Arguments are as for compile_command().
1723
1734
1724 One several things can happen:
1735 One several things can happen:
1725
1736
1726 1) The input is incorrect; compile_command() raised an
1737 1) The input is incorrect; compile_command() raised an
1727 exception (SyntaxError or OverflowError). A syntax traceback
1738 exception (SyntaxError or OverflowError). A syntax traceback
1728 will be printed by calling the showsyntaxerror() method.
1739 will be printed by calling the showsyntaxerror() method.
1729
1740
1730 2) The input is incomplete, and more input is required;
1741 2) The input is incomplete, and more input is required;
1731 compile_command() returned None. Nothing happens.
1742 compile_command() returned None. Nothing happens.
1732
1743
1733 3) The input is complete; compile_command() returned a code
1744 3) The input is complete; compile_command() returned a code
1734 object. The code is executed by calling self.runcode() (which
1745 object. The code is executed by calling self.runcode() (which
1735 also handles run-time exceptions, except for SystemExit).
1746 also handles run-time exceptions, except for SystemExit).
1736
1747
1737 The return value is:
1748 The return value is:
1738
1749
1739 - True in case 2
1750 - True in case 2
1740
1751
1741 - False in the other cases, unless an exception is raised, where
1752 - False in the other cases, unless an exception is raised, where
1742 None is returned instead. This can be used by external callers to
1753 None is returned instead. This can be used by external callers to
1743 know whether to continue feeding input or not.
1754 know whether to continue feeding input or not.
1744
1755
1745 The return value can be used to decide whether to use sys.ps1 or
1756 The return value can be used to decide whether to use sys.ps1 or
1746 sys.ps2 to prompt the next line."""
1757 sys.ps2 to prompt the next line."""
1747
1758
1748 try:
1759 try:
1749 code = self.compile(source,filename,symbol)
1760 code = self.compile(source,filename,symbol)
1750 except (OverflowError, SyntaxError, ValueError):
1761 except (OverflowError, SyntaxError, ValueError):
1751 # Case 1
1762 # Case 1
1752 self.showsyntaxerror(filename)
1763 self.showsyntaxerror(filename)
1753 return None
1764 return None
1754
1765
1755 if code is None:
1766 if code is None:
1756 # Case 2
1767 # Case 2
1757 return True
1768 return True
1758
1769
1759 # Case 3
1770 # Case 3
1760 # We store the code object so that threaded shells and
1771 # We store the code object so that threaded shells and
1761 # custom exception handlers can access all this info if needed.
1772 # custom exception handlers can access all this info if needed.
1762 # The source corresponding to this can be obtained from the
1773 # The source corresponding to this can be obtained from the
1763 # buffer attribute as '\n'.join(self.buffer).
1774 # buffer attribute as '\n'.join(self.buffer).
1764 self.code_to_run = code
1775 self.code_to_run = code
1765 # now actually execute the code object
1776 # now actually execute the code object
1766 if self.runcode(code) == 0:
1777 if self.runcode(code) == 0:
1767 return False
1778 return False
1768 else:
1779 else:
1769 return None
1780 return None
1770
1781
1771 def runcode(self,code_obj):
1782 def runcode(self,code_obj):
1772 """Execute a code object.
1783 """Execute a code object.
1773
1784
1774 When an exception occurs, self.showtraceback() is called to display a
1785 When an exception occurs, self.showtraceback() is called to display a
1775 traceback.
1786 traceback.
1776
1787
1777 Return value: a flag indicating whether the code to be run completed
1788 Return value: a flag indicating whether the code to be run completed
1778 successfully:
1789 successfully:
1779
1790
1780 - 0: successful execution.
1791 - 0: successful execution.
1781 - 1: an error occurred.
1792 - 1: an error occurred.
1782 """
1793 """
1783
1794
1784 # Set our own excepthook in case the user code tries to call it
1795 # Set our own excepthook in case the user code tries to call it
1785 # directly, so that the IPython crash handler doesn't get triggered
1796 # directly, so that the IPython crash handler doesn't get triggered
1786 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1797 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1787
1798
1788 # we save the original sys.excepthook in the instance, in case config
1799 # we save the original sys.excepthook in the instance, in case config
1789 # code (such as magics) needs access to it.
1800 # code (such as magics) needs access to it.
1790 self.sys_excepthook = old_excepthook
1801 self.sys_excepthook = old_excepthook
1791 outflag = 1 # happens in more places, so it's easier as default
1802 outflag = 1 # happens in more places, so it's easier as default
1792 try:
1803 try:
1793 try:
1804 try:
1794 # Embedded instances require separate global/local namespaces
1805 # Embedded instances require separate global/local namespaces
1795 # so they can see both the surrounding (local) namespace and
1806 # so they can see both the surrounding (local) namespace and
1796 # the module-level globals when called inside another function.
1807 # the module-level globals when called inside another function.
1797 if self.embedded:
1808 if self.embedded:
1798 exec code_obj in self.user_global_ns, self.user_ns
1809 exec code_obj in self.user_global_ns, self.user_ns
1799 # Normal (non-embedded) instances should only have a single
1810 # Normal (non-embedded) instances should only have a single
1800 # namespace for user code execution, otherwise functions won't
1811 # namespace for user code execution, otherwise functions won't
1801 # see interactive top-level globals.
1812 # see interactive top-level globals.
1802 else:
1813 else:
1803 exec code_obj in self.user_ns
1814 exec code_obj in self.user_ns
1804 finally:
1815 finally:
1805 # Reset our crash handler in place
1816 # Reset our crash handler in place
1806 sys.excepthook = old_excepthook
1817 sys.excepthook = old_excepthook
1807 except SystemExit:
1818 except SystemExit:
1808 self.resetbuffer()
1819 self.resetbuffer()
1809 self.showtraceback()
1820 self.showtraceback()
1810 warn("Type %exit or %quit to exit IPython "
1821 warn("Type %exit or %quit to exit IPython "
1811 "(%Exit or %Quit do so unconditionally).",level=1)
1822 "(%Exit or %Quit do so unconditionally).",level=1)
1812 except self.custom_exceptions:
1823 except self.custom_exceptions:
1813 etype,value,tb = sys.exc_info()
1824 etype,value,tb = sys.exc_info()
1814 self.CustomTB(etype,value,tb)
1825 self.CustomTB(etype,value,tb)
1815 except:
1826 except:
1816 self.showtraceback()
1827 self.showtraceback()
1817 else:
1828 else:
1818 outflag = 0
1829 outflag = 0
1819 if softspace(sys.stdout, 0):
1830 if softspace(sys.stdout, 0):
1820 print
1831 print
1821 # Flush out code object which has been run (and source)
1832 # Flush out code object which has been run (and source)
1822 self.code_to_run = None
1833 self.code_to_run = None
1823 return outflag
1834 return outflag
1824
1835
1825 def push(self, line):
1836 def push(self, line):
1826 """Push a line to the interpreter.
1837 """Push a line to the interpreter.
1827
1838
1828 The line should not have a trailing newline; it may have
1839 The line should not have a trailing newline; it may have
1829 internal newlines. The line is appended to a buffer and the
1840 internal newlines. The line is appended to a buffer and the
1830 interpreter's runsource() method is called with the
1841 interpreter's runsource() method is called with the
1831 concatenated contents of the buffer as source. If this
1842 concatenated contents of the buffer as source. If this
1832 indicates that the command was executed or invalid, the buffer
1843 indicates that the command was executed or invalid, the buffer
1833 is reset; otherwise, the command is incomplete, and the buffer
1844 is reset; otherwise, the command is incomplete, and the buffer
1834 is left as it was after the line was appended. The return
1845 is left as it was after the line was appended. The return
1835 value is 1 if more input is required, 0 if the line was dealt
1846 value is 1 if more input is required, 0 if the line was dealt
1836 with in some way (this is the same as runsource()).
1847 with in some way (this is the same as runsource()).
1837 """
1848 """
1838
1849
1839 # autoindent management should be done here, and not in the
1850 # autoindent management should be done here, and not in the
1840 # interactive loop, since that one is only seen by keyboard input. We
1851 # interactive loop, since that one is only seen by keyboard input. We
1841 # need this done correctly even for code run via runlines (which uses
1852 # need this done correctly even for code run via runlines (which uses
1842 # push).
1853 # push).
1843
1854
1844 #print 'push line: <%s>' % line # dbg
1855 #print 'push line: <%s>' % line # dbg
1845 for subline in line.splitlines():
1856 for subline in line.splitlines():
1846 self.autoindent_update(subline)
1857 self.autoindent_update(subline)
1847 self.buffer.append(line)
1858 self.buffer.append(line)
1848 more = self.runsource('\n'.join(self.buffer), self.filename)
1859 more = self.runsource('\n'.join(self.buffer), self.filename)
1849 if not more:
1860 if not more:
1850 self.resetbuffer()
1861 self.resetbuffer()
1851 return more
1862 return more
1852
1863
1853 def resetbuffer(self):
1864 def resetbuffer(self):
1854 """Reset the input buffer."""
1865 """Reset the input buffer."""
1855 self.buffer[:] = []
1866 self.buffer[:] = []
1856
1867
1857 def raw_input(self,prompt='',continue_prompt=False):
1868 def raw_input(self,prompt='',continue_prompt=False):
1858 """Write a prompt and read a line.
1869 """Write a prompt and read a line.
1859
1870
1860 The returned line does not include the trailing newline.
1871 The returned line does not include the trailing newline.
1861 When the user enters the EOF key sequence, EOFError is raised.
1872 When the user enters the EOF key sequence, EOFError is raised.
1862
1873
1863 Optional inputs:
1874 Optional inputs:
1864
1875
1865 - prompt(''): a string to be printed to prompt the user.
1876 - prompt(''): a string to be printed to prompt the user.
1866
1877
1867 - continue_prompt(False): whether this line is the first one or a
1878 - continue_prompt(False): whether this line is the first one or a
1868 continuation in a sequence of inputs.
1879 continuation in a sequence of inputs.
1869 """
1880 """
1870
1881
1871 try:
1882 try:
1872 line = raw_input_original(prompt)
1883 line = raw_input_original(prompt)
1873 except ValueError:
1884 except ValueError:
1874 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1885 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1875 self.exit_now = True
1886 self.exit_now = True
1876 return ""
1887 return ""
1877
1888
1878
1889
1879 # Try to be reasonably smart about not re-indenting pasted input more
1890 # Try to be reasonably smart about not re-indenting pasted input more
1880 # than necessary. We do this by trimming out the auto-indent initial
1891 # than necessary. We do this by trimming out the auto-indent initial
1881 # spaces, if the user's actual input started itself with whitespace.
1892 # spaces, if the user's actual input started itself with whitespace.
1882 #debugx('self.buffer[-1]')
1893 #debugx('self.buffer[-1]')
1883
1894
1884 if self.autoindent:
1895 if self.autoindent:
1885 if num_ini_spaces(line) > self.indent_current_nsp:
1896 if num_ini_spaces(line) > self.indent_current_nsp:
1886 line = line[self.indent_current_nsp:]
1897 line = line[self.indent_current_nsp:]
1887 self.indent_current_nsp = 0
1898 self.indent_current_nsp = 0
1888
1899
1889 # store the unfiltered input before the user has any chance to modify
1900 # store the unfiltered input before the user has any chance to modify
1890 # it.
1901 # it.
1891 if line.strip():
1902 if line.strip():
1892 if continue_prompt:
1903 if continue_prompt:
1893 self.input_hist_raw[-1] += '%s\n' % line
1904 self.input_hist_raw[-1] += '%s\n' % line
1894 if self.has_readline: # and some config option is set?
1905 if self.has_readline: # and some config option is set?
1895 try:
1906 try:
1896 histlen = self.readline.get_current_history_length()
1907 histlen = self.readline.get_current_history_length()
1897 newhist = self.input_hist_raw[-1].rstrip()
1908 newhist = self.input_hist_raw[-1].rstrip()
1898 self.readline.remove_history_item(histlen-1)
1909 self.readline.remove_history_item(histlen-1)
1899 self.readline.replace_history_item(histlen-2,newhist)
1910 self.readline.replace_history_item(histlen-2,newhist)
1900 except AttributeError:
1911 except AttributeError:
1901 pass # re{move,place}_history_item are new in 2.4.
1912 pass # re{move,place}_history_item are new in 2.4.
1902 else:
1913 else:
1903 self.input_hist_raw.append('%s\n' % line)
1914 self.input_hist_raw.append('%s\n' % line)
1904
1915
1905 try:
1916 try:
1906 lineout = self.prefilter(line,continue_prompt)
1917 lineout = self.prefilter(line,continue_prompt)
1907 except:
1918 except:
1908 # blanket except, in case a user-defined prefilter crashes, so it
1919 # blanket except, in case a user-defined prefilter crashes, so it
1909 # can't take all of ipython with it.
1920 # can't take all of ipython with it.
1910 self.showtraceback()
1921 self.showtraceback()
1911 return ''
1922 return ''
1912 else:
1923 else:
1913 return lineout
1924 return lineout
1914
1925
1915 def split_user_input(self,line):
1926 def split_user_input(self,line):
1916 """Split user input into pre-char, function part and rest."""
1927 """Split user input into pre-char, function part and rest."""
1917
1928
1918 lsplit = self.line_split.match(line)
1929 lsplit = self.line_split.match(line)
1919 if lsplit is None: # no regexp match returns None
1930 if lsplit is None: # no regexp match returns None
1920 try:
1931 try:
1921 iFun,theRest = line.split(None,1)
1932 iFun,theRest = line.split(None,1)
1922 except ValueError:
1933 except ValueError:
1923 iFun,theRest = line,''
1934 iFun,theRest = line,''
1924 pre = re.match('^(\s*)(.*)',line).groups()[0]
1935 pre = re.match('^(\s*)(.*)',line).groups()[0]
1925 else:
1936 else:
1926 pre,iFun,theRest = lsplit.groups()
1937 pre,iFun,theRest = lsplit.groups()
1927
1938
1928 #print 'line:<%s>' % line # dbg
1939 #print 'line:<%s>' % line # dbg
1929 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1940 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1930 return pre,iFun.strip(),theRest
1941 return pre,iFun.strip(),theRest
1931
1942
1932 def _prefilter(self, line, continue_prompt):
1943 def _prefilter(self, line, continue_prompt):
1933 """Calls different preprocessors, depending on the form of line."""
1944 """Calls different preprocessors, depending on the form of line."""
1934
1945
1935 # All handlers *must* return a value, even if it's blank ('').
1946 # All handlers *must* return a value, even if it's blank ('').
1936
1947
1937 # Lines are NOT logged here. Handlers should process the line as
1948 # Lines are NOT logged here. Handlers should process the line as
1938 # needed, update the cache AND log it (so that the input cache array
1949 # needed, update the cache AND log it (so that the input cache array
1939 # stays synced).
1950 # stays synced).
1940
1951
1941 # This function is _very_ delicate, and since it's also the one which
1952 # This function is _very_ delicate, and since it's also the one which
1942 # determines IPython's response to user input, it must be as efficient
1953 # determines IPython's response to user input, it must be as efficient
1943 # as possible. For this reason it has _many_ returns in it, trying
1954 # as possible. For this reason it has _many_ returns in it, trying
1944 # always to exit as quickly as it can figure out what it needs to do.
1955 # always to exit as quickly as it can figure out what it needs to do.
1945
1956
1946 # This function is the main responsible for maintaining IPython's
1957 # This function is the main responsible for maintaining IPython's
1947 # behavior respectful of Python's semantics. So be _very_ careful if
1958 # behavior respectful of Python's semantics. So be _very_ careful if
1948 # making changes to anything here.
1959 # making changes to anything here.
1949
1960
1950 #.....................................................................
1961 #.....................................................................
1951 # Code begins
1962 # Code begins
1952
1963
1953 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1964 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1954
1965
1955 # save the line away in case we crash, so the post-mortem handler can
1966 # save the line away in case we crash, so the post-mortem handler can
1956 # record it
1967 # record it
1957 self._last_input_line = line
1968 self._last_input_line = line
1958
1969
1959 #print '***line: <%s>' % line # dbg
1970 #print '***line: <%s>' % line # dbg
1960
1971
1961 # the input history needs to track even empty lines
1972 # the input history needs to track even empty lines
1962 stripped = line.strip()
1973 stripped = line.strip()
1963
1974
1964 if not stripped:
1975 if not stripped:
1965 if not continue_prompt:
1976 if not continue_prompt:
1966 self.outputcache.prompt_count -= 1
1977 self.outputcache.prompt_count -= 1
1967 return self.handle_normal(line,continue_prompt)
1978 return self.handle_normal(line,continue_prompt)
1968 #return self.handle_normal('',continue_prompt)
1979 #return self.handle_normal('',continue_prompt)
1969
1980
1970 # print '***cont',continue_prompt # dbg
1981 # print '***cont',continue_prompt # dbg
1971 # special handlers are only allowed for single line statements
1982 # special handlers are only allowed for single line statements
1972 if continue_prompt and not self.rc.multi_line_specials:
1983 if continue_prompt and not self.rc.multi_line_specials:
1973 return self.handle_normal(line,continue_prompt)
1984 return self.handle_normal(line,continue_prompt)
1974
1985
1975
1986
1976 # For the rest, we need the structure of the input
1987 # For the rest, we need the structure of the input
1977 pre,iFun,theRest = self.split_user_input(line)
1988 pre,iFun,theRest = self.split_user_input(line)
1978
1989
1979 # See whether any pre-existing handler can take care of it
1990 # See whether any pre-existing handler can take care of it
1980
1991
1981 rewritten = self.hooks.input_prefilter(stripped)
1992 rewritten = self.hooks.input_prefilter(stripped)
1982 if rewritten != stripped: # ok, some prefilter did something
1993 if rewritten != stripped: # ok, some prefilter did something
1983 rewritten = pre + rewritten # add indentation
1994 rewritten = pre + rewritten # add indentation
1984 return self.handle_normal(rewritten)
1995 return self.handle_normal(rewritten)
1985
1996
1986 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1997 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1987
1998
1988 # First check for explicit escapes in the last/first character
1999 # First check for explicit escapes in the last/first character
1989 handler = None
2000 handler = None
1990 if line[-1] == self.ESC_HELP:
2001 if line[-1] == self.ESC_HELP:
1991 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2002 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1992 if handler is None:
2003 if handler is None:
1993 # look at the first character of iFun, NOT of line, so we skip
2004 # look at the first character of iFun, NOT of line, so we skip
1994 # leading whitespace in multiline input
2005 # leading whitespace in multiline input
1995 handler = self.esc_handlers.get(iFun[0:1])
2006 handler = self.esc_handlers.get(iFun[0:1])
1996 if handler is not None:
2007 if handler is not None:
1997 return handler(line,continue_prompt,pre,iFun,theRest)
2008 return handler(line,continue_prompt,pre,iFun,theRest)
1998 # Emacs ipython-mode tags certain input lines
2009 # Emacs ipython-mode tags certain input lines
1999 if line.endswith('# PYTHON-MODE'):
2010 if line.endswith('# PYTHON-MODE'):
2000 return self.handle_emacs(line,continue_prompt)
2011 return self.handle_emacs(line,continue_prompt)
2001
2012
2002 # Next, check if we can automatically execute this thing
2013 # Next, check if we can automatically execute this thing
2003
2014
2004 # Allow ! in multi-line statements if multi_line_specials is on:
2015 # Allow ! in multi-line statements if multi_line_specials is on:
2005 if continue_prompt and self.rc.multi_line_specials and \
2016 if continue_prompt and self.rc.multi_line_specials and \
2006 iFun.startswith(self.ESC_SHELL):
2017 iFun.startswith(self.ESC_SHELL):
2007 return self.handle_shell_escape(line,continue_prompt,
2018 return self.handle_shell_escape(line,continue_prompt,
2008 pre=pre,iFun=iFun,
2019 pre=pre,iFun=iFun,
2009 theRest=theRest)
2020 theRest=theRest)
2010
2021
2011 # Let's try to find if the input line is a magic fn
2022 # Let's try to find if the input line is a magic fn
2012 oinfo = None
2023 oinfo = None
2013 if hasattr(self,'magic_'+iFun):
2024 if hasattr(self,'magic_'+iFun):
2014 # WARNING: _ofind uses getattr(), so it can consume generators and
2025 # WARNING: _ofind uses getattr(), so it can consume generators and
2015 # cause other side effects.
2026 # cause other side effects.
2016 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2027 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2017 if oinfo['ismagic']:
2028 if oinfo['ismagic']:
2018 # Be careful not to call magics when a variable assignment is
2029 # Be careful not to call magics when a variable assignment is
2019 # being made (ls='hi', for example)
2030 # being made (ls='hi', for example)
2020 if self.rc.automagic and \
2031 if self.rc.automagic and \
2021 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2032 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2022 (self.rc.multi_line_specials or not continue_prompt):
2033 (self.rc.multi_line_specials or not continue_prompt):
2023 return self.handle_magic(line,continue_prompt,
2034 return self.handle_magic(line,continue_prompt,
2024 pre,iFun,theRest)
2035 pre,iFun,theRest)
2025 else:
2036 else:
2026 return self.handle_normal(line,continue_prompt)
2037 return self.handle_normal(line,continue_prompt)
2027
2038
2028 # If the rest of the line begins with an (in)equality, assginment or
2039 # If the rest of the line begins with an (in)equality, assginment or
2029 # function call, we should not call _ofind but simply execute it.
2040 # function call, we should not call _ofind but simply execute it.
2030 # This avoids spurious geattr() accesses on objects upon assignment.
2041 # This avoids spurious geattr() accesses on objects upon assignment.
2031 #
2042 #
2032 # It also allows users to assign to either alias or magic names true
2043 # It also allows users to assign to either alias or magic names true
2033 # python variables (the magic/alias systems always take second seat to
2044 # python variables (the magic/alias systems always take second seat to
2034 # true python code).
2045 # true python code).
2035 if theRest and theRest[0] in '!=()':
2046 if theRest and theRest[0] in '!=()':
2036 return self.handle_normal(line,continue_prompt)
2047 return self.handle_normal(line,continue_prompt)
2037
2048
2038 if oinfo is None:
2049 if oinfo is None:
2039 # let's try to ensure that _oinfo is ONLY called when autocall is
2050 # let's try to ensure that _oinfo is ONLY called when autocall is
2040 # on. Since it has inevitable potential side effects, at least
2051 # on. Since it has inevitable potential side effects, at least
2041 # having autocall off should be a guarantee to the user that no
2052 # having autocall off should be a guarantee to the user that no
2042 # weird things will happen.
2053 # weird things will happen.
2043
2054
2044 if self.rc.autocall:
2055 if self.rc.autocall:
2045 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2056 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2046 else:
2057 else:
2047 # in this case, all that's left is either an alias or
2058 # in this case, all that's left is either an alias or
2048 # processing the line normally.
2059 # processing the line normally.
2049 if iFun in self.alias_table:
2060 if iFun in self.alias_table:
2050 # if autocall is off, by not running _ofind we won't know
2061 # if autocall is off, by not running _ofind we won't know
2051 # whether the given name may also exist in one of the
2062 # whether the given name may also exist in one of the
2052 # user's namespace. At this point, it's best to do a
2063 # user's namespace. At this point, it's best to do a
2053 # quick check just to be sure that we don't let aliases
2064 # quick check just to be sure that we don't let aliases
2054 # shadow variables.
2065 # shadow variables.
2055 head = iFun.split('.',1)[0]
2066 head = iFun.split('.',1)[0]
2056 if head in self.user_ns or head in self.internal_ns \
2067 if head in self.user_ns or head in self.internal_ns \
2057 or head in __builtin__.__dict__:
2068 or head in __builtin__.__dict__:
2058 return self.handle_normal(line,continue_prompt)
2069 return self.handle_normal(line,continue_prompt)
2059 else:
2070 else:
2060 return self.handle_alias(line,continue_prompt,
2071 return self.handle_alias(line,continue_prompt,
2061 pre,iFun,theRest)
2072 pre,iFun,theRest)
2062
2073
2063 else:
2074 else:
2064 return self.handle_normal(line,continue_prompt)
2075 return self.handle_normal(line,continue_prompt)
2065
2076
2066 if not oinfo['found']:
2077 if not oinfo['found']:
2067 return self.handle_normal(line,continue_prompt)
2078 return self.handle_normal(line,continue_prompt)
2068 else:
2079 else:
2069 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2080 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2070 if oinfo['isalias']:
2081 if oinfo['isalias']:
2071 return self.handle_alias(line,continue_prompt,
2082 return self.handle_alias(line,continue_prompt,
2072 pre,iFun,theRest)
2083 pre,iFun,theRest)
2073
2084
2074 if (self.rc.autocall
2085 if (self.rc.autocall
2075 and
2086 and
2076 (
2087 (
2077 #only consider exclusion re if not "," or ";" autoquoting
2088 #only consider exclusion re if not "," or ";" autoquoting
2078 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2089 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2079 or pre == self.ESC_PAREN) or
2090 or pre == self.ESC_PAREN) or
2080 (not self.re_exclude_auto.match(theRest)))
2091 (not self.re_exclude_auto.match(theRest)))
2081 and
2092 and
2082 self.re_fun_name.match(iFun) and
2093 self.re_fun_name.match(iFun) and
2083 callable(oinfo['obj'])) :
2094 callable(oinfo['obj'])) :
2084 #print 'going auto' # dbg
2095 #print 'going auto' # dbg
2085 return self.handle_auto(line,continue_prompt,
2096 return self.handle_auto(line,continue_prompt,
2086 pre,iFun,theRest,oinfo['obj'])
2097 pre,iFun,theRest,oinfo['obj'])
2087 else:
2098 else:
2088 #print 'was callable?', callable(oinfo['obj']) # dbg
2099 #print 'was callable?', callable(oinfo['obj']) # dbg
2089 return self.handle_normal(line,continue_prompt)
2100 return self.handle_normal(line,continue_prompt)
2090
2101
2091 # If we get here, we have a normal Python line. Log and return.
2102 # If we get here, we have a normal Python line. Log and return.
2092 return self.handle_normal(line,continue_prompt)
2103 return self.handle_normal(line,continue_prompt)
2093
2104
2094 def _prefilter_dumb(self, line, continue_prompt):
2105 def _prefilter_dumb(self, line, continue_prompt):
2095 """simple prefilter function, for debugging"""
2106 """simple prefilter function, for debugging"""
2096 return self.handle_normal(line,continue_prompt)
2107 return self.handle_normal(line,continue_prompt)
2097
2108
2098
2109
2099 def multiline_prefilter(self, line, continue_prompt):
2110 def multiline_prefilter(self, line, continue_prompt):
2100 """ Run _prefilter for each line of input
2111 """ Run _prefilter for each line of input
2101
2112
2102 Covers cases where there are multiple lines in the user entry,
2113 Covers cases where there are multiple lines in the user entry,
2103 which is the case when the user goes back to a multiline history
2114 which is the case when the user goes back to a multiline history
2104 entry and presses enter.
2115 entry and presses enter.
2105
2116
2106 """
2117 """
2107 out = []
2118 out = []
2108 for l in line.rstrip('\n').split('\n'):
2119 for l in line.rstrip('\n').split('\n'):
2109 out.append(self._prefilter(l, continue_prompt))
2120 out.append(self._prefilter(l, continue_prompt))
2110 return '\n'.join(out)
2121 return '\n'.join(out)
2111
2122
2112 # Set the default prefilter() function (this can be user-overridden)
2123 # Set the default prefilter() function (this can be user-overridden)
2113 prefilter = multiline_prefilter
2124 prefilter = multiline_prefilter
2114
2125
2115 def handle_normal(self,line,continue_prompt=None,
2126 def handle_normal(self,line,continue_prompt=None,
2116 pre=None,iFun=None,theRest=None):
2127 pre=None,iFun=None,theRest=None):
2117 """Handle normal input lines. Use as a template for handlers."""
2128 """Handle normal input lines. Use as a template for handlers."""
2118
2129
2119 # With autoindent on, we need some way to exit the input loop, and I
2130 # With autoindent on, we need some way to exit the input loop, and I
2120 # don't want to force the user to have to backspace all the way to
2131 # don't want to force the user to have to backspace all the way to
2121 # clear the line. The rule will be in this case, that either two
2132 # clear the line. The rule will be in this case, that either two
2122 # lines of pure whitespace in a row, or a line of pure whitespace but
2133 # lines of pure whitespace in a row, or a line of pure whitespace but
2123 # of a size different to the indent level, will exit the input loop.
2134 # of a size different to the indent level, will exit the input loop.
2124
2135
2125 if (continue_prompt and self.autoindent and line.isspace() and
2136 if (continue_prompt and self.autoindent and line.isspace() and
2126 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2137 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2127 (self.buffer[-1]).isspace() )):
2138 (self.buffer[-1]).isspace() )):
2128 line = ''
2139 line = ''
2129
2140
2130 self.log(line,line,continue_prompt)
2141 self.log(line,line,continue_prompt)
2131 return line
2142 return line
2132
2143
2133 def handle_alias(self,line,continue_prompt=None,
2144 def handle_alias(self,line,continue_prompt=None,
2134 pre=None,iFun=None,theRest=None):
2145 pre=None,iFun=None,theRest=None):
2135 """Handle alias input lines. """
2146 """Handle alias input lines. """
2136
2147
2137 # pre is needed, because it carries the leading whitespace. Otherwise
2148 # pre is needed, because it carries the leading whitespace. Otherwise
2138 # aliases won't work in indented sections.
2149 # aliases won't work in indented sections.
2139 transformed = self.expand_aliases(iFun, theRest)
2150 transformed = self.expand_aliases(iFun, theRest)
2140 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2151 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2141 self.log(line,line_out,continue_prompt)
2152 self.log(line,line_out,continue_prompt)
2142 #print 'line out:',line_out # dbg
2153 #print 'line out:',line_out # dbg
2143 return line_out
2154 return line_out
2144
2155
2145 def handle_shell_escape(self, line, continue_prompt=None,
2156 def handle_shell_escape(self, line, continue_prompt=None,
2146 pre=None,iFun=None,theRest=None):
2157 pre=None,iFun=None,theRest=None):
2147 """Execute the line in a shell, empty return value"""
2158 """Execute the line in a shell, empty return value"""
2148
2159
2149 #print 'line in :', `line` # dbg
2160 #print 'line in :', `line` # dbg
2150 # Example of a special handler. Others follow a similar pattern.
2161 # Example of a special handler. Others follow a similar pattern.
2151 if line.lstrip().startswith('!!'):
2162 if line.lstrip().startswith('!!'):
2152 # rewrite iFun/theRest to properly hold the call to %sx and
2163 # rewrite iFun/theRest to properly hold the call to %sx and
2153 # the actual command to be executed, so handle_magic can work
2164 # the actual command to be executed, so handle_magic can work
2154 # correctly
2165 # correctly
2155 theRest = '%s %s' % (iFun[2:],theRest)
2166 theRest = '%s %s' % (iFun[2:],theRest)
2156 iFun = 'sx'
2167 iFun = 'sx'
2157 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2168 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2158 line.lstrip()[2:]),
2169 line.lstrip()[2:]),
2159 continue_prompt,pre,iFun,theRest)
2170 continue_prompt,pre,iFun,theRest)
2160 else:
2171 else:
2161 cmd=line.lstrip().lstrip('!')
2172 cmd=line.lstrip().lstrip('!')
2162 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2173 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2163 # update cache/log and return
2174 # update cache/log and return
2164 self.log(line,line_out,continue_prompt)
2175 self.log(line,line_out,continue_prompt)
2165 return line_out
2176 return line_out
2166
2177
2167 def handle_magic(self, line, continue_prompt=None,
2178 def handle_magic(self, line, continue_prompt=None,
2168 pre=None,iFun=None,theRest=None):
2179 pre=None,iFun=None,theRest=None):
2169 """Execute magic functions."""
2180 """Execute magic functions."""
2170
2181
2171
2182
2172 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2183 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2173 self.log(line,cmd,continue_prompt)
2184 self.log(line,cmd,continue_prompt)
2174 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2185 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2175 return cmd
2186 return cmd
2176
2187
2177 def handle_auto(self, line, continue_prompt=None,
2188 def handle_auto(self, line, continue_prompt=None,
2178 pre=None,iFun=None,theRest=None,obj=None):
2189 pre=None,iFun=None,theRest=None,obj=None):
2179 """Hande lines which can be auto-executed, quoting if requested."""
2190 """Hande lines which can be auto-executed, quoting if requested."""
2180
2191
2181 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2192 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2182
2193
2183 # This should only be active for single-line input!
2194 # This should only be active for single-line input!
2184 if continue_prompt:
2195 if continue_prompt:
2185 self.log(line,line,continue_prompt)
2196 self.log(line,line,continue_prompt)
2186 return line
2197 return line
2187
2198
2188 auto_rewrite = True
2199 auto_rewrite = True
2189
2200
2190 if pre == self.ESC_QUOTE:
2201 if pre == self.ESC_QUOTE:
2191 # Auto-quote splitting on whitespace
2202 # Auto-quote splitting on whitespace
2192 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2203 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2193 elif pre == self.ESC_QUOTE2:
2204 elif pre == self.ESC_QUOTE2:
2194 # Auto-quote whole string
2205 # Auto-quote whole string
2195 newcmd = '%s("%s")' % (iFun,theRest)
2206 newcmd = '%s("%s")' % (iFun,theRest)
2196 elif pre == self.ESC_PAREN:
2207 elif pre == self.ESC_PAREN:
2197 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2208 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2198 else:
2209 else:
2199 # Auto-paren.
2210 # Auto-paren.
2200 # We only apply it to argument-less calls if the autocall
2211 # We only apply it to argument-less calls if the autocall
2201 # parameter is set to 2. We only need to check that autocall is <
2212 # parameter is set to 2. We only need to check that autocall is <
2202 # 2, since this function isn't called unless it's at least 1.
2213 # 2, since this function isn't called unless it's at least 1.
2203 if not theRest and (self.rc.autocall < 2):
2214 if not theRest and (self.rc.autocall < 2):
2204 newcmd = '%s %s' % (iFun,theRest)
2215 newcmd = '%s %s' % (iFun,theRest)
2205 auto_rewrite = False
2216 auto_rewrite = False
2206 else:
2217 else:
2207 if theRest.startswith('['):
2218 if theRest.startswith('['):
2208 if hasattr(obj,'__getitem__'):
2219 if hasattr(obj,'__getitem__'):
2209 # Don't autocall in this case: item access for an object
2220 # Don't autocall in this case: item access for an object
2210 # which is BOTH callable and implements __getitem__.
2221 # which is BOTH callable and implements __getitem__.
2211 newcmd = '%s %s' % (iFun,theRest)
2222 newcmd = '%s %s' % (iFun,theRest)
2212 auto_rewrite = False
2223 auto_rewrite = False
2213 else:
2224 else:
2214 # if the object doesn't support [] access, go ahead and
2225 # if the object doesn't support [] access, go ahead and
2215 # autocall
2226 # autocall
2216 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2227 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2217 elif theRest.endswith(';'):
2228 elif theRest.endswith(';'):
2218 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2229 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2219 else:
2230 else:
2220 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2231 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2221
2232
2222 if auto_rewrite:
2233 if auto_rewrite:
2223 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2234 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2224 # log what is now valid Python, not the actual user input (without the
2235 # log what is now valid Python, not the actual user input (without the
2225 # final newline)
2236 # final newline)
2226 self.log(line,newcmd,continue_prompt)
2237 self.log(line,newcmd,continue_prompt)
2227 return newcmd
2238 return newcmd
2228
2239
2229 def handle_help(self, line, continue_prompt=None,
2240 def handle_help(self, line, continue_prompt=None,
2230 pre=None,iFun=None,theRest=None):
2241 pre=None,iFun=None,theRest=None):
2231 """Try to get some help for the object.
2242 """Try to get some help for the object.
2232
2243
2233 obj? or ?obj -> basic information.
2244 obj? or ?obj -> basic information.
2234 obj?? or ??obj -> more details.
2245 obj?? or ??obj -> more details.
2235 """
2246 """
2236
2247
2237 # We need to make sure that we don't process lines which would be
2248 # We need to make sure that we don't process lines which would be
2238 # otherwise valid python, such as "x=1 # what?"
2249 # otherwise valid python, such as "x=1 # what?"
2239 try:
2250 try:
2240 codeop.compile_command(line)
2251 codeop.compile_command(line)
2241 except SyntaxError:
2252 except SyntaxError:
2242 # We should only handle as help stuff which is NOT valid syntax
2253 # We should only handle as help stuff which is NOT valid syntax
2243 if line[0]==self.ESC_HELP:
2254 if line[0]==self.ESC_HELP:
2244 line = line[1:]
2255 line = line[1:]
2245 elif line[-1]==self.ESC_HELP:
2256 elif line[-1]==self.ESC_HELP:
2246 line = line[:-1]
2257 line = line[:-1]
2247 self.log(line,'#?'+line,continue_prompt)
2258 self.log(line,'#?'+line,continue_prompt)
2248 if line:
2259 if line:
2249 self.magic_pinfo(line)
2260 self.magic_pinfo(line)
2250 else:
2261 else:
2251 page(self.usage,screen_lines=self.rc.screen_length)
2262 page(self.usage,screen_lines=self.rc.screen_length)
2252 return '' # Empty string is needed here!
2263 return '' # Empty string is needed here!
2253 except:
2264 except:
2254 # Pass any other exceptions through to the normal handler
2265 # Pass any other exceptions through to the normal handler
2255 return self.handle_normal(line,continue_prompt)
2266 return self.handle_normal(line,continue_prompt)
2256 else:
2267 else:
2257 # If the code compiles ok, we should handle it normally
2268 # If the code compiles ok, we should handle it normally
2258 return self.handle_normal(line,continue_prompt)
2269 return self.handle_normal(line,continue_prompt)
2259
2270
2260 def getapi(self):
2271 def getapi(self):
2261 """ Get an IPApi object for this shell instance
2272 """ Get an IPApi object for this shell instance
2262
2273
2263 Getting an IPApi object is always preferable to accessing the shell
2274 Getting an IPApi object is always preferable to accessing the shell
2264 directly, but this holds true especially for extensions.
2275 directly, but this holds true especially for extensions.
2265
2276
2266 It should always be possible to implement an extension with IPApi
2277 It should always be possible to implement an extension with IPApi
2267 alone. If not, contact maintainer to request an addition.
2278 alone. If not, contact maintainer to request an addition.
2268
2279
2269 """
2280 """
2270 return self.api
2281 return self.api
2271
2282
2272 def handle_emacs(self,line,continue_prompt=None,
2283 def handle_emacs(self,line,continue_prompt=None,
2273 pre=None,iFun=None,theRest=None):
2284 pre=None,iFun=None,theRest=None):
2274 """Handle input lines marked by python-mode."""
2285 """Handle input lines marked by python-mode."""
2275
2286
2276 # Currently, nothing is done. Later more functionality can be added
2287 # Currently, nothing is done. Later more functionality can be added
2277 # here if needed.
2288 # here if needed.
2278
2289
2279 # The input cache shouldn't be updated
2290 # The input cache shouldn't be updated
2280
2291
2281 return line
2292 return line
2282
2293
2283 def mktempfile(self,data=None):
2294 def mktempfile(self,data=None):
2284 """Make a new tempfile and return its filename.
2295 """Make a new tempfile and return its filename.
2285
2296
2286 This makes a call to tempfile.mktemp, but it registers the created
2297 This makes a call to tempfile.mktemp, but it registers the created
2287 filename internally so ipython cleans it up at exit time.
2298 filename internally so ipython cleans it up at exit time.
2288
2299
2289 Optional inputs:
2300 Optional inputs:
2290
2301
2291 - data(None): if data is given, it gets written out to the temp file
2302 - data(None): if data is given, it gets written out to the temp file
2292 immediately, and the file is closed again."""
2303 immediately, and the file is closed again."""
2293
2304
2294 filename = tempfile.mktemp('.py','ipython_edit_')
2305 filename = tempfile.mktemp('.py','ipython_edit_')
2295 self.tempfiles.append(filename)
2306 self.tempfiles.append(filename)
2296
2307
2297 if data:
2308 if data:
2298 tmp_file = open(filename,'w')
2309 tmp_file = open(filename,'w')
2299 tmp_file.write(data)
2310 tmp_file.write(data)
2300 tmp_file.close()
2311 tmp_file.close()
2301 return filename
2312 return filename
2302
2313
2303 def write(self,data):
2314 def write(self,data):
2304 """Write a string to the default output"""
2315 """Write a string to the default output"""
2305 Term.cout.write(data)
2316 Term.cout.write(data)
2306
2317
2307 def write_err(self,data):
2318 def write_err(self,data):
2308 """Write a string to the default error output"""
2319 """Write a string to the default error output"""
2309 Term.cerr.write(data)
2320 Term.cerr.write(data)
2310
2321
2311 def exit(self):
2322 def exit(self):
2312 """Handle interactive exit.
2323 """Handle interactive exit.
2313
2324
2314 This method sets the exit_now attribute."""
2325 This method sets the exit_now attribute."""
2315
2326
2316 if self.rc.confirm_exit:
2327 if self.rc.confirm_exit:
2317 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2328 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2318 self.exit_now = True
2329 self.exit_now = True
2319 else:
2330 else:
2320 self.exit_now = True
2331 self.exit_now = True
2321
2332
2322 def safe_execfile(self,fname,*where,**kw):
2333 def safe_execfile(self,fname,*where,**kw):
2323 fname = os.path.expanduser(fname)
2334 fname = os.path.expanduser(fname)
2324
2335
2325 # find things also in current directory
2336 # find things also in current directory
2326 dname = os.path.dirname(fname)
2337 dname = os.path.dirname(fname)
2327 if not sys.path.count(dname):
2338 if not sys.path.count(dname):
2328 sys.path.append(dname)
2339 sys.path.append(dname)
2329
2340
2330 try:
2341 try:
2331 xfile = open(fname)
2342 xfile = open(fname)
2332 except:
2343 except:
2333 print >> Term.cerr, \
2344 print >> Term.cerr, \
2334 'Could not open file <%s> for safe execution.' % fname
2345 'Could not open file <%s> for safe execution.' % fname
2335 return None
2346 return None
2336
2347
2337 kw.setdefault('islog',0)
2348 kw.setdefault('islog',0)
2338 kw.setdefault('quiet',1)
2349 kw.setdefault('quiet',1)
2339 kw.setdefault('exit_ignore',0)
2350 kw.setdefault('exit_ignore',0)
2340 first = xfile.readline()
2351 first = xfile.readline()
2341 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2352 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2342 xfile.close()
2353 xfile.close()
2343 # line by line execution
2354 # line by line execution
2344 if first.startswith(loghead) or kw['islog']:
2355 if first.startswith(loghead) or kw['islog']:
2345 print 'Loading log file <%s> one line at a time...' % fname
2356 print 'Loading log file <%s> one line at a time...' % fname
2346 if kw['quiet']:
2357 if kw['quiet']:
2347 stdout_save = sys.stdout
2358 stdout_save = sys.stdout
2348 sys.stdout = StringIO.StringIO()
2359 sys.stdout = StringIO.StringIO()
2349 try:
2360 try:
2350 globs,locs = where[0:2]
2361 globs,locs = where[0:2]
2351 except:
2362 except:
2352 try:
2363 try:
2353 globs = locs = where[0]
2364 globs = locs = where[0]
2354 except:
2365 except:
2355 globs = locs = globals()
2366 globs = locs = globals()
2356 badblocks = []
2367 badblocks = []
2357
2368
2358 # we also need to identify indented blocks of code when replaying
2369 # we also need to identify indented blocks of code when replaying
2359 # logs and put them together before passing them to an exec
2370 # logs and put them together before passing them to an exec
2360 # statement. This takes a bit of regexp and look-ahead work in the
2371 # statement. This takes a bit of regexp and look-ahead work in the
2361 # file. It's easiest if we swallow the whole thing in memory
2372 # file. It's easiest if we swallow the whole thing in memory
2362 # first, and manually walk through the lines list moving the
2373 # first, and manually walk through the lines list moving the
2363 # counter ourselves.
2374 # counter ourselves.
2364 indent_re = re.compile('\s+\S')
2375 indent_re = re.compile('\s+\S')
2365 xfile = open(fname)
2376 xfile = open(fname)
2366 filelines = xfile.readlines()
2377 filelines = xfile.readlines()
2367 xfile.close()
2378 xfile.close()
2368 nlines = len(filelines)
2379 nlines = len(filelines)
2369 lnum = 0
2380 lnum = 0
2370 while lnum < nlines:
2381 while lnum < nlines:
2371 line = filelines[lnum]
2382 line = filelines[lnum]
2372 lnum += 1
2383 lnum += 1
2373 # don't re-insert logger status info into cache
2384 # don't re-insert logger status info into cache
2374 if line.startswith('#log#'):
2385 if line.startswith('#log#'):
2375 continue
2386 continue
2376 else:
2387 else:
2377 # build a block of code (maybe a single line) for execution
2388 # build a block of code (maybe a single line) for execution
2378 block = line
2389 block = line
2379 try:
2390 try:
2380 next = filelines[lnum] # lnum has already incremented
2391 next = filelines[lnum] # lnum has already incremented
2381 except:
2392 except:
2382 next = None
2393 next = None
2383 while next and indent_re.match(next):
2394 while next and indent_re.match(next):
2384 block += next
2395 block += next
2385 lnum += 1
2396 lnum += 1
2386 try:
2397 try:
2387 next = filelines[lnum]
2398 next = filelines[lnum]
2388 except:
2399 except:
2389 next = None
2400 next = None
2390 # now execute the block of one or more lines
2401 # now execute the block of one or more lines
2391 try:
2402 try:
2392 exec block in globs,locs
2403 exec block in globs,locs
2393 except SystemExit:
2404 except SystemExit:
2394 pass
2405 pass
2395 except:
2406 except:
2396 badblocks.append(block.rstrip())
2407 badblocks.append(block.rstrip())
2397 if kw['quiet']: # restore stdout
2408 if kw['quiet']: # restore stdout
2398 sys.stdout.close()
2409 sys.stdout.close()
2399 sys.stdout = stdout_save
2410 sys.stdout = stdout_save
2400 print 'Finished replaying log file <%s>' % fname
2411 print 'Finished replaying log file <%s>' % fname
2401 if badblocks:
2412 if badblocks:
2402 print >> sys.stderr, ('\nThe following lines/blocks in file '
2413 print >> sys.stderr, ('\nThe following lines/blocks in file '
2403 '<%s> reported errors:' % fname)
2414 '<%s> reported errors:' % fname)
2404
2415
2405 for badline in badblocks:
2416 for badline in badblocks:
2406 print >> sys.stderr, badline
2417 print >> sys.stderr, badline
2407 else: # regular file execution
2418 else: # regular file execution
2408 try:
2419 try:
2409 execfile(fname,*where)
2420 execfile(fname,*where)
2410 except SyntaxError:
2421 except SyntaxError:
2411 self.showsyntaxerror()
2422 self.showsyntaxerror()
2412 warn('Failure executing file: <%s>' % fname)
2423 warn('Failure executing file: <%s>' % fname)
2413 except SystemExit,status:
2424 except SystemExit,status:
2414 if not kw['exit_ignore']:
2425 if not kw['exit_ignore']:
2415 self.showtraceback()
2426 self.showtraceback()
2416 warn('Failure executing file: <%s>' % fname)
2427 warn('Failure executing file: <%s>' % fname)
2417 except:
2428 except:
2418 self.showtraceback()
2429 self.showtraceback()
2419 warn('Failure executing file: <%s>' % fname)
2430 warn('Failure executing file: <%s>' % fname)
2420
2431
2421 #************************* end of file <iplib.py> *****************************
2432 #************************* end of file <iplib.py> *****************************
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