##// END OF EJS Templates
Cleaned up embedded shell and added cleanup method to InteractiveShell....
Brian Granger -
Show More
@@ -1,62 +1,64 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 IPython.
4 IPython.
5
5
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 IPython is a set of tools for interactive and exploratory computing in Python.
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2009 The IPython Development Team
10 # Copyright (C) 2008-2009 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import os
20 import os
21 import sys
21 import sys
22 from IPython.core import release
22 from IPython.core import release
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Setup everything
25 # Setup everything
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 if sys.version[0:3] < '2.4':
29 if sys.version[0:3] < '2.4':
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
31
31
32
32
33 # Make it easy to import extensions - they are always directly on pythonpath.
33 # Make it easy to import extensions - they are always directly on pythonpath.
34 # Therefore, non-IPython modules can be added to extensions directory
34 # Therefore, non-IPython modules can be added to extensions directory
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Setup the top level names
38 # Setup the top level names
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 # In some cases, these are causing circular imports.
41 from IPython.core.iplib import InteractiveShell
42 from IPython.core.iplib import InteractiveShell
43 from IPython.core.embed import embed
42 from IPython.core.error import TryNext
44 from IPython.core.error import TryNext
43
45
44 from IPython.lib import (
46 from IPython.lib import (
45 enable_wx, disable_wx,
47 enable_wx, disable_wx,
46 enable_gtk, disable_gtk,
48 enable_gtk, disable_gtk,
47 enable_qt4, disable_qt4,
49 enable_qt4, disable_qt4,
48 enable_tk, disable_tk,
50 enable_tk, disable_tk,
49 set_inputhook, clear_inputhook,
51 set_inputhook, clear_inputhook,
50 current_gui, spin,
52 current_gui, spin,
51 appstart_qt4, appstart_wx,
53 appstart_qt4, appstart_wx,
52 appstart_gtk, appstart_tk
54 appstart_gtk, appstart_tk
53 )
55 )
54
56
55 # Release data
57 # Release data
56 __author__ = ''
58 __author__ = ''
57 for author, email in release.authors.values():
59 for author, email in release.authors.values():
58 __author__ += author + ' <' + email + '>\n'
60 __author__ += author + ' <' + email + '>\n'
59 __license__ = release.license
61 __license__ = release.license
60 __version__ = release.version
62 __version__ = release.version
61 __revision__ = release.revision
63 __revision__ = release.revision
62
64
@@ -1,229 +1,229 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
4
5 Authors
5 Authors
6 -------
6 -------
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 #****************************************************************************
18 #****************************************************************************
19 # 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 pformat
24 from pprint import pformat
25
25
26 # Our own
26 # Our own
27 from IPython.core import release
27 from IPython.core import release
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.external.Itpl import itpl
29 from IPython.external.Itpl import itpl
30
30
31 from IPython.utils.genutils import *
31 from IPython.utils.genutils import *
32
32
33 #****************************************************************************
33 #****************************************************************************
34 class CrashHandler:
34 class CrashHandler:
35 """Customizable crash handlers for IPython-based systems.
35 """Customizable crash handlers for IPython-based systems.
36
36
37 Instances of this class provide a __call__ method which can be used as a
37 Instances of this class provide a __call__ method which can be used as a
38 sys.excepthook, i.e., the __call__ signature is:
38 sys.excepthook, i.e., the __call__ signature is:
39
39
40 def __call__(self,etype, evalue, etb)
40 def __call__(self,etype, evalue, etb)
41
41
42 """
42 """
43
43
44 def __init__(self,IP,app_name,contact_name,contact_email,
44 def __init__(self,IP,app_name,contact_name,contact_email,
45 bug_tracker,crash_report_fname,
45 bug_tracker,crash_report_fname,
46 show_crash_traceback=True):
46 show_crash_traceback=True):
47 """New crash handler.
47 """New crash handler.
48
48
49 Inputs:
49 Inputs:
50
50
51 - IP: a running IPython instance, which will be queried at crash time
51 - IP: a running IPython instance, which will be queried at crash time
52 for internal information.
52 for internal information.
53
53
54 - app_name: a string containing the name of your application.
54 - app_name: a string containing the name of your application.
55
55
56 - contact_name: a string with the name of the person to contact.
56 - contact_name: a string with the name of the person to contact.
57
57
58 - contact_email: a string with the email address of the contact.
58 - contact_email: a string with the email address of the contact.
59
59
60 - bug_tracker: a string with the URL for your project's bug tracker.
60 - bug_tracker: a string with the URL for your project's bug tracker.
61
61
62 - crash_report_fname: a string with the filename for the crash report
62 - crash_report_fname: a string with the filename for the crash report
63 to be saved in. These reports are left in the ipython user directory
63 to be saved in. These reports are left in the ipython user directory
64 as determined by the running IPython instance.
64 as determined by the running IPython instance.
65
65
66 Optional inputs:
66 Optional inputs:
67
67
68 - show_crash_traceback(True): if false, don't print the crash
68 - show_crash_traceback(True): if false, don't print the crash
69 traceback on stderr, only generate the on-disk report
69 traceback on stderr, only generate the on-disk report
70
70
71
71
72 Non-argument instance attributes:
72 Non-argument instance attributes:
73
73
74 These instances contain some non-argument attributes which allow for
74 These instances contain some non-argument attributes which allow for
75 further customization of the crash handler's behavior. Please see the
75 further customization of the crash handler's behavior. Please see the
76 source for further details.
76 source for further details.
77 """
77 """
78
78
79 # apply args into instance
79 # apply args into instance
80 self.IP = IP # IPython instance
80 self.IP = IP # IPython instance
81 self.app_name = app_name
81 self.app_name = app_name
82 self.contact_name = contact_name
82 self.contact_name = contact_name
83 self.contact_email = contact_email
83 self.contact_email = contact_email
84 self.bug_tracker = bug_tracker
84 self.bug_tracker = bug_tracker
85 self.crash_report_fname = crash_report_fname
85 self.crash_report_fname = crash_report_fname
86 self.show_crash_traceback = show_crash_traceback
86 self.show_crash_traceback = show_crash_traceback
87
87
88 # Hardcoded defaults, which can be overridden either by subclasses or
88 # Hardcoded defaults, which can be overridden either by subclasses or
89 # at runtime for the instance.
89 # at runtime for the instance.
90
90
91 # Template for the user message. Subclasses which completely override
91 # Template for the user message. Subclasses which completely override
92 # this, or user apps, can modify it to suit their tastes. It gets
92 # this, or user apps, can modify it to suit their tastes. It gets
93 # expanded using itpl, so calls of the kind $self.foo are valid.
93 # expanded using itpl, so calls of the kind $self.foo are valid.
94 self.user_message_template = """
94 self.user_message_template = """
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
96
96
97 A crash report was automatically generated with the following information:
97 A crash report was automatically generated with the following information:
98 - A verbatim copy of the crash traceback.
98 - A verbatim copy of the crash traceback.
99 - A copy of your input history during this session.
99 - A copy of your input history during this session.
100 - Data on your current $self.app_name configuration.
100 - Data on your current $self.app_name configuration.
101
101
102 It was left in the file named:
102 It was left in the file named:
103 \t'$self.crash_report_fname'
103 \t'$self.crash_report_fname'
104 If you can email this file to the developers, the information in it will help
104 If you can email this file to the developers, the information in it will help
105 them in understanding and correcting the problem.
105 them in understanding and correcting the problem.
106
106
107 You can mail it to: $self.contact_name at $self.contact_email
107 You can mail it to: $self.contact_name at $self.contact_email
108 with the subject '$self.app_name Crash Report'.
108 with the subject '$self.app_name Crash Report'.
109
109
110 If you want to do it now, the following command will work (under Unix):
110 If you want to do it now, the following command will work (under Unix):
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
112
112
113 To ensure accurate tracking of this issue, please file a report about it at:
113 To ensure accurate tracking of this issue, please file a report about it at:
114 $self.bug_tracker
114 $self.bug_tracker
115 """
115 """
116
116
117 def __call__(self,etype, evalue, etb):
117 def __call__(self,etype, evalue, etb):
118 """Handle an exception, call for compatible with sys.excepthook"""
118 """Handle an exception, call for compatible with sys.excepthook"""
119
119
120 # Report tracebacks shouldn't use color in general (safer for users)
120 # Report tracebacks shouldn't use color in general (safer for users)
121 color_scheme = 'NoColor'
121 color_scheme = 'NoColor'
122
122
123 # Use this ONLY for developer debugging (keep commented out for release)
123 # Use this ONLY for developer debugging (keep commented out for release)
124 #color_scheme = 'Linux' # dbg
124 #color_scheme = 'Linux' # dbg
125
125
126 try:
126 try:
127 rptdir = self.IP.config.IPYTHONDIR
127 rptdir = self.IP.config.IPYTHONDIR
128 except:
128 except:
129 rptdir = os.getcwd()
129 rptdir = os.getcwd()
130 if not os.path.isdir(rptdir):
130 if not os.path.isdir(rptdir):
131 rptdir = os.getcwd()
131 rptdir = os.getcwd()
132 report_name = os.path.join(rptdir,self.crash_report_fname)
132 report_name = os.path.join(rptdir,self.crash_report_fname)
133 # write the report filename into the instance dict so it can get
133 # write the report filename into the instance dict so it can get
134 # properly expanded out in the user message template
134 # properly expanded out in the user message template
135 self.crash_report_fname = report_name
135 self.crash_report_fname = report_name
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
137 long_header=1)
137 long_header=1)
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
139
139
140 # print traceback to screen
140 # print traceback to screen
141 if self.show_crash_traceback:
141 if self.show_crash_traceback:
142 print >> sys.stderr, traceback
142 print >> sys.stderr, traceback
143
143
144 # and generate a complete report on disk
144 # and generate a complete report on disk
145 try:
145 try:
146 report = open(report_name,'w')
146 report = open(report_name,'w')
147 except:
147 except:
148 print >> sys.stderr, 'Could not create crash report on disk.'
148 print >> sys.stderr, 'Could not create crash report on disk.'
149 return
149 return
150
150
151 # Inform user on stderr of what happened
151 # Inform user on stderr of what happened
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
153 print >> sys.stderr, msg
153 print >> sys.stderr, msg
154
154
155 # Construct report on disk
155 # Construct report on disk
156 report.write(self.make_report(traceback))
156 report.write(self.make_report(traceback))
157 report.close()
157 report.close()
158 raw_input("Press enter to exit:")
158 raw_input("Press enter to exit:")
159
159
160 def make_report(self,traceback):
160 def make_report(self,traceback):
161 """Return a string containing a crash report."""
161 """Return a string containing a crash report."""
162
162
163 sec_sep = '\n\n'+'*'*75+'\n\n'
163 sec_sep = '\n\n'+'*'*75+'\n\n'
164
164
165 report = []
165 report = []
166 rpt_add = report.append
166 rpt_add = report.append
167
167
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
169 rpt_add('IPython version: %s \n\n' % release.version)
169 rpt_add('IPython version: %s \n\n' % release.version)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
172 (os.name,sys.platform) )
172 (os.name,sys.platform) )
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
174 rpt_add(pformat(self.IP.dict()))
174 rpt_add(pformat(self.IP.dict()))
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 try:
176 try:
177 rpt_add(sec_sep+"History of session input:")
177 rpt_add(sec_sep+"History of session input:")
178 for line in self.IP.user_ns['_ih']:
178 for line in self.IP.user_ns['_ih']:
179 rpt_add(line)
179 rpt_add(line)
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
181 rpt_add(self.IP._last_input_line+'\n')
181 rpt_add(self.IP._last_input_line+'\n')
182 except:
182 except:
183 pass
183 pass
184
184
185 return ''.join(report)
185 return ''.join(report)
186
186
187 class IPythonCrashHandler(CrashHandler):
187 class IPythonCrashHandler(CrashHandler):
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
189
189
190 def __init__(self,IP):
190 def __init__(self,IP):
191
191
192 # Set here which of the IPython authors should be listed as contact
192 # Set here which of the IPython authors should be listed as contact
193 AUTHOR_CONTACT = 'Fernando'
193 AUTHOR_CONTACT = 'Fernando'
194
194
195 # Set argument defaults
195 # Set argument defaults
196 app_name = 'IPython'
196 app_name = 'IPython'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
199 crash_report_fname = 'IPython_crash_report.txt'
199 crash_report_fname = 'IPython_crash_report.txt'
200 # Call parent constructor
200 # Call parent constructor
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
202 bug_tracker,crash_report_fname)
202 bug_tracker,crash_report_fname)
203
203
204 def make_report(self,traceback):
204 def make_report(self,traceback):
205 """Return a string containing a crash report."""
205 """Return a string containing a crash report."""
206
206
207 sec_sep = '\n\n'+'*'*75+'\n\n'
207 sec_sep = '\n\n'+'*'*75+'\n\n'
208
208
209 report = []
209 report = []
210 rpt_add = report.append
210 rpt_add = report.append
211
211
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
213 rpt_add('IPython version: %s \n\n' % release.version)
213 rpt_add('IPython version: %s \n\n' % release.version)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
216 (os.name,sys.platform) )
216 (os.name,sys.platform) )
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
218 rpt_add(pformat(self.IP.dict()))
218 # rpt_add(pformat(self.IP.dict()))
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
220 try:
220 try:
221 rpt_add(sec_sep+"History of session input:")
221 rpt_add(sec_sep+"History of session input:")
222 for line in self.IP.user_ns['_ih']:
222 for line in self.IP.user_ns['_ih']:
223 rpt_add(line)
223 rpt_add(line)
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
225 rpt_add(self.IP._last_input_line+'\n')
225 rpt_add(self.IP._last_input_line+'\n')
226 except:
226 except:
227 pass
227 pass
228
228
229 return ''.join(report)
229 return ''.join(report)
@@ -1,176 +1,215 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An embedded IPython shell.
4 An embedded IPython shell.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import sys
26 import sys
27
27
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.core.iplib import InteractiveShell
29 from IPython.core.iplib import InteractiveShell
30
30
31 from IPython.utils.traitlets import Bool, Str
31 from IPython.utils.traitlets import Bool, Str, CBool
32 from IPython.utils.genutils import ask_yes_no
32 from IPython.utils.genutils import ask_yes_no
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Classes and functions
35 # Classes and functions
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 # This is an additional magic that is exposed in embedded shells.
38 # This is an additional magic that is exposed in embedded shells.
39 def kill_embedded(self,parameter_s=''):
39 def kill_embedded(self,parameter_s=''):
40 """%kill_embedded : deactivate for good the current embedded IPython.
40 """%kill_embedded : deactivate for good the current embedded IPython.
41
41
42 This function (after asking for confirmation) sets an internal flag so that
42 This function (after asking for confirmation) sets an internal flag so that
43 an embedded IPython will never activate again. This is useful to
43 an embedded IPython will never activate again. This is useful to
44 permanently disable a shell that is being called inside a loop: once you've
44 permanently disable a shell that is being called inside a loop: once you've
45 figured out what you needed from it, you may then kill it and the program
45 figured out what you needed from it, you may then kill it and the program
46 will then continue to run without the interactive shell interfering again.
46 will then continue to run without the interactive shell interfering again.
47 """
47 """
48
48
49 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
49 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
50 "(y/n)? [y/N] ",'n')
50 "(y/n)? [y/N] ",'n')
51 if kill:
51 if kill:
52 self.embedded_active = False
52 self.embedded_active = False
53 print "This embedded IPython will not reactivate anymore once you exit."
53 print "This embedded IPython will not reactivate anymore once you exit."
54
54
55
55
56 class InteractiveShellEmbed(InteractiveShell):
56 class InteractiveShellEmbed(InteractiveShell):
57
57
58 dummy_mode = Bool(False)
58 dummy_mode = Bool(False)
59 exit_msg = Str('')
59 exit_msg = Str('')
60 embedded = CBool(True)
61 embedded_active = CBool(True)
60
62
61 def __init__(self, parent=None, config=None, usage=None,
63 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
62 user_ns=None, user_global_ns=None,
64 user_ns=None, user_global_ns=None,
63 banner1='', banner2='',
65 banner1=None, banner2=None,
64 custom_exceptions=((),None), exit_msg=''):
66 custom_exceptions=((),None), exit_msg=None):
65
67
66 # First we need to save the state of sys.displayhook and
68 # First we need to save the state of sys.displayhook and
67 # sys.ipcompleter so we can restore it when we are done.
69 # sys.ipcompleter so we can restore it when we are done.
68 self.save_sys_displayhook()
70 self.save_sys_displayhook()
69 self.save_sys_ipcompleter()
71 self.save_sys_ipcompleter()
70
72
71 super(InteractiveShellEmbed,self).__init__(
73 super(InteractiveShellEmbed,self).__init__(
72 parent=parent, config=config, usage=usage,
74 parent=parent, config=config, ipythondir=ipythondir, usage=usage,
73 user_ns=user_ns, user_global_ns=user_global_ns,
75 user_ns=user_ns, user_global_ns=user_global_ns,
74 banner1=banner1, banner2=banner2,
76 banner1=banner1, banner2=banner2,
75 custom_exceptions=custom_exceptions, embedded=True)
77 custom_exceptions=custom_exceptions)
76
78
77 self.save_sys_displayhook_embed()
79 self.save_sys_displayhook_embed()
78 self.exit_msg = exit_msg
80 self.exit_msg = exit_msg
79 self.define_magic("kill_embedded", kill_embedded)
81 self.define_magic("kill_embedded", kill_embedded)
80
82
81 # don't use the ipython crash handler so that user exceptions aren't
83 # don't use the ipython crash handler so that user exceptions aren't
82 # trapped
84 # trapped
83 sys.excepthook = ultratb.FormattedTB(color_scheme = self.colors,
85 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
84 mode = self.xmode,
86 mode=self.xmode,
85 call_pdb = self.pdb)
87 call_pdb=self.pdb)
86
88
87 self.restore_sys_displayhook()
89 self.restore_sys_displayhook()
88 self.restore_sys_ipcompleter()
90 self.restore_sys_ipcompleter()
89
91
92 def init_sys_modules(self):
93 pass
94
90 def save_sys_displayhook(self):
95 def save_sys_displayhook(self):
91 # sys.displayhook is a global, we need to save the user's original
96 # sys.displayhook is a global, we need to save the user's original
92 # Don't rely on __displayhook__, as the user may have changed that.
97 # Don't rely on __displayhook__, as the user may have changed that.
93 self.sys_displayhook_orig = sys.displayhook
98 self.sys_displayhook_orig = sys.displayhook
94
99
95 def save_sys_ipcompleter(self):
100 def save_sys_ipcompleter(self):
96 """Save readline completer status."""
101 """Save readline completer status."""
97 try:
102 try:
98 #print 'Save completer',sys.ipcompleter # dbg
103 #print 'Save completer',sys.ipcompleter # dbg
99 self.sys_ipcompleter_orig = sys.ipcompleter
104 self.sys_ipcompleter_orig = sys.ipcompleter
100 except:
105 except:
101 pass # not nested with IPython
106 pass # not nested with IPython
102
107
103 def restore_sys_displayhook(self):
108 def restore_sys_displayhook(self):
104 sys.displayhook = self.sys_displayhook_orig
109 sys.displayhook = self.sys_displayhook_orig
105
110
106 def restore_sys_ipcompleter(self):
111 def restore_sys_ipcompleter(self):
107 """Restores the readline completer which was in place.
112 """Restores the readline completer which was in place.
108
113
109 This allows embedded IPython within IPython not to disrupt the
114 This allows embedded IPython within IPython not to disrupt the
110 parent's completion.
115 parent's completion.
111 """
116 """
112 try:
117 try:
113 self.readline.set_completer(self.sys_ipcompleter_orig)
118 self.readline.set_completer(self.sys_ipcompleter_orig)
114 sys.ipcompleter = self.sys_ipcompleter_orig
119 sys.ipcompleter = self.sys_ipcompleter_orig
115 except:
120 except:
116 pass
121 pass
117
122
118 def save_sys_displayhook_embed(self):
123 def save_sys_displayhook_embed(self):
119 self.sys_displayhook_embed = sys.displayhook
124 self.sys_displayhook_embed = sys.displayhook
120
125
121 def restore_sys_displayhook_embed(self):
126 def restore_sys_displayhook_embed(self):
122 sys.displayhook = self.sys_displayhook_embed
127 sys.displayhook = self.sys_displayhook_embed
123
128
124 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None):
129 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
130 stack_depth=1):
125 """Activate the interactive interpreter.
131 """Activate the interactive interpreter.
126
132
127 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
133 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
128 the interpreter shell with the given local and global namespaces, and
134 the interpreter shell with the given local and global namespaces, and
129 optionally print a header string at startup.
135 optionally print a header string at startup.
130
136
131 The shell can be globally activated/deactivated using the
137 The shell can be globally activated/deactivated using the
132 set/get_dummy_mode methods. This allows you to turn off a shell used
138 set/get_dummy_mode methods. This allows you to turn off a shell used
133 for debugging globally.
139 for debugging globally.
134
140
135 However, *each* time you call the shell you can override the current
141 However, *each* time you call the shell you can override the current
136 state of dummy_mode with the optional keyword parameter 'dummy'. For
142 state of dummy_mode with the optional keyword parameter 'dummy'. For
137 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
143 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
138 can still have a specific call work by making it as IPShell(dummy=0).
144 can still have a specific call work by making it as IPShell(dummy=0).
139
145
140 The optional keyword parameter dummy controls whether the call
146 The optional keyword parameter dummy controls whether the call
141 actually does anything.
147 actually does anything.
142 """
148 """
143
149
144 # If the user has turned it off, go away
150 # If the user has turned it off, go away
145 if not self.embedded_active:
151 if not self.embedded_active:
146 return
152 return
147
153
148 # Normal exits from interactive mode set this flag, so the shell can't
154 # Normal exits from interactive mode set this flag, so the shell can't
149 # re-enter (it checks this variable at the start of interactive mode).
155 # re-enter (it checks this variable at the start of interactive mode).
150 self.exit_now = False
156 self.exit_now = False
151
157
152 # Allow the dummy parameter to override the global __dummy_mode
158 # Allow the dummy parameter to override the global __dummy_mode
153 if dummy or (dummy != 0 and self.dummy_mode):
159 if dummy or (dummy != 0 and self.dummy_mode):
154 return
160 return
155
161
156 self.restore_sys_displayhook_embed()
162 self.restore_sys_displayhook_embed()
157
163
158 if self.has_readline:
164 if self.has_readline:
159 self.set_completer()
165 self.set_completer()
160
166
161 if self.banner and header:
167 if self.banner and header:
162 format = '%s\n%s\n'
168 format = '%s\n%s\n'
163 else:
169 else:
164 format = '%s%s\n'
170 format = '%s%s\n'
165 banner = format % (self.banner,header)
171 banner = format % (self.banner,header)
166
172
167 # Call the embedding code with a stack depth of 1 so it can skip over
173 # Call the embedding code with a stack depth of 1 so it can skip over
168 # our call and get the original caller's namespaces.
174 # our call and get the original caller's namespaces.
169 self.embed_mainloop(banner, local_ns, global_ns, stack_depth=1)
175 self.embed_mainloop(banner, local_ns, global_ns,
176 stack_depth=stack_depth)
170
177
171 if self.exit_msg:
178 if self.exit_msg is not None:
172 print self.exit_msg
179 print self.exit_msg
173
180
174 # Restore global systems (display, completion)
181 # Restore global systems (display, completion)
175 self.restore_sys_displayhook()
182 self.restore_sys_displayhook()
176 self.restore_sys_ipcompleter()
183 self.restore_sys_ipcompleter()
184
185
186 _embedded_shell = None
187
188
189 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
190 exit_msg=''):
191 """Call this to embed IPython at the current point in your program.
192
193 The first invocation of this will create an :class:`InteractiveShellEmbed`
194 instance and then call it. Consecutive calls just call the already
195 created instance.
196
197 Here is a simple example::
198
199 from IPython import embed
200 a = 10
201 b = 20
202 embed('First time')
203 c = 30
204 d = 40
205 embed
206
207 Full customization can be done by passing a :class:`Struct` in as the
208 config argument.
209 """
210 global _embedded_shell
211 if _embedded_shell is None:
212 _embedded_shell = InteractiveShellEmbed(config=config,
213 usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg)
214 _embedded_shell(header=header, stack_depth=2)
215
@@ -1,264 +1,274 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 import os, bisect
44 import os, bisect
45 import sys
45 import sys
46 from IPython.utils.genutils import Term, shell
46 from IPython.utils.genutils import Term, shell
47 from pprint import PrettyPrinter
47 from pprint import PrettyPrinter
48
48
49 from IPython.core.error import TryNext
49 from IPython.core.error import TryNext
50
50
51 # List here all the default hooks. For now it's just the editor functions
51 # List here all the default hooks. For now it's just the editor functions
52 # but over time we'll move here all the public API for user-accessible things.
52 # but over time we'll move here all the public API for user-accessible things.
53 # vds: >>
53
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
56 'generate_prompt', 'generate_output_prompt','shell_hook',
56 'generate_prompt', 'generate_output_prompt','shell_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
58 'clipboard_get']
58 'clipboard_get']
59 # vds: <<
60
59
61 pformat = PrettyPrinter().pformat
60 pformat = PrettyPrinter().pformat
62
61
63 def editor(self,filename, linenum=None):
62 def editor(self,filename, linenum=None):
64 """Open the default editor at the given filename and linenumber.
63 """Open the default editor at the given filename and linenumber.
65
64
66 This is IPython's default editor hook, you can use it as an example to
65 This is IPython's default editor hook, you can use it as an example to
67 write your own modified one. To set your own editor function as the
66 write your own modified one. To set your own editor function as the
68 new editor hook, call ip.set_hook('editor',yourfunc)."""
67 new editor hook, call ip.set_hook('editor',yourfunc)."""
69
68
70 # IPython configures a default editor at startup by reading $EDITOR from
69 # IPython configures a default editor at startup by reading $EDITOR from
71 # the environment, and falling back on vi (unix) or notepad (win32).
70 # the environment, and falling back on vi (unix) or notepad (win32).
72 editor = self.editor
71 editor = self.editor
73
72
74 # marker for at which line to open the file (for existing objects)
73 # marker for at which line to open the file (for existing objects)
75 if linenum is None or editor=='notepad':
74 if linenum is None or editor=='notepad':
76 linemark = ''
75 linemark = ''
77 else:
76 else:
78 linemark = '+%d' % int(linenum)
77 linemark = '+%d' % int(linenum)
79
78
80 # Enclose in quotes if necessary and legal
79 # Enclose in quotes if necessary and legal
81 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
80 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
82 editor = '"%s"' % editor
81 editor = '"%s"' % editor
83
82
84 # Call the actual editor
83 # Call the actual editor
85 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
84 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
86 raise TryNext()
85 raise TryNext()
87
86
88 import tempfile
87 import tempfile
89 def fix_error_editor(self,filename,linenum,column,msg):
88 def fix_error_editor(self,filename,linenum,column,msg):
90 """Open the editor at the given filename, linenumber, column and
89 """Open the editor at the given filename, linenumber, column and
91 show an error message. This is used for correcting syntax errors.
90 show an error message. This is used for correcting syntax errors.
92 The current implementation only has special support for the VIM editor,
91 The current implementation only has special support for the VIM editor,
93 and falls back on the 'editor' hook if VIM is not used.
92 and falls back on the 'editor' hook if VIM is not used.
94
93
95 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
94 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
96 """
95 """
97 def vim_quickfix_file():
96 def vim_quickfix_file():
98 t = tempfile.NamedTemporaryFile()
97 t = tempfile.NamedTemporaryFile()
99 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
98 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
100 t.flush()
99 t.flush()
101 return t
100 return t
102 if os.path.basename(self.editor) != 'vim':
101 if os.path.basename(self.editor) != 'vim':
103 self.hooks.editor(filename,linenum)
102 self.hooks.editor(filename,linenum)
104 return
103 return
105 t = vim_quickfix_file()
104 t = vim_quickfix_file()
106 try:
105 try:
107 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
106 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
108 raise TryNext()
107 raise TryNext()
109 finally:
108 finally:
110 t.close()
109 t.close()
111
110
112 # vds: >>
111
113 def synchronize_with_editor(self, filename, linenum, column):
112 def synchronize_with_editor(self, filename, linenum, column):
114 pass
113 pass
115 # vds: <<
114
116
115
117 class CommandChainDispatcher:
116 class CommandChainDispatcher:
118 """ Dispatch calls to a chain of commands until some func can handle it
117 """ Dispatch calls to a chain of commands until some func can handle it
119
118
120 Usage: instantiate, execute "add" to add commands (with optional
119 Usage: instantiate, execute "add" to add commands (with optional
121 priority), execute normally via f() calling mechanism.
120 priority), execute normally via f() calling mechanism.
122
121
123 """
122 """
124 def __init__(self,commands=None):
123 def __init__(self,commands=None):
125 if commands is None:
124 if commands is None:
126 self.chain = []
125 self.chain = []
127 else:
126 else:
128 self.chain = commands
127 self.chain = commands
129
128
130
129
131 def __call__(self,*args, **kw):
130 def __call__(self,*args, **kw):
132 """ Command chain is called just like normal func.
131 """ Command chain is called just like normal func.
133
132
134 This will call all funcs in chain with the same args as were given to this
133 This will call all funcs in chain with the same args as were given to this
135 function, and return the result of first func that didn't raise
134 function, and return the result of first func that didn't raise
136 TryNext """
135 TryNext """
137
136
138 for prio,cmd in self.chain:
137 for prio,cmd in self.chain:
139 #print "prio",prio,"cmd",cmd #dbg
138 #print "prio",prio,"cmd",cmd #dbg
140 try:
139 try:
141 ret = cmd(*args, **kw)
140 ret = cmd(*args, **kw)
142 return ret
141 return ret
143 except TryNext, exc:
142 except TryNext, exc:
144 if exc.args or exc.kwargs:
143 if exc.args or exc.kwargs:
145 args = exc.args
144 args = exc.args
146 kw = exc.kwargs
145 kw = exc.kwargs
147 # if no function will accept it, raise TryNext up to the caller
146 # if no function will accept it, raise TryNext up to the caller
148 raise TryNext
147 raise TryNext
149
148
150 def __str__(self):
149 def __str__(self):
151 return str(self.chain)
150 return str(self.chain)
152
151
153 def add(self, func, priority=0):
152 def add(self, func, priority=0):
154 """ Add a func to the cmd chain with given priority """
153 """ Add a func to the cmd chain with given priority """
155 bisect.insort(self.chain,(priority,func))
154 bisect.insort(self.chain,(priority,func))
156
155
157 def __iter__(self):
156 def __iter__(self):
158 """ Return all objects in chain.
157 """ Return all objects in chain.
159
158
160 Handy if the objects are not callable.
159 Handy if the objects are not callable.
161 """
160 """
162 return iter(self.chain)
161 return iter(self.chain)
163
162
163
164 def result_display(self,arg):
164 def result_display(self,arg):
165 """ Default display hook.
165 """ Default display hook.
166
166
167 Called for displaying the result to the user.
167 Called for displaying the result to the user.
168 """
168 """
169
169
170 if self.pprint:
170 if self.pprint:
171 out = pformat(arg)
171 out = pformat(arg)
172 if '\n' in out:
172 if '\n' in out:
173 # So that multi-line strings line up with the left column of
173 # So that multi-line strings line up with the left column of
174 # the screen, instead of having the output prompt mess up
174 # the screen, instead of having the output prompt mess up
175 # their first line.
175 # their first line.
176 Term.cout.write('\n')
176 Term.cout.write('\n')
177 print >>Term.cout, out
177 print >>Term.cout, out
178 else:
178 else:
179 # By default, the interactive prompt uses repr() to display results,
179 # By default, the interactive prompt uses repr() to display results,
180 # so we should honor this. Users who'd rather use a different
180 # so we should honor this. Users who'd rather use a different
181 # mechanism can easily override this hook.
181 # mechanism can easily override this hook.
182 print >>Term.cout, repr(arg)
182 print >>Term.cout, repr(arg)
183 # the default display hook doesn't manipulate the value to put in history
183 # the default display hook doesn't manipulate the value to put in history
184 return None
184 return None
185
185
186
186 def input_prefilter(self,line):
187 def input_prefilter(self,line):
187 """ Default input prefilter
188 """ Default input prefilter
188
189
189 This returns the line as unchanged, so that the interpreter
190 This returns the line as unchanged, so that the interpreter
190 knows that nothing was done and proceeds with "classic" prefiltering
191 knows that nothing was done and proceeds with "classic" prefiltering
191 (%magics, !shell commands etc.).
192 (%magics, !shell commands etc.).
192
193
193 Note that leading whitespace is not passed to this hook. Prefilter
194 Note that leading whitespace is not passed to this hook. Prefilter
194 can't alter indentation.
195 can't alter indentation.
195
196
196 """
197 """
197 #print "attempt to rewrite",line #dbg
198 #print "attempt to rewrite",line #dbg
198 return line
199 return line
199
200
201
200 def shutdown_hook(self):
202 def shutdown_hook(self):
201 """ default shutdown hook
203 """ default shutdown hook
202
204
203 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
205 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
204 """
206 """
205
207
206 #print "default shutdown hook ok" # dbg
208 #print "default shutdown hook ok" # dbg
207 return
209 return
208
210
211
209 def late_startup_hook(self):
212 def late_startup_hook(self):
210 """ Executed after ipython has been constructed and configured
213 """ Executed after ipython has been constructed and configured
211
214
212 """
215 """
213 #print "default startup hook ok" # dbg
216 #print "default startup hook ok" # dbg
214
217
218
215 def generate_prompt(self, is_continuation):
219 def generate_prompt(self, is_continuation):
216 """ calculate and return a string with the prompt to display """
220 """ calculate and return a string with the prompt to display """
217 if is_continuation:
221 if is_continuation:
218 return str(self.outputcache.prompt2)
222 return str(self.outputcache.prompt2)
219 return str(self.outputcache.prompt1)
223 return str(self.outputcache.prompt1)
220
224
225
221 def generate_output_prompt(self):
226 def generate_output_prompt(self):
222 return str(self.outputcache.prompt_out)
227 return str(self.outputcache.prompt_out)
223
228
229
224 def shell_hook(self,cmd):
230 def shell_hook(self,cmd):
225 """ Run system/shell command a'la os.system() """
231 """ Run system/shell command a'la os.system() """
226
232
227 shell(cmd, header=self.system_header, verbose=self.system_verbose)
233 shell(cmd, header=self.system_header, verbose=self.system_verbose)
228
234
235
229 def show_in_pager(self,s):
236 def show_in_pager(self,s):
230 """ Run a string through pager """
237 """ Run a string through pager """
231 # raising TryNext here will use the default paging functionality
238 # raising TryNext here will use the default paging functionality
232 raise TryNext
239 raise TryNext
233
240
241
234 def pre_prompt_hook(self):
242 def pre_prompt_hook(self):
235 """ Run before displaying the next prompt
243 """ Run before displaying the next prompt
236
244
237 Use this e.g. to display output from asynchronous operations (in order
245 Use this e.g. to display output from asynchronous operations (in order
238 to not mess up text entry)
246 to not mess up text entry)
239 """
247 """
240
248
241 return None
249 return None
242
250
251
243 def pre_runcode_hook(self):
252 def pre_runcode_hook(self):
244 """ Executed before running the (prefiltered) code in IPython """
253 """ Executed before running the (prefiltered) code in IPython """
245 return None
254 return None
246
255
256
247 def clipboard_get(self):
257 def clipboard_get(self):
248 """ Get text from the clipboard.
258 """ Get text from the clipboard.
249 """
259 """
250 from IPython.lib.clipboard import (
260 from IPython.lib.clipboard import (
251 osx_clipboard_get, tkinter_clipboard_get,
261 osx_clipboard_get, tkinter_clipboard_get,
252 win32_clipboard_get
262 win32_clipboard_get
253 )
263 )
254 if sys.platform == 'win32':
264 if sys.platform == 'win32':
255 chain = [win32_clipboard_get, tkinter_clipboard_get]
265 chain = [win32_clipboard_get, tkinter_clipboard_get]
256 elif sys.platform == 'darwin':
266 elif sys.platform == 'darwin':
257 chain = [osx_clipboard_get, tkinter_clipboard_get]
267 chain = [osx_clipboard_get, tkinter_clipboard_get]
258 else:
268 else:
259 chain = [tkinter_clipboard_get]
269 chain = [tkinter_clipboard_get]
260 dispatcher = CommandChainDispatcher()
270 dispatcher = CommandChainDispatcher()
261 for func in chain:
271 for func in chain:
262 dispatcher.add(func)
272 dispatcher.add(func)
263 text = dispatcher()
273 text = dispatcher()
264 return text
274 return text
@@ -1,59 +1,58 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Oh my @#*%, where did ipapi go?
4 Oh my @#*%, where did ipapi go?
5
5
6 Originally, this module was designed to be a public api for IPython. It is
6 Originally, this module was designed to be a public api for IPython. It is
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
8 Almost all of the methods that were here are now there, but possibly renamed.
8 Almost all of the methods that were here are now there, but possibly renamed.
9
9
10 During our transition, we will keep this simple module with its :func:`get`
10 During our transition, we will keep this simple module with its :func:`get`
11 function. It too will eventually go away when the new component querying
11 function. It too will eventually go away when the new component querying
12 interface is fully used.
12 interface is fully used.
13
13
14 Authors:
14 Authors:
15
15
16 * Brian Granger
16 * Brian Granger
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 from IPython.core.error import TryNext, UsageError
30 from IPython.core.error import TryNext, UsageError
31 from IPython.core.component import Component
32 from IPython.core.iplib import InteractiveShell
33
31
34 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
35 # Classes and functions
33 # Classes and functions
36 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
37
35
38 def get():
36 def get():
39 """Get the most recently created InteractiveShell instance."""
37 """Get the most recently created InteractiveShell instance."""
38 from IPython.core.iplib import InteractiveShell
40 insts = InteractiveShell.get_instances()
39 insts = InteractiveShell.get_instances()
41 most_recent = insts[0]
40 most_recent = insts[0]
42 for inst in insts[1:]:
41 for inst in insts[1:]:
43 if inst.created > most_recent.created:
42 if inst.created > most_recent.created:
44 most_recent = inst
43 most_recent = inst
45 return most_recent
44 return most_recent
46
45
47 def launch_new_instance():
46 def launch_new_instance():
48 """Create a run a full blown IPython instance"""
47 """Create a run a full blown IPython instance"""
49 from IPython.core.ipapp import IPythonApp
48 from IPython.core.ipapp import IPythonApp
50 app = IPythonApp()
49 app = IPythonApp()
51 app.start()
50 app.start()
52
51
53
52
54
53
55
54
56
55
57
56
58
57
59
58
@@ -1,3059 +1,3100 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import __main__
19 import __main__
20 import __builtin__
20 import __builtin__
21 import StringIO
21 import StringIO
22 import bdb
22 import bdb
23 import codeop
23 import codeop
24 import exceptions
24 import exceptions
25 import glob
25 import glob
26 import keyword
26 import keyword
27 import new
27 import new
28 import os
28 import os
29 import re
29 import re
30 import shutil
30 import shutil
31 import string
31 import string
32 import sys
32 import sys
33 import tempfile
33 import tempfile
34
34
35 from IPython.core import ultratb
35 from IPython.core import ultratb
36 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import history as ipcorehist
38 from IPython.core import history as ipcorehist
39 from IPython.core import prefilter
39 from IPython.core import prefilter
40 from IPython.core.autocall import IPyAutocall
40 from IPython.core.autocall import IPyAutocall
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.logger import Logger
42 from IPython.core.logger import Logger
43 from IPython.core.magic import Magic
43 from IPython.core.magic import Magic
44 from IPython.core.prompts import CachedOutput
44 from IPython.core.prompts import CachedOutput
45 from IPython.core.page import page
45 from IPython.core.page import page
46 from IPython.core.component import Component
46 from IPython.core.component import Component
47 from IPython.core.oldusersetup import user_setup
47 from IPython.core.oldusersetup import user_setup
48 from IPython.core.usage import interactive_usage, default_banner
48 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
49 from IPython.core.error import TryNext, UsageError
50
50
51 from IPython.extensions import pickleshare
51 from IPython.extensions import pickleshare
52 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
53 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils.ipstruct import Struct
54 from IPython.utils.ipstruct import Struct
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils.genutils import *
56 from IPython.utils.genutils import *
57 from IPython.utils.strdispatch import StrDispatch
57 from IPython.utils.strdispatch import StrDispatch
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59
59
60 from IPython.utils.traitlets import (
60 from IPython.utils.traitlets import (
61 Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode
61 Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode
62 )
62 )
63
63
64 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
65 # Globals
65 # Globals
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67
67
68
68
69 # store the builtin raw_input globally, and use this always, in case user code
69 # store the builtin raw_input globally, and use this always, in case user code
70 # overwrites it (like wx.py.PyShell does)
70 # overwrites it (like wx.py.PyShell does)
71 raw_input_original = raw_input
71 raw_input_original = raw_input
72
72
73 # compiled regexps for autoindent management
73 # compiled regexps for autoindent management
74 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
74 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
75
75
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Utilities
78 # Utilities
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81
81
82 ini_spaces_re = re.compile(r'^(\s+)')
82 ini_spaces_re = re.compile(r'^(\s+)')
83
83
84
84
85 def num_ini_spaces(strng):
85 def num_ini_spaces(strng):
86 """Return the number of initial spaces in a string"""
86 """Return the number of initial spaces in a string"""
87
87
88 ini_spaces = ini_spaces_re.match(strng)
88 ini_spaces = ini_spaces_re.match(strng)
89 if ini_spaces:
89 if ini_spaces:
90 return ini_spaces.end()
90 return ini_spaces.end()
91 else:
91 else:
92 return 0
92 return 0
93
93
94
94
95 def softspace(file, newvalue):
95 def softspace(file, newvalue):
96 """Copied from code.py, to remove the dependency"""
96 """Copied from code.py, to remove the dependency"""
97
97
98 oldvalue = 0
98 oldvalue = 0
99 try:
99 try:
100 oldvalue = file.softspace
100 oldvalue = file.softspace
101 except AttributeError:
101 except AttributeError:
102 pass
102 pass
103 try:
103 try:
104 file.softspace = newvalue
104 file.softspace = newvalue
105 except (AttributeError, TypeError):
105 except (AttributeError, TypeError):
106 # "attribute-less object" or "read-only attributes"
106 # "attribute-less object" or "read-only attributes"
107 pass
107 pass
108 return oldvalue
108 return oldvalue
109
109
110
110
111 class SpaceInInput(exceptions.Exception): pass
111 class SpaceInInput(exceptions.Exception): pass
112
112
113 class Bunch: pass
113 class Bunch: pass
114
114
115 class Undefined: pass
115 class BuiltinUndefined: pass
116 BuiltinUndefined = BuiltinUndefined()
117
116
118
117 class Quitter(object):
119 class Quitter(object):
118 """Simple class to handle exit, similar to Python 2.5's.
120 """Simple class to handle exit, similar to Python 2.5's.
119
121
120 It handles exiting in an ipython-safe manner, which the one in Python 2.5
122 It handles exiting in an ipython-safe manner, which the one in Python 2.5
121 doesn't do (obviously, since it doesn't know about ipython)."""
123 doesn't do (obviously, since it doesn't know about ipython)."""
122
124
123 def __init__(self,shell,name):
125 def __init__(self, shell, name):
124 self.shell = shell
126 self.shell = shell
125 self.name = name
127 self.name = name
126
128
127 def __repr__(self):
129 def __repr__(self):
128 return 'Type %s() to exit.' % self.name
130 return 'Type %s() to exit.' % self.name
129 __str__ = __repr__
131 __str__ = __repr__
130
132
131 def __call__(self):
133 def __call__(self):
132 self.shell.exit()
134 self.shell.exit()
133
135
136
134 class InputList(list):
137 class InputList(list):
135 """Class to store user input.
138 """Class to store user input.
136
139
137 It's basically a list, but slices return a string instead of a list, thus
140 It's basically a list, but slices return a string instead of a list, thus
138 allowing things like (assuming 'In' is an instance):
141 allowing things like (assuming 'In' is an instance):
139
142
140 exec In[4:7]
143 exec In[4:7]
141
144
142 or
145 or
143
146
144 exec In[5:9] + In[14] + In[21:25]"""
147 exec In[5:9] + In[14] + In[21:25]"""
145
148
146 def __getslice__(self,i,j):
149 def __getslice__(self,i,j):
147 return ''.join(list.__getslice__(self,i,j))
150 return ''.join(list.__getslice__(self,i,j))
148
151
152
149 class SyntaxTB(ultratb.ListTB):
153 class SyntaxTB(ultratb.ListTB):
150 """Extension which holds some state: the last exception value"""
154 """Extension which holds some state: the last exception value"""
151
155
152 def __init__(self,color_scheme = 'NoColor'):
156 def __init__(self,color_scheme = 'NoColor'):
153 ultratb.ListTB.__init__(self,color_scheme)
157 ultratb.ListTB.__init__(self,color_scheme)
154 self.last_syntax_error = None
158 self.last_syntax_error = None
155
159
156 def __call__(self, etype, value, elist):
160 def __call__(self, etype, value, elist):
157 self.last_syntax_error = value
161 self.last_syntax_error = value
158 ultratb.ListTB.__call__(self,etype,value,elist)
162 ultratb.ListTB.__call__(self,etype,value,elist)
159
163
160 def clear_err_state(self):
164 def clear_err_state(self):
161 """Return the current error state and clear it"""
165 """Return the current error state and clear it"""
162 e = self.last_syntax_error
166 e = self.last_syntax_error
163 self.last_syntax_error = None
167 self.last_syntax_error = None
164 return e
168 return e
165
169
170
166 def get_default_editor():
171 def get_default_editor():
167 try:
172 try:
168 ed = os.environ['EDITOR']
173 ed = os.environ['EDITOR']
169 except KeyError:
174 except KeyError:
170 if os.name == 'posix':
175 if os.name == 'posix':
171 ed = 'vi' # the only one guaranteed to be there!
176 ed = 'vi' # the only one guaranteed to be there!
172 else:
177 else:
173 ed = 'notepad' # same in Windows!
178 ed = 'notepad' # same in Windows!
174 return ed
179 return ed
175
180
176
181
177 class SeparateStr(Str):
182 class SeparateStr(Str):
178 """A Str subclass to validate separate_in, separate_out, etc.
183 """A Str subclass to validate separate_in, separate_out, etc.
179
184
180 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
185 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
181 """
186 """
182
187
183 def validate(self, obj, value):
188 def validate(self, obj, value):
184 if value == '0': value = ''
189 if value == '0': value = ''
185 value = value.replace('\\n','\n')
190 value = value.replace('\\n','\n')
186 return super(SeparateStr, self).validate(obj, value)
191 return super(SeparateStr, self).validate(obj, value)
187
192
188
193
189 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
190 # Main IPython class
195 # Main IPython class
191 #-----------------------------------------------------------------------------
196 #-----------------------------------------------------------------------------
192
197
193 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
194 # until a full rewrite is made. I've cleaned all cross-class uses of
195 # attributes and methods, but too much user code out there relies on the
196 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
197 #
198 # But at least now, all the pieces have been separated and we could, in
199 # principle, stop using the mixin. This will ease the transition to the
200 # chainsaw branch.
201
202 # For reference, the following is the list of 'self.foo' uses in the Magic
203 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
204 # class, to prevent clashes.
205
206 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
207 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
208 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
209 # 'self.value']
210
198
211 class InteractiveShell(Component, Magic):
199 class InteractiveShell(Component, Magic):
212 """An enhanced console for Python."""
200 """An enhanced, interactive shell for Python."""
213
201
214 autocall = Enum((0,1,2), config_key='AUTOCALL')
202 autocall = Enum((0,1,2), config_key='AUTOCALL')
215 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
203 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
216 autoindent = CBool(True, config_key='AUTOINDENT')
204 autoindent = CBool(True, config_key='AUTOINDENT')
217 automagic = CBool(True, config_key='AUTOMAGIC')
205 automagic = CBool(True, config_key='AUTOMAGIC')
218 display_banner = CBool(True, config_key='DISPLAY_BANNER')
206 display_banner = CBool(True, config_key='DISPLAY_BANNER')
219 banner = Str('')
207 banner = Str('')
220 banner1 = Str(default_banner, config_key='BANNER1')
208 banner1 = Str(default_banner, config_key='BANNER1')
221 banner2 = Str('', config_key='BANNER2')
209 banner2 = Str('', config_key='BANNER2')
222 c = Str('', config_key='C')
210 c = Str('', config_key='C')
223 cache_size = Int(1000, config_key='CACHE_SIZE')
211 cache_size = Int(1000, config_key='CACHE_SIZE')
224 classic = CBool(False, config_key='CLASSIC')
212 classic = CBool(False, config_key='CLASSIC')
225 color_info = CBool(True, config_key='COLOR_INFO')
213 color_info = CBool(True, config_key='COLOR_INFO')
226 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
214 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
227 default_value='LightBG', config_key='COLORS')
215 default_value='LightBG', config_key='COLORS')
228 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
216 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
229 debug = CBool(False, config_key='DEBUG')
217 debug = CBool(False, config_key='DEBUG')
230 deep_reload = CBool(False, config_key='DEEP_RELOAD')
218 deep_reload = CBool(False, config_key='DEEP_RELOAD')
231 embedded = CBool(False)
219 embedded = CBool(False)
220 embedded_active = CBool(False)
232 editor = Str(get_default_editor(), config_key='EDITOR')
221 editor = Str(get_default_editor(), config_key='EDITOR')
233 filename = Str("<ipython console>")
222 filename = Str("<ipython console>")
234 interactive = CBool(False, config_key='INTERACTIVE')
223 interactive = CBool(False, config_key='INTERACTIVE')
235 ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__
224 ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__
236 logstart = CBool(False, config_key='LOGSTART')
225 logstart = CBool(False, config_key='LOGSTART')
237 logfile = Str('', config_key='LOGFILE')
226 logfile = Str('', config_key='LOGFILE')
238 logplay = Str('', config_key='LOGPLAY')
227 logplay = Str('', config_key='LOGPLAY')
239 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
228 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
240 object_info_string_level = Enum((0,1,2), default_value=0,
229 object_info_string_level = Enum((0,1,2), default_value=0,
241 config_keys='OBJECT_INFO_STRING_LEVEL')
230 config_keys='OBJECT_INFO_STRING_LEVEL')
242 pager = Str('less', config_key='PAGER')
231 pager = Str('less', config_key='PAGER')
243 pdb = CBool(False, config_key='PDB')
232 pdb = CBool(False, config_key='PDB')
244 pprint = CBool(True, config_key='PPRINT')
233 pprint = CBool(True, config_key='PPRINT')
245 profile = Str('', config_key='PROFILE')
234 profile = Str('', config_key='PROFILE')
246 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
235 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
247 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
236 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
248 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
237 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
249 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
238 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
250 quiet = CBool(False, config_key='QUIET')
239 quiet = CBool(False, config_key='QUIET')
251
240
252 readline_use = CBool(True, config_key='READLINE_USE')
241 readline_use = CBool(True, config_key='READLINE_USE')
253 readline_merge_completions = CBool(True,
242 readline_merge_completions = CBool(True,
254 config_key='READLINE_MERGE_COMPLETIONS')
243 config_key='READLINE_MERGE_COMPLETIONS')
255 readline_omit__names = Enum((0,1,2), default_value=0,
244 readline_omit__names = Enum((0,1,2), default_value=0,
256 config_key='READLINE_OMIT_NAMES')
245 config_key='READLINE_OMIT_NAMES')
257 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
246 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
258 readline_parse_and_bind = List([
247 readline_parse_and_bind = List([
259 'tab: complete',
248 'tab: complete',
260 '"\C-l": possible-completions',
249 '"\C-l": possible-completions',
261 'set show-all-if-ambiguous on',
250 'set show-all-if-ambiguous on',
262 '"\C-o": tab-insert',
251 '"\C-o": tab-insert',
263 '"\M-i": " "',
252 '"\M-i": " "',
264 '"\M-o": "\d\d\d\d"',
253 '"\M-o": "\d\d\d\d"',
265 '"\M-I": "\d\d\d\d"',
254 '"\M-I": "\d\d\d\d"',
266 '"\C-r": reverse-search-history',
255 '"\C-r": reverse-search-history',
267 '"\C-s": forward-search-history',
256 '"\C-s": forward-search-history',
268 '"\C-p": history-search-backward',
257 '"\C-p": history-search-backward',
269 '"\C-n": history-search-forward',
258 '"\C-n": history-search-forward',
270 '"\e[A": history-search-backward',
259 '"\e[A": history-search-backward',
271 '"\e[B": history-search-forward',
260 '"\e[B": history-search-forward',
272 '"\C-k": kill-line',
261 '"\C-k": kill-line',
273 '"\C-u": unix-line-discard',
262 '"\C-u": unix-line-discard',
274 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
263 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
275 )
264 )
276
265
277 screen_length = Int(0, config_key='SCREEN_LENGTH')
266 screen_length = Int(0, config_key='SCREEN_LENGTH')
278
267
279 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
268 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
280 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
269 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
281 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
270 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
282 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
271 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
283
272
284 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
273 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
285 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
274 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
286 term_title = CBool(False, config_key='TERM_TITLE')
275 term_title = CBool(False, config_key='TERM_TITLE')
287 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
276 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
288 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
277 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
289 default_value='Context', config_key='XMODE')
278 default_value='Context', config_key='XMODE')
290
279
291 alias = List(allow_none=False, config_key='ALIAS')
280 alias = List(allow_none=False, config_key='ALIAS')
292 autoexec = List(allow_none=False)
281 autoexec = List(allow_none=False)
293
282
294 # class attribute to indicate whether the class supports threads or not.
283 # class attribute to indicate whether the class supports threads or not.
295 # Subclasses with thread support should override this as needed.
284 # Subclasses with thread support should override this as needed.
296 isthreaded = False
285 isthreaded = False
297
286
298 def __init__(self, parent=None, ipythondir=None, config=None, usage=None,
287 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
299 user_ns=None, user_global_ns=None,
288 user_ns=None, user_global_ns=None,
300 banner1=None, banner2=None,
289 banner1=None, banner2=None,
301 custom_exceptions=((),None), embedded=False):
290 custom_exceptions=((),None)):
302
291
303 # This is where traitlets with a config_key argument are updated
292 # This is where traitlets with a config_key argument are updated
304 # from the values on config.
293 # from the values on config.
305 # Ideally, from here on out, the config should only be used when
306 # passing it to children components.
307 super(InteractiveShell, self).__init__(parent, config=config, name='__IP')
294 super(InteractiveShell, self).__init__(parent, config=config, name='__IP')
308
295
296 # These are relatively independent and stateless
309 self.init_ipythondir(ipythondir)
297 self.init_ipythondir(ipythondir)
310 self.init_instance_attrs()
298 self.init_instance_attrs()
311 self.init_term_title()
299 self.init_term_title()
312 self.init_usage(usage)
300 self.init_usage(usage)
313 self.init_banner(banner1, banner2)
301 self.init_banner(banner1, banner2)
314 self.init_embedded(embedded)
302
303 # Create namespaces (user_ns, user_global_ns, alias_table, etc.)
315 self.init_create_namespaces(user_ns, user_global_ns)
304 self.init_create_namespaces(user_ns, user_global_ns)
305 # This has to be done after init_create_namespaces because it uses
306 # something in self.user_ns, but before init_sys_modules, which
307 # is the first thing to modify sys.
308 self.save_sys_module_state()
309 self.init_sys_modules()
310
316 self.init_history()
311 self.init_history()
317 self.init_encoding()
312 self.init_encoding()
318 self.init_handlers()
313 self.init_handlers()
319
314
320 Magic.__init__(self, self)
315 Magic.__init__(self, self)
321
316
322 self.init_syntax_highlighting()
317 self.init_syntax_highlighting()
323 self.init_hooks()
318 self.init_hooks()
324 self.init_pushd_popd_magic()
319 self.init_pushd_popd_magic()
325 self.init_traceback_handlers(custom_exceptions)
320 self.init_traceback_handlers(custom_exceptions)
326 self.init_namespaces()
321 self.init_user_ns()
327 self.init_logger()
322 self.init_logger()
328 self.init_aliases()
323 self.init_aliases()
329 self.init_builtins()
324 self.init_builtins()
330
325
331 # pre_config_initialization
326 # pre_config_initialization
332 self.init_shadow_hist()
327 self.init_shadow_hist()
333
328
334 # The next section should contain averything that was in ipmaker.
329 # The next section should contain averything that was in ipmaker.
335 self.init_logstart()
330 self.init_logstart()
336
331
337 # The following was in post_config_initialization
332 # The following was in post_config_initialization
338 self.init_inspector()
333 self.init_inspector()
339 self.init_readline()
334 self.init_readline()
340 self.init_prompts()
335 self.init_prompts()
341 self.init_displayhook()
336 self.init_displayhook()
342 self.init_reload_doctest()
337 self.init_reload_doctest()
343 self.init_magics()
338 self.init_magics()
344 self.init_pdb()
339 self.init_pdb()
345 self.hooks.late_startup_hook()
340 self.hooks.late_startup_hook()
346
341
342 def cleanup(self):
343 self.remove_builtins()
344 self.restore_sys_module_state()
345
347 #-------------------------------------------------------------------------
346 #-------------------------------------------------------------------------
348 # Traitlet changed handlers
347 # Traitlet changed handlers
349 #-------------------------------------------------------------------------
348 #-------------------------------------------------------------------------
350
349
351 def _banner1_changed(self):
350 def _banner1_changed(self):
352 self.compute_banner()
351 self.compute_banner()
353
352
354 def _banner2_changed(self):
353 def _banner2_changed(self):
355 self.compute_banner()
354 self.compute_banner()
356
355
357 @property
356 @property
358 def usable_screen_length(self):
357 def usable_screen_length(self):
359 if self.screen_length == 0:
358 if self.screen_length == 0:
360 return 0
359 return 0
361 else:
360 else:
362 num_lines_bot = self.separate_in.count('\n')+1
361 num_lines_bot = self.separate_in.count('\n')+1
363 return self.screen_length - num_lines_bot
362 return self.screen_length - num_lines_bot
364
363
365 def _term_title_changed(self, name, new_value):
364 def _term_title_changed(self, name, new_value):
366 self.init_term_title()
365 self.init_term_title()
367
366
368 #-------------------------------------------------------------------------
367 #-------------------------------------------------------------------------
369 # init_* methods called by __init__
368 # init_* methods called by __init__
370 #-------------------------------------------------------------------------
369 #-------------------------------------------------------------------------
371
370
372 def init_ipythondir(self, ipythondir):
371 def init_ipythondir(self, ipythondir):
373 if ipythondir is not None:
372 if ipythondir is not None:
374 self.ipythondir = ipythondir
373 self.ipythondir = ipythondir
374 self.config.IPYTHONDIR = self.ipythondir
375 return
375 return
376
376
377 if hasattr(self.config, 'IPYTHONDIR'):
378 self.ipythondir = self.config.IPYTHONDIR
377 if not hasattr(self.config, 'IPYTHONDIR'):
379 if not hasattr(self.config, 'IPYTHONDIR'):
378 # cdw is always defined
380 # cdw is always defined
379 self.ipythondir = os.getcwd()
381 self.ipythondir = os.getcwd()
380 return
382
383 # The caller must make sure that ipythondir exists. We should
384 # probably handle this using a Dir traitlet.
385 if not os.path.isdir(self.ipythondir):
386 raise IOError('IPython dir does not exist: %s' % self.ipythondir)
387
388 # All children can just read this
389 self.config.IPYTHONDIR = self.ipythondir
381
390
382 def init_instance_attrs(self):
391 def init_instance_attrs(self):
383 self.jobs = BackgroundJobManager()
392 self.jobs = BackgroundJobManager()
384 self.more = False
393 self.more = False
385
394
386 # command compiler
395 # command compiler
387 self.compile = codeop.CommandCompiler()
396 self.compile = codeop.CommandCompiler()
388
397
389 # User input buffer
398 # User input buffer
390 self.buffer = []
399 self.buffer = []
391
400
392 # Make an empty namespace, which extension writers can rely on both
401 # Make an empty namespace, which extension writers can rely on both
393 # existing and NEVER being used by ipython itself. This gives them a
402 # existing and NEVER being used by ipython itself. This gives them a
394 # convenient location for storing additional information and state
403 # convenient location for storing additional information and state
395 # their extensions may require, without fear of collisions with other
404 # their extensions may require, without fear of collisions with other
396 # ipython names that may develop later.
405 # ipython names that may develop later.
397 self.meta = Struct()
406 self.meta = Struct()
398
407
399 # Object variable to store code object waiting execution. This is
408 # Object variable to store code object waiting execution. This is
400 # used mainly by the multithreaded shells, but it can come in handy in
409 # used mainly by the multithreaded shells, but it can come in handy in
401 # other situations. No need to use a Queue here, since it's a single
410 # other situations. No need to use a Queue here, since it's a single
402 # item which gets cleared once run.
411 # item which gets cleared once run.
403 self.code_to_run = None
412 self.code_to_run = None
404
413
405 # Flag to mark unconditional exit
414 # Flag to mark unconditional exit
406 self.exit_now = False
415 self.exit_now = False
407
416
408 # Temporary files used for various purposes. Deleted at exit.
417 # Temporary files used for various purposes. Deleted at exit.
409 self.tempfiles = []
418 self.tempfiles = []
410
419
411 # Keep track of readline usage (later set by init_readline)
420 # Keep track of readline usage (later set by init_readline)
412 self.has_readline = False
421 self.has_readline = False
413
422
414 # keep track of where we started running (mainly for crash post-mortem)
423 # keep track of where we started running (mainly for crash post-mortem)
415 # This is not being used anywhere currently.
424 # This is not being used anywhere currently.
416 self.starting_dir = os.getcwd()
425 self.starting_dir = os.getcwd()
417
426
418 # Indentation management
427 # Indentation management
419 self.indent_current_nsp = 0
428 self.indent_current_nsp = 0
420
429
421 def init_term_title(self):
430 def init_term_title(self):
422 # Enable or disable the terminal title.
431 # Enable or disable the terminal title.
423 if self.term_title:
432 if self.term_title:
424 toggle_set_term_title(True)
433 toggle_set_term_title(True)
425 set_term_title('IPython: ' + abbrev_cwd())
434 set_term_title('IPython: ' + abbrev_cwd())
426 else:
435 else:
427 toggle_set_term_title(False)
436 toggle_set_term_title(False)
428
437
429 def init_usage(self, usage=None):
438 def init_usage(self, usage=None):
430 if usage is None:
439 if usage is None:
431 self.usage = interactive_usage
440 self.usage = interactive_usage
432 else:
441 else:
433 self.usage = usage
442 self.usage = usage
434
443
435 def init_banner(self, banner1, banner2):
444 def init_banner(self, banner1, banner2):
436 if self.c: # regular python doesn't print the banner with -c
445 if self.c: # regular python doesn't print the banner with -c
437 self.display_banner = False
446 self.display_banner = False
438 if banner1 is not None:
447 if banner1 is not None:
439 self.banner1 = banner1
448 self.banner1 = banner1
440 if banner2 is not None:
449 if banner2 is not None:
441 self.banner2 = banner2
450 self.banner2 = banner2
442 self.compute_banner()
451 self.compute_banner()
443
452
444 def compute_banner(self):
453 def compute_banner(self):
445 self.banner = self.banner1 + '\n'
454 self.banner = self.banner1 + '\n'
446 if self.profile:
455 if self.profile:
447 self.banner += '\nIPython profile: %s\n' % self.profile
456 self.banner += '\nIPython profile: %s\n' % self.profile
448 if self.banner2:
457 if self.banner2:
449 self.banner += '\n' + self.banner2 + '\n'
458 self.banner += '\n' + self.banner2 + '\n'
450
459
451 def init_embedded(self, embedded):
452 # We need to know whether the instance is meant for embedding, since
453 # global/local namespaces need to be handled differently in that case
454 self.embedded = embedded
455 if embedded:
456 # Control variable so users can, from within the embedded instance,
457 # permanently deactivate it.
458 self.embedded_active = True
459
460 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
460 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
461 # Create the namespace where the user will operate. user_ns is
461 # Create the namespace where the user will operate. user_ns is
462 # normally the only one used, and it is passed to the exec calls as
462 # normally the only one used, and it is passed to the exec calls as
463 # the locals argument. But we do carry a user_global_ns namespace
463 # the locals argument. But we do carry a user_global_ns namespace
464 # given as the exec 'globals' argument, This is useful in embedding
464 # given as the exec 'globals' argument, This is useful in embedding
465 # situations where the ipython shell opens in a context where the
465 # situations where the ipython shell opens in a context where the
466 # distinction between locals and globals is meaningful. For
466 # distinction between locals and globals is meaningful. For
467 # non-embedded contexts, it is just the same object as the user_ns dict.
467 # non-embedded contexts, it is just the same object as the user_ns dict.
468
468
469 # FIXME. For some strange reason, __builtins__ is showing up at user
469 # FIXME. For some strange reason, __builtins__ is showing up at user
470 # level as a dict instead of a module. This is a manual fix, but I
470 # level as a dict instead of a module. This is a manual fix, but I
471 # should really track down where the problem is coming from. Alex
471 # should really track down where the problem is coming from. Alex
472 # Schmolck reported this problem first.
472 # Schmolck reported this problem first.
473
473
474 # A useful post by Alex Martelli on this topic:
474 # A useful post by Alex Martelli on this topic:
475 # Re: inconsistent value from __builtins__
475 # Re: inconsistent value from __builtins__
476 # Von: Alex Martelli <aleaxit@yahoo.com>
476 # Von: Alex Martelli <aleaxit@yahoo.com>
477 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
477 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
478 # Gruppen: comp.lang.python
478 # Gruppen: comp.lang.python
479
479
480 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
480 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
481 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
481 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
482 # > <type 'dict'>
482 # > <type 'dict'>
483 # > >>> print type(__builtins__)
483 # > >>> print type(__builtins__)
484 # > <type 'module'>
484 # > <type 'module'>
485 # > Is this difference in return value intentional?
485 # > Is this difference in return value intentional?
486
486
487 # Well, it's documented that '__builtins__' can be either a dictionary
487 # Well, it's documented that '__builtins__' can be either a dictionary
488 # or a module, and it's been that way for a long time. Whether it's
488 # or a module, and it's been that way for a long time. Whether it's
489 # intentional (or sensible), I don't know. In any case, the idea is
489 # intentional (or sensible), I don't know. In any case, the idea is
490 # that if you need to access the built-in namespace directly, you
490 # that if you need to access the built-in namespace directly, you
491 # should start with "import __builtin__" (note, no 's') which will
491 # should start with "import __builtin__" (note, no 's') which will
492 # definitely give you a module. Yeah, it's somewhat confusing:-(.
492 # definitely give you a module. Yeah, it's somewhat confusing:-(.
493
493
494 # These routines return properly built dicts as needed by the rest of
494 # These routines return properly built dicts as needed by the rest of
495 # the code, and can also be used by extension writers to generate
495 # the code, and can also be used by extension writers to generate
496 # properly initialized namespaces.
496 # properly initialized namespaces.
497 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
497 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
498 user_global_ns)
498 user_global_ns)
499
499
500 # Assign namespaces
500 # Assign namespaces
501 # This is the namespace where all normal user variables live
501 # This is the namespace where all normal user variables live
502 self.user_ns = user_ns
502 self.user_ns = user_ns
503 self.user_global_ns = user_global_ns
503 self.user_global_ns = user_global_ns
504
504
505 # An auxiliary namespace that checks what parts of the user_ns were
505 # An auxiliary namespace that checks what parts of the user_ns were
506 # loaded at startup, so we can list later only variables defined in
506 # loaded at startup, so we can list later only variables defined in
507 # actual interactive use. Since it is always a subset of user_ns, it
507 # actual interactive use. Since it is always a subset of user_ns, it
508 # doesn't need to be seaparately tracked in the ns_table
508 # doesn't need to be seaparately tracked in the ns_table
509 self.user_config_ns = {}
509 self.user_config_ns = {}
510
510
511 # A namespace to keep track of internal data structures to prevent
511 # A namespace to keep track of internal data structures to prevent
512 # them from cluttering user-visible stuff. Will be updated later
512 # them from cluttering user-visible stuff. Will be updated later
513 self.internal_ns = {}
513 self.internal_ns = {}
514
514
515 # Namespace of system aliases. Each entry in the alias
515 # Namespace of system aliases. Each entry in the alias
516 # table must be a 2-tuple of the form (N,name), where N is the number
516 # table must be a 2-tuple of the form (N,name), where N is the number
517 # of positional arguments of the alias.
517 # of positional arguments of the alias.
518 self.alias_table = {}
518 self.alias_table = {}
519
519
520 # Now that FakeModule produces a real module, we've run into a nasty
520 # Now that FakeModule produces a real module, we've run into a nasty
521 # problem: after script execution (via %run), the module where the user
521 # problem: after script execution (via %run), the module where the user
522 # code ran is deleted. Now that this object is a true module (needed
522 # code ran is deleted. Now that this object is a true module (needed
523 # so docetst and other tools work correctly), the Python module
523 # so docetst and other tools work correctly), the Python module
524 # teardown mechanism runs over it, and sets to None every variable
524 # teardown mechanism runs over it, and sets to None every variable
525 # present in that module. Top-level references to objects from the
525 # present in that module. Top-level references to objects from the
526 # script survive, because the user_ns is updated with them. However,
526 # script survive, because the user_ns is updated with them. However,
527 # calling functions defined in the script that use other things from
527 # calling functions defined in the script that use other things from
528 # the script will fail, because the function's closure had references
528 # the script will fail, because the function's closure had references
529 # to the original objects, which are now all None. So we must protect
529 # to the original objects, which are now all None. So we must protect
530 # these modules from deletion by keeping a cache.
530 # these modules from deletion by keeping a cache.
531 #
531 #
532 # To avoid keeping stale modules around (we only need the one from the
532 # To avoid keeping stale modules around (we only need the one from the
533 # last run), we use a dict keyed with the full path to the script, so
533 # last run), we use a dict keyed with the full path to the script, so
534 # only the last version of the module is held in the cache. Note,
534 # only the last version of the module is held in the cache. Note,
535 # however, that we must cache the module *namespace contents* (their
535 # however, that we must cache the module *namespace contents* (their
536 # __dict__). Because if we try to cache the actual modules, old ones
536 # __dict__). Because if we try to cache the actual modules, old ones
537 # (uncached) could be destroyed while still holding references (such as
537 # (uncached) could be destroyed while still holding references (such as
538 # those held by GUI objects that tend to be long-lived)>
538 # those held by GUI objects that tend to be long-lived)>
539 #
539 #
540 # The %reset command will flush this cache. See the cache_main_mod()
540 # The %reset command will flush this cache. See the cache_main_mod()
541 # and clear_main_mod_cache() methods for details on use.
541 # and clear_main_mod_cache() methods for details on use.
542
542
543 # This is the cache used for 'main' namespaces
543 # This is the cache used for 'main' namespaces
544 self._main_ns_cache = {}
544 self._main_ns_cache = {}
545 # And this is the single instance of FakeModule whose __dict__ we keep
545 # And this is the single instance of FakeModule whose __dict__ we keep
546 # copying and clearing for reuse on each %run
546 # copying and clearing for reuse on each %run
547 self._user_main_module = FakeModule()
547 self._user_main_module = FakeModule()
548
548
549 # A table holding all the namespaces IPython deals with, so that
549 # A table holding all the namespaces IPython deals with, so that
550 # introspection facilities can search easily.
550 # introspection facilities can search easily.
551 self.ns_table = {'user':user_ns,
551 self.ns_table = {'user':user_ns,
552 'user_global':user_global_ns,
552 'user_global':user_global_ns,
553 'alias':self.alias_table,
553 'alias':self.alias_table,
554 'internal':self.internal_ns,
554 'internal':self.internal_ns,
555 'builtin':__builtin__.__dict__
555 'builtin':__builtin__.__dict__
556 }
556 }
557
557
558 # Similarly, track all namespaces where references can be held and that
558 # Similarly, track all namespaces where references can be held and that
559 # we can safely clear (so it can NOT include builtin). This one can be
559 # we can safely clear (so it can NOT include builtin). This one can be
560 # a simple list.
560 # a simple list.
561 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
561 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
562 self.alias_table, self.internal_ns,
562 self.alias_table, self.internal_ns,
563 self._main_ns_cache ]
563 self._main_ns_cache ]
564
564
565 def init_sys_modules(self):
565 # We need to insert into sys.modules something that looks like a
566 # We need to insert into sys.modules something that looks like a
566 # module but which accesses the IPython namespace, for shelve and
567 # module but which accesses the IPython namespace, for shelve and
567 # pickle to work interactively. Normally they rely on getting
568 # pickle to work interactively. Normally they rely on getting
568 # everything out of __main__, but for embedding purposes each IPython
569 # everything out of __main__, but for embedding purposes each IPython
569 # instance has its own private namespace, so we can't go shoving
570 # instance has its own private namespace, so we can't go shoving
570 # everything into __main__.
571 # everything into __main__.
571
572
572 # note, however, that we should only do this for non-embedded
573 # note, however, that we should only do this for non-embedded
573 # ipythons, which really mimic the __main__.__dict__ with their own
574 # ipythons, which really mimic the __main__.__dict__ with their own
574 # namespace. Embedded instances, on the other hand, should not do
575 # namespace. Embedded instances, on the other hand, should not do
575 # this because they need to manage the user local/global namespaces
576 # this because they need to manage the user local/global namespaces
576 # only, but they live within a 'normal' __main__ (meaning, they
577 # only, but they live within a 'normal' __main__ (meaning, they
577 # shouldn't overtake the execution environment of the script they're
578 # shouldn't overtake the execution environment of the script they're
578 # embedded in).
579 # embedded in).
579
580
580 if not self.embedded:
581 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
582
581 try:
583 try:
582 main_name = self.user_ns['__name__']
584 main_name = self.user_ns['__name__']
583 except KeyError:
585 except KeyError:
584 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
586 raise KeyError('user_ns dictionary MUST have a "__name__" key')
585 else:
587 else:
586 sys.modules[main_name] = FakeModule(self.user_ns)
588 sys.modules[main_name] = FakeModule(self.user_ns)
587
589
588 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
590 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
589 """Return a valid local and global user interactive namespaces.
591 """Return a valid local and global user interactive namespaces.
590
592
591 This builds a dict with the minimal information needed to operate as a
593 This builds a dict with the minimal information needed to operate as a
592 valid IPython user namespace, which you can pass to the various
594 valid IPython user namespace, which you can pass to the various
593 embedding classes in ipython. The default implementation returns the
595 embedding classes in ipython. The default implementation returns the
594 same dict for both the locals and the globals to allow functions to
596 same dict for both the locals and the globals to allow functions to
595 refer to variables in the namespace. Customized implementations can
597 refer to variables in the namespace. Customized implementations can
596 return different dicts. The locals dictionary can actually be anything
598 return different dicts. The locals dictionary can actually be anything
597 following the basic mapping protocol of a dict, but the globals dict
599 following the basic mapping protocol of a dict, but the globals dict
598 must be a true dict, not even a subclass. It is recommended that any
600 must be a true dict, not even a subclass. It is recommended that any
599 custom object for the locals namespace synchronize with the globals
601 custom object for the locals namespace synchronize with the globals
600 dict somehow.
602 dict somehow.
601
603
602 Raises TypeError if the provided globals namespace is not a true dict.
604 Raises TypeError if the provided globals namespace is not a true dict.
603
605
604 :Parameters:
606 :Parameters:
605 user_ns : dict-like, optional
607 user_ns : dict-like, optional
606 The current user namespace. The items in this namespace should
608 The current user namespace. The items in this namespace should
607 be included in the output. If None, an appropriate blank
609 be included in the output. If None, an appropriate blank
608 namespace should be created.
610 namespace should be created.
609 user_global_ns : dict, optional
611 user_global_ns : dict, optional
610 The current user global namespace. The items in this namespace
612 The current user global namespace. The items in this namespace
611 should be included in the output. If None, an appropriate
613 should be included in the output. If None, an appropriate
612 blank namespace should be created.
614 blank namespace should be created.
613
615
614 :Returns:
616 :Returns:
615 A tuple pair of dictionary-like object to be used as the local namespace
617 A tuple pair of dictionary-like object to be used as the local namespace
616 of the interpreter and a dict to be used as the global namespace.
618 of the interpreter and a dict to be used as the global namespace.
617 """
619 """
618
620
619 if user_ns is None:
621 if user_ns is None:
620 # Set __name__ to __main__ to better match the behavior of the
622 # Set __name__ to __main__ to better match the behavior of the
621 # normal interpreter.
623 # normal interpreter.
622 user_ns = {'__name__' :'__main__',
624 user_ns = {'__name__' :'__main__',
623 '__builtins__' : __builtin__,
625 '__builtins__' : __builtin__,
624 }
626 }
625 else:
627 else:
626 user_ns.setdefault('__name__','__main__')
628 user_ns.setdefault('__name__','__main__')
627 user_ns.setdefault('__builtins__',__builtin__)
629 user_ns.setdefault('__builtins__',__builtin__)
628
630
629 if user_global_ns is None:
631 if user_global_ns is None:
630 user_global_ns = user_ns
632 user_global_ns = user_ns
631 if type(user_global_ns) is not dict:
633 if type(user_global_ns) is not dict:
632 raise TypeError("user_global_ns must be a true dict; got %r"
634 raise TypeError("user_global_ns must be a true dict; got %r"
633 % type(user_global_ns))
635 % type(user_global_ns))
634
636
635 return user_ns, user_global_ns
637 return user_ns, user_global_ns
636
638
637 def init_history(self):
639 def init_history(self):
638 # List of input with multi-line handling.
640 # List of input with multi-line handling.
639 self.input_hist = InputList()
641 self.input_hist = InputList()
640 # This one will hold the 'raw' input history, without any
642 # This one will hold the 'raw' input history, without any
641 # pre-processing. This will allow users to retrieve the input just as
643 # pre-processing. This will allow users to retrieve the input just as
642 # it was exactly typed in by the user, with %hist -r.
644 # it was exactly typed in by the user, with %hist -r.
643 self.input_hist_raw = InputList()
645 self.input_hist_raw = InputList()
644
646
645 # list of visited directories
647 # list of visited directories
646 try:
648 try:
647 self.dir_hist = [os.getcwd()]
649 self.dir_hist = [os.getcwd()]
648 except OSError:
650 except OSError:
649 self.dir_hist = []
651 self.dir_hist = []
650
652
651 # dict of output history
653 # dict of output history
652 self.output_hist = {}
654 self.output_hist = {}
653
655
654 # Now the history file
656 # Now the history file
655 try:
657 try:
656 histfname = 'history-%s' % self.profile
658 histfname = 'history-%s' % self.profile
657 except AttributeError:
659 except AttributeError:
658 histfname = 'history'
660 histfname = 'history'
659 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
661 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
660
662
661 # Fill the history zero entry, user counter starts at 1
663 # Fill the history zero entry, user counter starts at 1
662 self.input_hist.append('\n')
664 self.input_hist.append('\n')
663 self.input_hist_raw.append('\n')
665 self.input_hist_raw.append('\n')
664
666
665 def init_encoding(self):
667 def init_encoding(self):
666 # Get system encoding at startup time. Certain terminals (like Emacs
668 # Get system encoding at startup time. Certain terminals (like Emacs
667 # under Win32 have it set to None, and we need to have a known valid
669 # under Win32 have it set to None, and we need to have a known valid
668 # encoding to use in the raw_input() method
670 # encoding to use in the raw_input() method
669 try:
671 try:
670 self.stdin_encoding = sys.stdin.encoding or 'ascii'
672 self.stdin_encoding = sys.stdin.encoding or 'ascii'
671 except AttributeError:
673 except AttributeError:
672 self.stdin_encoding = 'ascii'
674 self.stdin_encoding = 'ascii'
673
675
674 def init_handlers(self):
676 def init_handlers(self):
675 # escapes for automatic behavior on the command line
677 # escapes for automatic behavior on the command line
676 self.ESC_SHELL = '!'
678 self.ESC_SHELL = '!'
677 self.ESC_SH_CAP = '!!'
679 self.ESC_SH_CAP = '!!'
678 self.ESC_HELP = '?'
680 self.ESC_HELP = '?'
679 self.ESC_MAGIC = '%'
681 self.ESC_MAGIC = '%'
680 self.ESC_QUOTE = ','
682 self.ESC_QUOTE = ','
681 self.ESC_QUOTE2 = ';'
683 self.ESC_QUOTE2 = ';'
682 self.ESC_PAREN = '/'
684 self.ESC_PAREN = '/'
683
685
684 # And their associated handlers
686 # And their associated handlers
685 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
687 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
686 self.ESC_QUOTE : self.handle_auto,
688 self.ESC_QUOTE : self.handle_auto,
687 self.ESC_QUOTE2 : self.handle_auto,
689 self.ESC_QUOTE2 : self.handle_auto,
688 self.ESC_MAGIC : self.handle_magic,
690 self.ESC_MAGIC : self.handle_magic,
689 self.ESC_HELP : self.handle_help,
691 self.ESC_HELP : self.handle_help,
690 self.ESC_SHELL : self.handle_shell_escape,
692 self.ESC_SHELL : self.handle_shell_escape,
691 self.ESC_SH_CAP : self.handle_shell_escape,
693 self.ESC_SH_CAP : self.handle_shell_escape,
692 }
694 }
693
695
694 def init_syntax_highlighting(self):
696 def init_syntax_highlighting(self):
695 # Python source parser/formatter for syntax highlighting
697 # Python source parser/formatter for syntax highlighting
696 pyformat = PyColorize.Parser().format
698 pyformat = PyColorize.Parser().format
697 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
699 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
698
700
699 def init_hooks(self):
701 def init_hooks(self):
700 # hooks holds pointers used for user-side customizations
702 # hooks holds pointers used for user-side customizations
701 self.hooks = Struct()
703 self.hooks = Struct()
702
704
703 self.strdispatchers = {}
705 self.strdispatchers = {}
704
706
705 # Set all default hooks, defined in the IPython.hooks module.
707 # Set all default hooks, defined in the IPython.hooks module.
706 import IPython.core.hooks
708 import IPython.core.hooks
707 hooks = IPython.core.hooks
709 hooks = IPython.core.hooks
708 for hook_name in hooks.__all__:
710 for hook_name in hooks.__all__:
709 # default hooks have priority 100, i.e. low; user hooks should have
711 # default hooks have priority 100, i.e. low; user hooks should have
710 # 0-100 priority
712 # 0-100 priority
711 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
713 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
712
714
713 def init_pushd_popd_magic(self):
715 def init_pushd_popd_magic(self):
714 # for pushd/popd management
716 # for pushd/popd management
715 try:
717 try:
716 self.home_dir = get_home_dir()
718 self.home_dir = get_home_dir()
717 except HomeDirError, msg:
719 except HomeDirError, msg:
718 fatal(msg)
720 fatal(msg)
719
721
720 self.dir_stack = []
722 self.dir_stack = []
721
723
722 def init_traceback_handlers(self, custom_exceptions):
724 def init_traceback_handlers(self, custom_exceptions):
723 # Syntax error handler.
725 # Syntax error handler.
724 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
726 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
725
727
726 # The interactive one is initialized with an offset, meaning we always
728 # The interactive one is initialized with an offset, meaning we always
727 # want to remove the topmost item in the traceback, which is our own
729 # want to remove the topmost item in the traceback, which is our own
728 # internal code. Valid modes: ['Plain','Context','Verbose']
730 # internal code. Valid modes: ['Plain','Context','Verbose']
729 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
731 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
730 color_scheme='NoColor',
732 color_scheme='NoColor',
731 tb_offset = 1)
733 tb_offset = 1)
732
734
733 # IPython itself shouldn't crash. This will produce a detailed
735 # IPython itself shouldn't crash. This will produce a detailed
734 # post-mortem if it does. But we only install the crash handler for
736 # post-mortem if it does. But we only install the crash handler for
735 # non-threaded shells, the threaded ones use a normal verbose reporter
737 # non-threaded shells, the threaded ones use a normal verbose reporter
736 # and lose the crash handler. This is because exceptions in the main
738 # and lose the crash handler. This is because exceptions in the main
737 # thread (such as in GUI code) propagate directly to sys.excepthook,
739 # thread (such as in GUI code) propagate directly to sys.excepthook,
738 # and there's no point in printing crash dumps for every user exception.
740 # and there's no point in printing crash dumps for every user exception.
739 if self.isthreaded:
741 if self.isthreaded:
740 ipCrashHandler = ultratb.FormattedTB()
742 ipCrashHandler = ultratb.FormattedTB()
741 else:
743 else:
742 from IPython.core import crashhandler
744 from IPython.core import crashhandler
743 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
745 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
744 self.set_crash_handler(ipCrashHandler)
746 self.set_crash_handler(ipCrashHandler)
745
747
746 # and add any custom exception handlers the user may have specified
748 # and add any custom exception handlers the user may have specified
747 self.set_custom_exc(*custom_exceptions)
749 self.set_custom_exc(*custom_exceptions)
748
750
749 def init_logger(self):
751 def init_logger(self):
750 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
752 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
751 # local shortcut, this is used a LOT
753 # local shortcut, this is used a LOT
752 self.log = self.logger.log
754 self.log = self.logger.log
753 # template for logfile headers. It gets resolved at runtime by the
755 # template for logfile headers. It gets resolved at runtime by the
754 # logstart method.
756 # logstart method.
755 self.loghead_tpl = \
757 self.loghead_tpl = \
756 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
758 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
757 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
759 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
758 #log# opts = %s
760 #log# opts = %s
759 #log# args = %s
761 #log# args = %s
760 #log# It is safe to make manual edits below here.
762 #log# It is safe to make manual edits below here.
761 #log#-----------------------------------------------------------------------
763 #log#-----------------------------------------------------------------------
762 """
764 """
763
765
764 def init_logstart(self):
766 def init_logstart(self):
765 if self.logplay:
767 if self.logplay:
766 self.magic_logstart(self.logplay + ' append')
768 self.magic_logstart(self.logplay + ' append')
767 elif self.logfile:
769 elif self.logfile:
768 self.magic_logstart(self.logfile)
770 self.magic_logstart(self.logfile)
769 elif self.logstart:
771 elif self.logstart:
770 self.magic_logstart()
772 self.magic_logstart()
771
773
772 def init_aliases(self):
774 def init_aliases(self):
773 # dict of things NOT to alias (keywords, builtins and some magics)
775 # dict of things NOT to alias (keywords, builtins and some magics)
774 no_alias = {}
776 no_alias = {}
775 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
777 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
776 for key in keyword.kwlist + no_alias_magics:
778 for key in keyword.kwlist + no_alias_magics:
777 no_alias[key] = 1
779 no_alias[key] = 1
778 no_alias.update(__builtin__.__dict__)
780 no_alias.update(__builtin__.__dict__)
779 self.no_alias = no_alias
781 self.no_alias = no_alias
780
782
781 # Make some aliases automatically
783 # Make some aliases automatically
782 # Prepare list of shell aliases to auto-define
784 # Prepare list of shell aliases to auto-define
783 if os.name == 'posix':
785 if os.name == 'posix':
784 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
786 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
785 'mv mv -i','rm rm -i','cp cp -i',
787 'mv mv -i','rm rm -i','cp cp -i',
786 'cat cat','less less','clear clear',
788 'cat cat','less less','clear clear',
787 # a better ls
789 # a better ls
788 'ls ls -F',
790 'ls ls -F',
789 # long ls
791 # long ls
790 'll ls -lF')
792 'll ls -lF')
791 # Extra ls aliases with color, which need special treatment on BSD
793 # Extra ls aliases with color, which need special treatment on BSD
792 # variants
794 # variants
793 ls_extra = ( # color ls
795 ls_extra = ( # color ls
794 'lc ls -F -o --color',
796 'lc ls -F -o --color',
795 # ls normal files only
797 # ls normal files only
796 'lf ls -F -o --color %l | grep ^-',
798 'lf ls -F -o --color %l | grep ^-',
797 # ls symbolic links
799 # ls symbolic links
798 'lk ls -F -o --color %l | grep ^l',
800 'lk ls -F -o --color %l | grep ^l',
799 # directories or links to directories,
801 # directories or links to directories,
800 'ldir ls -F -o --color %l | grep /$',
802 'ldir ls -F -o --color %l | grep /$',
801 # things which are executable
803 # things which are executable
802 'lx ls -F -o --color %l | grep ^-..x',
804 'lx ls -F -o --color %l | grep ^-..x',
803 )
805 )
804 # The BSDs don't ship GNU ls, so they don't understand the
806 # The BSDs don't ship GNU ls, so they don't understand the
805 # --color switch out of the box
807 # --color switch out of the box
806 if 'bsd' in sys.platform:
808 if 'bsd' in sys.platform:
807 ls_extra = ( # ls normal files only
809 ls_extra = ( # ls normal files only
808 'lf ls -lF | grep ^-',
810 'lf ls -lF | grep ^-',
809 # ls symbolic links
811 # ls symbolic links
810 'lk ls -lF | grep ^l',
812 'lk ls -lF | grep ^l',
811 # directories or links to directories,
813 # directories or links to directories,
812 'ldir ls -lF | grep /$',
814 'ldir ls -lF | grep /$',
813 # things which are executable
815 # things which are executable
814 'lx ls -lF | grep ^-..x',
816 'lx ls -lF | grep ^-..x',
815 )
817 )
816 auto_alias = auto_alias + ls_extra
818 auto_alias = auto_alias + ls_extra
817 elif os.name in ['nt','dos']:
819 elif os.name in ['nt','dos']:
818 auto_alias = ('ls dir /on',
820 auto_alias = ('ls dir /on',
819 'ddir dir /ad /on', 'ldir dir /ad /on',
821 'ddir dir /ad /on', 'ldir dir /ad /on',
820 'mkdir mkdir','rmdir rmdir','echo echo',
822 'mkdir mkdir','rmdir rmdir','echo echo',
821 'ren ren','cls cls','copy copy')
823 'ren ren','cls cls','copy copy')
822 else:
824 else:
823 auto_alias = ()
825 auto_alias = ()
824 self.auto_alias = [s.split(None,1) for s in auto_alias]
826 self.auto_alias = [s.split(None,1) for s in auto_alias]
825
827
826 # Load default aliases
828 # Load default aliases
827 for alias, cmd in self.auto_alias:
829 for alias, cmd in self.auto_alias:
828 self.define_alias(alias,cmd)
830 self.define_alias(alias,cmd)
829
831
830 # Load user aliases
832 # Load user aliases
831 for alias in self.alias:
833 for alias in self.alias:
832 self.magic_alias(alias)
834 self.magic_alias(alias)
833
835
834 def init_builtins(self):
836 def init_builtins(self):
835 # track which builtins we add, so we can clean up later
837 # track which builtins we add, so we can clean up later
836 self.builtins_added = {}
838 self._orig_builtins = {}
837 # This method will add the necessary builtins for operation, but
839 self._builtins_added = False
838 # tracking what it did via the builtins_added dict.
839
840 #TODO: remove this, redundant. I don't understand why this is
841 # redundant?
842 self.add_builtins()
840 self.add_builtins()
843
841
844 def init_shadow_hist(self):
842 def init_shadow_hist(self):
845 try:
843 try:
846 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
844 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
847 except exceptions.UnicodeDecodeError:
845 except exceptions.UnicodeDecodeError:
848 print "Your ipythondir can't be decoded to unicode!"
846 print "Your ipythondir can't be decoded to unicode!"
849 print "Please set HOME environment variable to something that"
847 print "Please set HOME environment variable to something that"
850 print r"only has ASCII characters, e.g. c:\home"
848 print r"only has ASCII characters, e.g. c:\home"
851 print "Now it is", self.config.IPYTHONDIR
849 print "Now it is", self.config.IPYTHONDIR
852 sys.exit()
850 sys.exit()
853 self.shadowhist = ipcorehist.ShadowHist(self.db)
851 self.shadowhist = ipcorehist.ShadowHist(self.db)
854
852
855 def init_inspector(self):
853 def init_inspector(self):
856 # Object inspector
854 # Object inspector
857 self.inspector = oinspect.Inspector(oinspect.InspectColors,
855 self.inspector = oinspect.Inspector(oinspect.InspectColors,
858 PyColorize.ANSICodeColors,
856 PyColorize.ANSICodeColors,
859 'NoColor',
857 'NoColor',
860 self.object_info_string_level)
858 self.object_info_string_level)
861
859
862 def init_readline(self):
860 def init_readline(self):
863 """Command history completion/saving/reloading."""
861 """Command history completion/saving/reloading."""
864
862
865 self.rl_next_input = None
863 self.rl_next_input = None
866 self.rl_do_indent = False
864 self.rl_do_indent = False
867
865
868 if not self.readline_use:
866 if not self.readline_use:
869 return
867 return
870
868
871 import IPython.utils.rlineimpl as readline
869 import IPython.utils.rlineimpl as readline
872
870
873 if not readline.have_readline:
871 if not readline.have_readline:
874 self.has_readline = 0
872 self.has_readline = 0
875 self.readline = None
873 self.readline = None
876 # no point in bugging windows users with this every time:
874 # no point in bugging windows users with this every time:
877 warn('Readline services not available on this platform.')
875 warn('Readline services not available on this platform.')
878 else:
876 else:
879 sys.modules['readline'] = readline
877 sys.modules['readline'] = readline
880 import atexit
878 import atexit
881 from IPython.core.completer import IPCompleter
879 from IPython.core.completer import IPCompleter
882 self.Completer = IPCompleter(self,
880 self.Completer = IPCompleter(self,
883 self.user_ns,
881 self.user_ns,
884 self.user_global_ns,
882 self.user_global_ns,
885 self.readline_omit__names,
883 self.readline_omit__names,
886 self.alias_table)
884 self.alias_table)
887 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
885 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
888 self.strdispatchers['complete_command'] = sdisp
886 self.strdispatchers['complete_command'] = sdisp
889 self.Completer.custom_completers = sdisp
887 self.Completer.custom_completers = sdisp
890 # Platform-specific configuration
888 # Platform-specific configuration
891 if os.name == 'nt':
889 if os.name == 'nt':
892 self.readline_startup_hook = readline.set_pre_input_hook
890 self.readline_startup_hook = readline.set_pre_input_hook
893 else:
891 else:
894 self.readline_startup_hook = readline.set_startup_hook
892 self.readline_startup_hook = readline.set_startup_hook
895
893
896 # Load user's initrc file (readline config)
894 # Load user's initrc file (readline config)
897 # Or if libedit is used, load editrc.
895 # Or if libedit is used, load editrc.
898 inputrc_name = os.environ.get('INPUTRC')
896 inputrc_name = os.environ.get('INPUTRC')
899 if inputrc_name is None:
897 if inputrc_name is None:
900 home_dir = get_home_dir()
898 home_dir = get_home_dir()
901 if home_dir is not None:
899 if home_dir is not None:
902 inputrc_name = '.inputrc'
900 inputrc_name = '.inputrc'
903 if readline.uses_libedit:
901 if readline.uses_libedit:
904 inputrc_name = '.editrc'
902 inputrc_name = '.editrc'
905 inputrc_name = os.path.join(home_dir, inputrc_name)
903 inputrc_name = os.path.join(home_dir, inputrc_name)
906 if os.path.isfile(inputrc_name):
904 if os.path.isfile(inputrc_name):
907 try:
905 try:
908 readline.read_init_file(inputrc_name)
906 readline.read_init_file(inputrc_name)
909 except:
907 except:
910 warn('Problems reading readline initialization file <%s>'
908 warn('Problems reading readline initialization file <%s>'
911 % inputrc_name)
909 % inputrc_name)
912
910
913 self.has_readline = 1
911 self.has_readline = 1
914 self.readline = readline
912 self.readline = readline
915 # save this in sys so embedded copies can restore it properly
913 # save this in sys so embedded copies can restore it properly
916 sys.ipcompleter = self.Completer.complete
914 sys.ipcompleter = self.Completer.complete
917 self.set_completer()
915 self.set_completer()
918
916
919 # Configure readline according to user's prefs
917 # Configure readline according to user's prefs
920 # This is only done if GNU readline is being used. If libedit
918 # This is only done if GNU readline is being used. If libedit
921 # is being used (as on Leopard) the readline config is
919 # is being used (as on Leopard) the readline config is
922 # not run as the syntax for libedit is different.
920 # not run as the syntax for libedit is different.
923 if not readline.uses_libedit:
921 if not readline.uses_libedit:
924 for rlcommand in self.readline_parse_and_bind:
922 for rlcommand in self.readline_parse_and_bind:
925 #print "loading rl:",rlcommand # dbg
923 #print "loading rl:",rlcommand # dbg
926 readline.parse_and_bind(rlcommand)
924 readline.parse_and_bind(rlcommand)
927
925
928 # Remove some chars from the delimiters list. If we encounter
926 # Remove some chars from the delimiters list. If we encounter
929 # unicode chars, discard them.
927 # unicode chars, discard them.
930 delims = readline.get_completer_delims().encode("ascii", "ignore")
928 delims = readline.get_completer_delims().encode("ascii", "ignore")
931 delims = delims.translate(string._idmap,
929 delims = delims.translate(string._idmap,
932 self.readline_remove_delims)
930 self.readline_remove_delims)
933 readline.set_completer_delims(delims)
931 readline.set_completer_delims(delims)
934 # otherwise we end up with a monster history after a while:
932 # otherwise we end up with a monster history after a while:
935 readline.set_history_length(1000)
933 readline.set_history_length(1000)
936 try:
934 try:
937 #print '*** Reading readline history' # dbg
935 #print '*** Reading readline history' # dbg
938 readline.read_history_file(self.histfile)
936 readline.read_history_file(self.histfile)
939 except IOError:
937 except IOError:
940 pass # It doesn't exist yet.
938 pass # It doesn't exist yet.
941
939
942 atexit.register(self.atexit_operations)
940 atexit.register(self.atexit_operations)
943 del atexit
941 del atexit
944
942
945 # Configure auto-indent for all platforms
943 # Configure auto-indent for all platforms
946 self.set_autoindent(self.autoindent)
944 self.set_autoindent(self.autoindent)
947
945
948 def init_prompts(self):
946 def init_prompts(self):
949 # Initialize cache, set in/out prompts and printing system
947 # Initialize cache, set in/out prompts and printing system
950 self.outputcache = CachedOutput(self,
948 self.outputcache = CachedOutput(self,
951 self.cache_size,
949 self.cache_size,
952 self.pprint,
950 self.pprint,
953 input_sep = self.separate_in,
951 input_sep = self.separate_in,
954 output_sep = self.separate_out,
952 output_sep = self.separate_out,
955 output_sep2 = self.separate_out2,
953 output_sep2 = self.separate_out2,
956 ps1 = self.prompt_in1,
954 ps1 = self.prompt_in1,
957 ps2 = self.prompt_in2,
955 ps2 = self.prompt_in2,
958 ps_out = self.prompt_out,
956 ps_out = self.prompt_out,
959 pad_left = self.prompts_pad_left)
957 pad_left = self.prompts_pad_left)
960
958
961 # user may have over-ridden the default print hook:
959 # user may have over-ridden the default print hook:
962 try:
960 try:
963 self.outputcache.__class__.display = self.hooks.display
961 self.outputcache.__class__.display = self.hooks.display
964 except AttributeError:
962 except AttributeError:
965 pass
963 pass
966
964
967 def init_displayhook(self):
965 def init_displayhook(self):
968 # I don't like assigning globally to sys, because it means when
966 # I don't like assigning globally to sys, because it means when
969 # embedding instances, each embedded instance overrides the previous
967 # embedding instances, each embedded instance overrides the previous
970 # choice. But sys.displayhook seems to be called internally by exec,
968 # choice. But sys.displayhook seems to be called internally by exec,
971 # so I don't see a way around it. We first save the original and then
969 # so I don't see a way around it. We first save the original and then
972 # overwrite it.
970 # overwrite it.
973 self.sys_displayhook = sys.displayhook
971 self.sys_displayhook = sys.displayhook
974 sys.displayhook = self.outputcache
972 sys.displayhook = self.outputcache
975
973
976 def init_reload_doctest(self):
974 def init_reload_doctest(self):
977 # Do a proper resetting of doctest, including the necessary displayhook
975 # Do a proper resetting of doctest, including the necessary displayhook
978 # monkeypatching
976 # monkeypatching
979 try:
977 try:
980 doctest_reload()
978 doctest_reload()
981 except ImportError:
979 except ImportError:
982 warn("doctest module does not exist.")
980 warn("doctest module does not exist.")
983
981
984 def init_magics(self):
982 def init_magics(self):
985 # Set user colors (don't do it in the constructor above so that it
983 # Set user colors (don't do it in the constructor above so that it
986 # doesn't crash if colors option is invalid)
984 # doesn't crash if colors option is invalid)
987 self.magic_colors(self.colors)
985 self.magic_colors(self.colors)
988
986
989 def init_pdb(self):
987 def init_pdb(self):
990 # Set calling of pdb on exceptions
988 # Set calling of pdb on exceptions
991 # self.call_pdb is a property
989 # self.call_pdb is a property
992 self.call_pdb = self.pdb
990 self.call_pdb = self.pdb
993
991
994 # def init_exec_commands(self):
992 # def init_exec_commands(self):
995 # for cmd in self.config.EXECUTE:
993 # for cmd in self.config.EXECUTE:
996 # print "execute:", cmd
994 # print "execute:", cmd
997 # self.api.runlines(cmd)
995 # self.api.runlines(cmd)
998 #
996 #
999 # batchrun = False
997 # batchrun = False
1000 # if self.config.has_key('EXECFILE'):
998 # if self.config.has_key('EXECFILE'):
1001 # for batchfile in [path(arg) for arg in self.config.EXECFILE
999 # for batchfile in [path(arg) for arg in self.config.EXECFILE
1002 # if arg.lower().endswith('.ipy')]:
1000 # if arg.lower().endswith('.ipy')]:
1003 # if not batchfile.isfile():
1001 # if not batchfile.isfile():
1004 # print "No such batch file:", batchfile
1002 # print "No such batch file:", batchfile
1005 # continue
1003 # continue
1006 # self.api.runlines(batchfile.text())
1004 # self.api.runlines(batchfile.text())
1007 # batchrun = True
1005 # batchrun = True
1008 # # without -i option, exit after running the batch file
1006 # # without -i option, exit after running the batch file
1009 # if batchrun and not self.interactive:
1007 # if batchrun and not self.interactive:
1010 # self.ask_exit()
1008 # self.ask_exit()
1011
1009
1012 # def load(self, mod):
1010 # def load(self, mod):
1013 # """ Load an extension.
1011 # """ Load an extension.
1014 #
1012 #
1015 # Some modules should (or must) be 'load()':ed, rather than just imported.
1013 # Some modules should (or must) be 'load()':ed, rather than just imported.
1016 #
1014 #
1017 # Loading will do:
1015 # Loading will do:
1018 #
1016 #
1019 # - run init_ipython(ip)
1017 # - run init_ipython(ip)
1020 # - run ipython_firstrun(ip)
1018 # - run ipython_firstrun(ip)
1021 # """
1019 # """
1022 #
1020 #
1023 # if mod in self.extensions:
1021 # if mod in self.extensions:
1024 # # just to make sure we don't init it twice
1022 # # just to make sure we don't init it twice
1025 # # note that if you 'load' a module that has already been
1023 # # note that if you 'load' a module that has already been
1026 # # imported, init_ipython gets run anyway
1024 # # imported, init_ipython gets run anyway
1027 #
1025 #
1028 # return self.extensions[mod]
1026 # return self.extensions[mod]
1029 # __import__(mod)
1027 # __import__(mod)
1030 # m = sys.modules[mod]
1028 # m = sys.modules[mod]
1031 # if hasattr(m,'init_ipython'):
1029 # if hasattr(m,'init_ipython'):
1032 # m.init_ipython(self)
1030 # m.init_ipython(self)
1033 #
1031 #
1034 # if hasattr(m,'ipython_firstrun'):
1032 # if hasattr(m,'ipython_firstrun'):
1035 # already_loaded = self.db.get('firstrun_done', set())
1033 # already_loaded = self.db.get('firstrun_done', set())
1036 # if mod not in already_loaded:
1034 # if mod not in already_loaded:
1037 # m.ipython_firstrun(self)
1035 # m.ipython_firstrun(self)
1038 # already_loaded.add(mod)
1036 # already_loaded.add(mod)
1039 # self.db['firstrun_done'] = already_loaded
1037 # self.db['firstrun_done'] = already_loaded
1040 #
1038 #
1041 # self.extensions[mod] = m
1039 # self.extensions[mod] = m
1042 # return m
1040 # return m
1043
1041
1044 def init_namespaces(self):
1042 def init_user_ns(self):
1045 """Initialize all user-visible namespaces to their minimum defaults.
1043 """Initialize all user-visible namespaces to their minimum defaults.
1046
1044
1047 Certain history lists are also initialized here, as they effectively
1045 Certain history lists are also initialized here, as they effectively
1048 act as user namespaces.
1046 act as user namespaces.
1049
1047
1050 Notes
1048 Notes
1051 -----
1049 -----
1052 All data structures here are only filled in, they are NOT reset by this
1050 All data structures here are only filled in, they are NOT reset by this
1053 method. If they were not empty before, data will simply be added to
1051 method. If they were not empty before, data will simply be added to
1054 therm.
1052 therm.
1055 """
1053 """
1056 # The user namespace MUST have a pointer to the shell itself.
1054 # The user namespace MUST have a pointer to the shell itself.
1057 self.user_ns[self.name] = self
1055 self.user_ns[self.name] = self
1058
1056
1059 # Store myself as the public api!!!
1057 # Store myself as the public api!!!
1060 self.user_ns['_ip'] = self
1058 self.user_ns['_ip'] = self
1061
1059
1062 # make global variables for user access to the histories
1060 # make global variables for user access to the histories
1063 self.user_ns['_ih'] = self.input_hist
1061 self.user_ns['_ih'] = self.input_hist
1064 self.user_ns['_oh'] = self.output_hist
1062 self.user_ns['_oh'] = self.output_hist
1065 self.user_ns['_dh'] = self.dir_hist
1063 self.user_ns['_dh'] = self.dir_hist
1066
1064
1067 # user aliases to input and output histories
1065 # user aliases to input and output histories
1068 self.user_ns['In'] = self.input_hist
1066 self.user_ns['In'] = self.input_hist
1069 self.user_ns['Out'] = self.output_hist
1067 self.user_ns['Out'] = self.output_hist
1070
1068
1071 self.user_ns['_sh'] = shadowns
1069 self.user_ns['_sh'] = shadowns
1072
1070
1073 # Put 'help' in the user namespace
1071 # Put 'help' in the user namespace
1074 try:
1072 try:
1075 from site import _Helper
1073 from site import _Helper
1076 self.user_ns['help'] = _Helper()
1074 self.user_ns['help'] = _Helper()
1077 except ImportError:
1075 except ImportError:
1078 warn('help() not available - check site.py')
1076 warn('help() not available - check site.py')
1079
1077
1078 def add_builtin(self, key, value):
1079 """Add a builtin and save the original."""
1080 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
1081 self._orig_builtins[key] = orig
1082 __builtin__.__dict__[key] = value
1083
1084 def remove_builtin(self, key):
1085 """Remove an added builtin and re-set the original."""
1086 try:
1087 orig = self._orig_builtins.pop(key)
1088 except KeyError:
1089 pass
1090 else:
1091 if orig is BuiltinUndefined:
1092 del __builtin__.__dict__[key]
1093 else:
1094 __builtin__.__dict__[key] = orig
1095
1080 def add_builtins(self):
1096 def add_builtins(self):
1081 """Store ipython references into the __builtin__ namespace.
1097 """Store ipython references into the __builtin__ namespace.
1082
1098
1083 We strive to modify the __builtin__ namespace as little as possible.
1099 We strive to modify the __builtin__ namespace as little as possible.
1084 """
1100 """
1101 if not self._builtins_added:
1102 self.add_builtin('exit', Quitter(self,'exit'))
1103 self.add_builtin('quit', Quitter(self,'quit'))
1085
1104
1086 # Install our own quitter instead of the builtins.
1105 # Recursive reload function
1087 # This used to be in the __init__ method, but this is a better
1088 # place for it. These can be incorporated to the logic below
1089 # when it is refactored.
1090 __builtin__.exit = Quitter(self,'exit')
1091 __builtin__.quit = Quitter(self,'quit')
1092
1093 # Recursive reload
1094 try:
1106 try:
1095 from IPython.lib import deepreload
1107 from IPython.lib import deepreload
1096 if self.deep_reload:
1108 if self.deep_reload:
1097 __builtin__.reload = deepreload.reload
1109 self.add_builtin('reload', deepreload.reload)
1098 else:
1110 else:
1099 __builtin__.dreload = deepreload.reload
1111 self.add_builtin('dreload', deepreload.reload)
1100 del deepreload
1112 del deepreload
1101 except ImportError:
1113 except ImportError:
1102 pass
1114 pass
1103
1115
1104 # Keep in the builtins a flag for when IPython is active. We set it
1116 # Keep in the builtins a flag for when IPython is active. We set it
1105 # with setdefault so that multiple nested IPythons don't clobber one
1117 # with setdefault so that multiple nested IPythons don't clobber one
1106 # another. Each will increase its value by one upon being activated,
1118 # another. Each will increase its value by one upon being activated,
1107 # which also gives us a way to determine the nesting level.
1119 # which also gives us a way to determine the nesting level.
1108 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
1120 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
1121 self._builtins_added = True
1109
1122
1110 def clean_builtins(self):
1123 def remove_builtins(self):
1111 """Remove any builtins which might have been added by add_builtins, or
1124 """Remove any builtins which might have been added by add_builtins, or
1112 restore overwritten ones to their previous values."""
1125 restore overwritten ones to their previous values."""
1113 for biname,bival in self.builtins_added.items():
1126 if self._builtins_added:
1114 if bival is Undefined:
1127 for key in self._orig_builtins.keys():
1115 del __builtin__.__dict__[biname]
1128 self.remove_builtin(key)
1116 else:
1129 self._orig_builtins.clear()
1117 __builtin__.__dict__[biname] = bival
1130 self._builtins_added = False
1118 self.builtins_added.clear()
1131
1132 def save_sys_module_state(self):
1133 """Save the state of hooks in the sys module.
1134
1135 This has to be called after self.user_ns is created.
1136 """
1137 self._orig_sys_module_state = {}
1138 self._orig_sys_module_state['stdin'] = sys.stdin
1139 self._orig_sys_module_state['stdout'] = sys.stdout
1140 self._orig_sys_module_state['stderr'] = sys.stderr
1141 self._orig_sys_module_state['displayhook'] = sys.displayhook
1142 self._orig_sys_module_state['excepthook'] = sys.excepthook
1143 try:
1144 self._orig_sys_modules_main_name = self.user_ns['__name__']
1145 except KeyError:
1146 pass
1147
1148 def restore_sys_module_state(self):
1149 """Restore the state of the sys module."""
1150 try:
1151 for k, v in self._orig_sys_module_state.items():
1152 setattr(sys, k, v)
1153 except AttributeError:
1154 pass
1155 try:
1156 delattr(sys, 'ipcompleter')
1157 except AttributeError:
1158 pass
1159 # Reset what what done in self.init_sys_modules
1160 try:
1161 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
1162 except (AttributeError, KeyError):
1163 pass
1119
1164
1120 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1165 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1121 """set_hook(name,hook) -> sets an internal IPython hook.
1166 """set_hook(name,hook) -> sets an internal IPython hook.
1122
1167
1123 IPython exposes some of its internal API as user-modifiable hooks. By
1168 IPython exposes some of its internal API as user-modifiable hooks. By
1124 adding your function to one of these hooks, you can modify IPython's
1169 adding your function to one of these hooks, you can modify IPython's
1125 behavior to call at runtime your own routines."""
1170 behavior to call at runtime your own routines."""
1126
1171
1127 # At some point in the future, this should validate the hook before it
1172 # At some point in the future, this should validate the hook before it
1128 # accepts it. Probably at least check that the hook takes the number
1173 # accepts it. Probably at least check that the hook takes the number
1129 # of args it's supposed to.
1174 # of args it's supposed to.
1130
1175
1131 f = new.instancemethod(hook,self,self.__class__)
1176 f = new.instancemethod(hook,self,self.__class__)
1132
1177
1133 # check if the hook is for strdispatcher first
1178 # check if the hook is for strdispatcher first
1134 if str_key is not None:
1179 if str_key is not None:
1135 sdp = self.strdispatchers.get(name, StrDispatch())
1180 sdp = self.strdispatchers.get(name, StrDispatch())
1136 sdp.add_s(str_key, f, priority )
1181 sdp.add_s(str_key, f, priority )
1137 self.strdispatchers[name] = sdp
1182 self.strdispatchers[name] = sdp
1138 return
1183 return
1139 if re_key is not None:
1184 if re_key is not None:
1140 sdp = self.strdispatchers.get(name, StrDispatch())
1185 sdp = self.strdispatchers.get(name, StrDispatch())
1141 sdp.add_re(re.compile(re_key), f, priority )
1186 sdp.add_re(re.compile(re_key), f, priority )
1142 self.strdispatchers[name] = sdp
1187 self.strdispatchers[name] = sdp
1143 return
1188 return
1144
1189
1145 dp = getattr(self.hooks, name, None)
1190 dp = getattr(self.hooks, name, None)
1146 if name not in IPython.core.hooks.__all__:
1191 if name not in IPython.core.hooks.__all__:
1147 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1192 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1148 if not dp:
1193 if not dp:
1149 dp = IPython.core.hooks.CommandChainDispatcher()
1194 dp = IPython.core.hooks.CommandChainDispatcher()
1150
1195
1151 try:
1196 try:
1152 dp.add(f,priority)
1197 dp.add(f,priority)
1153 except AttributeError:
1198 except AttributeError:
1154 # it was not commandchain, plain old func - replace
1199 # it was not commandchain, plain old func - replace
1155 dp = f
1200 dp = f
1156
1201
1157 setattr(self.hooks,name, dp)
1202 setattr(self.hooks,name, dp)
1158
1203
1159
1160 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1161
1162 def set_crash_handler(self,crashHandler):
1204 def set_crash_handler(self, crashHandler):
1163 """Set the IPython crash handler.
1205 """Set the IPython crash handler.
1164
1206
1165 This must be a callable with a signature suitable for use as
1207 This must be a callable with a signature suitable for use as
1166 sys.excepthook."""
1208 sys.excepthook."""
1167
1209
1168 # Install the given crash handler as the Python exception hook
1210 # Install the given crash handler as the Python exception hook
1169 sys.excepthook = crashHandler
1211 sys.excepthook = crashHandler
1170
1212
1171 # The instance will store a pointer to this, so that runtime code
1213 # The instance will store a pointer to this, so that runtime code
1172 # (such as magics) can access it. This is because during the
1214 # (such as magics) can access it. This is because during the
1173 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1215 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1174 # frameworks).
1216 # frameworks).
1175 self.sys_excepthook = sys.excepthook
1217 self.sys_excepthook = sys.excepthook
1176
1218
1177
1178 def set_custom_exc(self,exc_tuple,handler):
1219 def set_custom_exc(self,exc_tuple,handler):
1179 """set_custom_exc(exc_tuple,handler)
1220 """set_custom_exc(exc_tuple,handler)
1180
1221
1181 Set a custom exception handler, which will be called if any of the
1222 Set a custom exception handler, which will be called if any of the
1182 exceptions in exc_tuple occur in the mainloop (specifically, in the
1223 exceptions in exc_tuple occur in the mainloop (specifically, in the
1183 runcode() method.
1224 runcode() method.
1184
1225
1185 Inputs:
1226 Inputs:
1186
1227
1187 - exc_tuple: a *tuple* of valid exceptions to call the defined
1228 - exc_tuple: a *tuple* of valid exceptions to call the defined
1188 handler for. It is very important that you use a tuple, and NOT A
1229 handler for. It is very important that you use a tuple, and NOT A
1189 LIST here, because of the way Python's except statement works. If
1230 LIST here, because of the way Python's except statement works. If
1190 you only want to trap a single exception, use a singleton tuple:
1231 you only want to trap a single exception, use a singleton tuple:
1191
1232
1192 exc_tuple == (MyCustomException,)
1233 exc_tuple == (MyCustomException,)
1193
1234
1194 - handler: this must be defined as a function with the following
1235 - handler: this must be defined as a function with the following
1195 basic interface: def my_handler(self,etype,value,tb).
1236 basic interface: def my_handler(self,etype,value,tb).
1196
1237
1197 This will be made into an instance method (via new.instancemethod)
1238 This will be made into an instance method (via new.instancemethod)
1198 of IPython itself, and it will be called if any of the exceptions
1239 of IPython itself, and it will be called if any of the exceptions
1199 listed in the exc_tuple are caught. If the handler is None, an
1240 listed in the exc_tuple are caught. If the handler is None, an
1200 internal basic one is used, which just prints basic info.
1241 internal basic one is used, which just prints basic info.
1201
1242
1202 WARNING: by putting in your own exception handler into IPython's main
1243 WARNING: by putting in your own exception handler into IPython's main
1203 execution loop, you run a very good chance of nasty crashes. This
1244 execution loop, you run a very good chance of nasty crashes. This
1204 facility should only be used if you really know what you are doing."""
1245 facility should only be used if you really know what you are doing."""
1205
1246
1206 assert type(exc_tuple)==type(()) , \
1247 assert type(exc_tuple)==type(()) , \
1207 "The custom exceptions must be given AS A TUPLE."
1248 "The custom exceptions must be given AS A TUPLE."
1208
1249
1209 def dummy_handler(self,etype,value,tb):
1250 def dummy_handler(self,etype,value,tb):
1210 print '*** Simple custom exception handler ***'
1251 print '*** Simple custom exception handler ***'
1211 print 'Exception type :',etype
1252 print 'Exception type :',etype
1212 print 'Exception value:',value
1253 print 'Exception value:',value
1213 print 'Traceback :',tb
1254 print 'Traceback :',tb
1214 print 'Source code :','\n'.join(self.buffer)
1255 print 'Source code :','\n'.join(self.buffer)
1215
1256
1216 if handler is None: handler = dummy_handler
1257 if handler is None: handler = dummy_handler
1217
1258
1218 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1259 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1219 self.custom_exceptions = exc_tuple
1260 self.custom_exceptions = exc_tuple
1220
1261
1221 def set_custom_completer(self,completer,pos=0):
1262 def set_custom_completer(self,completer,pos=0):
1222 """set_custom_completer(completer,pos=0)
1263 """set_custom_completer(completer,pos=0)
1223
1264
1224 Adds a new custom completer function.
1265 Adds a new custom completer function.
1225
1266
1226 The position argument (defaults to 0) is the index in the completers
1267 The position argument (defaults to 0) is the index in the completers
1227 list where you want the completer to be inserted."""
1268 list where you want the completer to be inserted."""
1228
1269
1229 newcomp = new.instancemethod(completer,self.Completer,
1270 newcomp = new.instancemethod(completer,self.Completer,
1230 self.Completer.__class__)
1271 self.Completer.__class__)
1231 self.Completer.matchers.insert(pos,newcomp)
1272 self.Completer.matchers.insert(pos,newcomp)
1232
1273
1233 def set_completer(self):
1274 def set_completer(self):
1234 """reset readline's completer to be our own."""
1275 """reset readline's completer to be our own."""
1235 self.readline.set_completer(self.Completer.complete)
1276 self.readline.set_completer(self.Completer.complete)
1236
1277
1237 def _get_call_pdb(self):
1278 def _get_call_pdb(self):
1238 return self._call_pdb
1279 return self._call_pdb
1239
1280
1240 def _set_call_pdb(self,val):
1281 def _set_call_pdb(self,val):
1241
1282
1242 if val not in (0,1,False,True):
1283 if val not in (0,1,False,True):
1243 raise ValueError,'new call_pdb value must be boolean'
1284 raise ValueError,'new call_pdb value must be boolean'
1244
1285
1245 # store value in instance
1286 # store value in instance
1246 self._call_pdb = val
1287 self._call_pdb = val
1247
1288
1248 # notify the actual exception handlers
1289 # notify the actual exception handlers
1249 self.InteractiveTB.call_pdb = val
1290 self.InteractiveTB.call_pdb = val
1250 if self.isthreaded:
1291 if self.isthreaded:
1251 try:
1292 try:
1252 self.sys_excepthook.call_pdb = val
1293 self.sys_excepthook.call_pdb = val
1253 except:
1294 except:
1254 warn('Failed to activate pdb for threaded exception handler')
1295 warn('Failed to activate pdb for threaded exception handler')
1255
1296
1256 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1297 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1257 'Control auto-activation of pdb at exceptions')
1298 'Control auto-activation of pdb at exceptions')
1258
1299
1259 def magic(self,arg_s):
1300 def magic(self,arg_s):
1260 """Call a magic function by name.
1301 """Call a magic function by name.
1261
1302
1262 Input: a string containing the name of the magic function to call and any
1303 Input: a string containing the name of the magic function to call and any
1263 additional arguments to be passed to the magic.
1304 additional arguments to be passed to the magic.
1264
1305
1265 magic('name -opt foo bar') is equivalent to typing at the ipython
1306 magic('name -opt foo bar') is equivalent to typing at the ipython
1266 prompt:
1307 prompt:
1267
1308
1268 In[1]: %name -opt foo bar
1309 In[1]: %name -opt foo bar
1269
1310
1270 To call a magic without arguments, simply use magic('name').
1311 To call a magic without arguments, simply use magic('name').
1271
1312
1272 This provides a proper Python function to call IPython's magics in any
1313 This provides a proper Python function to call IPython's magics in any
1273 valid Python code you can type at the interpreter, including loops and
1314 valid Python code you can type at the interpreter, including loops and
1274 compound statements.
1315 compound statements.
1275 """
1316 """
1276
1317
1277 args = arg_s.split(' ',1)
1318 args = arg_s.split(' ',1)
1278 magic_name = args[0]
1319 magic_name = args[0]
1279 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1320 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1280
1321
1281 try:
1322 try:
1282 magic_args = args[1]
1323 magic_args = args[1]
1283 except IndexError:
1324 except IndexError:
1284 magic_args = ''
1325 magic_args = ''
1285 fn = getattr(self,'magic_'+magic_name,None)
1326 fn = getattr(self,'magic_'+magic_name,None)
1286 if fn is None:
1327 if fn is None:
1287 error("Magic function `%s` not found." % magic_name)
1328 error("Magic function `%s` not found." % magic_name)
1288 else:
1329 else:
1289 magic_args = self.var_expand(magic_args,1)
1330 magic_args = self.var_expand(magic_args,1)
1290 return fn(magic_args)
1331 return fn(magic_args)
1291
1332
1292 def define_magic(self, magicname, func):
1333 def define_magic(self, magicname, func):
1293 """Expose own function as magic function for ipython
1334 """Expose own function as magic function for ipython
1294
1335
1295 def foo_impl(self,parameter_s=''):
1336 def foo_impl(self,parameter_s=''):
1296 'My very own magic!. (Use docstrings, IPython reads them).'
1337 'My very own magic!. (Use docstrings, IPython reads them).'
1297 print 'Magic function. Passed parameter is between < >:'
1338 print 'Magic function. Passed parameter is between < >:'
1298 print '<%s>' % parameter_s
1339 print '<%s>' % parameter_s
1299 print 'The self object is:',self
1340 print 'The self object is:',self
1300
1341
1301 self.define_magic('foo',foo_impl)
1342 self.define_magic('foo',foo_impl)
1302 """
1343 """
1303
1344
1304 import new
1345 import new
1305 im = new.instancemethod(func,self, self.__class__)
1346 im = new.instancemethod(func,self, self.__class__)
1306 old = getattr(self, "magic_" + magicname, None)
1347 old = getattr(self, "magic_" + magicname, None)
1307 setattr(self, "magic_" + magicname, im)
1348 setattr(self, "magic_" + magicname, im)
1308 return old
1349 return old
1309
1350
1310 def define_macro(self, name, themacro):
1351 def define_macro(self, name, themacro):
1311 """Define a new macro
1352 """Define a new macro
1312
1353
1313 Parameters
1354 Parameters
1314 ----------
1355 ----------
1315 name : str
1356 name : str
1316 The name of the macro.
1357 The name of the macro.
1317 themacro : str or Macro
1358 themacro : str or Macro
1318 The action to do upon invoking the macro. If a string, a new
1359 The action to do upon invoking the macro. If a string, a new
1319 Macro object is created by passing the string to it.
1360 Macro object is created by passing the string to it.
1320 """
1361 """
1321
1362
1322 from IPython.core import macro
1363 from IPython.core import macro
1323
1364
1324 if isinstance(themacro, basestring):
1365 if isinstance(themacro, basestring):
1325 themacro = macro.Macro(themacro)
1366 themacro = macro.Macro(themacro)
1326 if not isinstance(themacro, macro.Macro):
1367 if not isinstance(themacro, macro.Macro):
1327 raise ValueError('A macro must be a string or a Macro instance.')
1368 raise ValueError('A macro must be a string or a Macro instance.')
1328 self.user_ns[name] = themacro
1369 self.user_ns[name] = themacro
1329
1370
1330 def define_alias(self, name, cmd):
1371 def define_alias(self, name, cmd):
1331 """ Define a new alias."""
1372 """ Define a new alias."""
1332
1373
1333 if callable(cmd):
1374 if callable(cmd):
1334 self.alias_table[name] = cmd
1375 self.alias_table[name] = cmd
1335 from IPython.core import shadowns
1376 from IPython.core import shadowns
1336 setattr(shadowns, name, cmd)
1377 setattr(shadowns, name, cmd)
1337 return
1378 return
1338
1379
1339 if isinstance(cmd, basestring):
1380 if isinstance(cmd, basestring):
1340 nargs = cmd.count('%s')
1381 nargs = cmd.count('%s')
1341 if nargs>0 and cmd.find('%l')>=0:
1382 if nargs>0 and cmd.find('%l')>=0:
1342 raise Exception('The %s and %l specifiers are mutually '
1383 raise Exception('The %s and %l specifiers are mutually '
1343 'exclusive in alias definitions.')
1384 'exclusive in alias definitions.')
1344
1385
1345 self.alias_table[name] = (nargs,cmd)
1386 self.alias_table[name] = (nargs,cmd)
1346 return
1387 return
1347
1388
1348 self.alias_table[name] = cmd
1389 self.alias_table[name] = cmd
1349
1390
1350 def ipalias(self,arg_s):
1391 def ipalias(self,arg_s):
1351 """Call an alias by name.
1392 """Call an alias by name.
1352
1393
1353 Input: a string containing the name of the alias to call and any
1394 Input: a string containing the name of the alias to call and any
1354 additional arguments to be passed to the magic.
1395 additional arguments to be passed to the magic.
1355
1396
1356 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1397 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1357 prompt:
1398 prompt:
1358
1399
1359 In[1]: name -opt foo bar
1400 In[1]: name -opt foo bar
1360
1401
1361 To call an alias without arguments, simply use ipalias('name').
1402 To call an alias without arguments, simply use ipalias('name').
1362
1403
1363 This provides a proper Python function to call IPython's aliases in any
1404 This provides a proper Python function to call IPython's aliases in any
1364 valid Python code you can type at the interpreter, including loops and
1405 valid Python code you can type at the interpreter, including loops and
1365 compound statements. It is added by IPython to the Python builtin
1406 compound statements. It is added by IPython to the Python builtin
1366 namespace upon initialization."""
1407 namespace upon initialization."""
1367
1408
1368 args = arg_s.split(' ',1)
1409 args = arg_s.split(' ',1)
1369 alias_name = args[0]
1410 alias_name = args[0]
1370 try:
1411 try:
1371 alias_args = args[1]
1412 alias_args = args[1]
1372 except IndexError:
1413 except IndexError:
1373 alias_args = ''
1414 alias_args = ''
1374 if alias_name in self.alias_table:
1415 if alias_name in self.alias_table:
1375 self.call_alias(alias_name,alias_args)
1416 self.call_alias(alias_name,alias_args)
1376 else:
1417 else:
1377 error("Alias `%s` not found." % alias_name)
1418 error("Alias `%s` not found." % alias_name)
1378
1419
1379 def system(self, cmd):
1420 def system(self, cmd):
1380 """Make a system call, using IPython."""
1421 """Make a system call, using IPython."""
1381 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1422 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1382
1423
1383 def ex(self, cmd):
1424 def ex(self, cmd):
1384 """Execute a normal python statement in user namespace."""
1425 """Execute a normal python statement in user namespace."""
1385 exec cmd in self.user_ns
1426 exec cmd in self.user_global_ns, self.user_ns
1386
1427
1387 def ev(self, expr):
1428 def ev(self, expr):
1388 """Evaluate python expression expr in user namespace.
1429 """Evaluate python expression expr in user namespace.
1389
1430
1390 Returns the result of evaluation
1431 Returns the result of evaluation
1391 """
1432 """
1392 return eval(expr,self.user_ns)
1433 return eval(expr, self.user_global_ns, self.user_ns)
1393
1434
1394 def getoutput(self, cmd):
1435 def getoutput(self, cmd):
1395 return getoutput(self.var_expand(cmd,depth=2),
1436 return getoutput(self.var_expand(cmd,depth=2),
1396 header=self.system_header,
1437 header=self.system_header,
1397 verbose=self.system_verbose)
1438 verbose=self.system_verbose)
1398
1439
1399 def getoutputerror(self, cmd):
1440 def getoutputerror(self, cmd):
1400 return getoutputerror(self.var_expand(cmd,depth=2),
1441 return getoutputerror(self.var_expand(cmd,depth=2),
1401 header=self.system_header,
1442 header=self.system_header,
1402 verbose=self.system_verbose)
1443 verbose=self.system_verbose)
1403
1444
1404 def complete(self,text):
1445 def complete(self, text):
1405 """Return a sorted list of all possible completions on text.
1446 """Return a sorted list of all possible completions on text.
1406
1447
1407 Inputs:
1448 Inputs:
1408
1449
1409 - text: a string of text to be completed on.
1450 - text: a string of text to be completed on.
1410
1451
1411 This is a wrapper around the completion mechanism, similar to what
1452 This is a wrapper around the completion mechanism, similar to what
1412 readline does at the command line when the TAB key is hit. By
1453 readline does at the command line when the TAB key is hit. By
1413 exposing it as a method, it can be used by other non-readline
1454 exposing it as a method, it can be used by other non-readline
1414 environments (such as GUIs) for text completion.
1455 environments (such as GUIs) for text completion.
1415
1456
1416 Simple usage example:
1457 Simple usage example:
1417
1458
1418 In [7]: x = 'hello'
1459 In [7]: x = 'hello'
1419
1460
1420 In [8]: x
1461 In [8]: x
1421 Out[8]: 'hello'
1462 Out[8]: 'hello'
1422
1463
1423 In [9]: print x
1464 In [9]: print x
1424 hello
1465 hello
1425
1466
1426 In [10]: _ip.complete('x.l')
1467 In [10]: _ip.complete('x.l')
1427 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1468 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1428 """
1469 """
1429
1470
1430 complete = self.Completer.complete
1471 complete = self.Completer.complete
1431 state = 0
1472 state = 0
1432 # use a dict so we get unique keys, since ipyhton's multiple
1473 # use a dict so we get unique keys, since ipyhton's multiple
1433 # completers can return duplicates. When we make 2.4 a requirement,
1474 # completers can return duplicates. When we make 2.4 a requirement,
1434 # start using sets instead, which are faster.
1475 # start using sets instead, which are faster.
1435 comps = {}
1476 comps = {}
1436 while True:
1477 while True:
1437 newcomp = complete(text,state,line_buffer=text)
1478 newcomp = complete(text,state,line_buffer=text)
1438 if newcomp is None:
1479 if newcomp is None:
1439 break
1480 break
1440 comps[newcomp] = 1
1481 comps[newcomp] = 1
1441 state += 1
1482 state += 1
1442 outcomps = comps.keys()
1483 outcomps = comps.keys()
1443 outcomps.sort()
1484 outcomps.sort()
1444 #print "T:",text,"OC:",outcomps # dbg
1485 #print "T:",text,"OC:",outcomps # dbg
1445 #print "vars:",self.user_ns.keys()
1486 #print "vars:",self.user_ns.keys()
1446 return outcomps
1487 return outcomps
1447
1488
1448 def set_completer_frame(self, frame=None):
1489 def set_completer_frame(self, frame=None):
1449 if frame:
1490 if frame:
1450 self.Completer.namespace = frame.f_locals
1491 self.Completer.namespace = frame.f_locals
1451 self.Completer.global_namespace = frame.f_globals
1492 self.Completer.global_namespace = frame.f_globals
1452 else:
1493 else:
1453 self.Completer.namespace = self.user_ns
1494 self.Completer.namespace = self.user_ns
1454 self.Completer.global_namespace = self.user_global_ns
1495 self.Completer.global_namespace = self.user_global_ns
1455
1496
1456 def init_auto_alias(self):
1497 def init_auto_alias(self):
1457 """Define some aliases automatically.
1498 """Define some aliases automatically.
1458
1499
1459 These are ALL parameter-less aliases"""
1500 These are ALL parameter-less aliases"""
1460
1501
1461 for alias,cmd in self.auto_alias:
1502 for alias,cmd in self.auto_alias:
1462 self.define_alias(alias,cmd)
1503 self.define_alias(alias,cmd)
1463
1504
1464 def alias_table_validate(self,verbose=0):
1505 def alias_table_validate(self,verbose=0):
1465 """Update information about the alias table.
1506 """Update information about the alias table.
1466
1507
1467 In particular, make sure no Python keywords/builtins are in it."""
1508 In particular, make sure no Python keywords/builtins are in it."""
1468
1509
1469 no_alias = self.no_alias
1510 no_alias = self.no_alias
1470 for k in self.alias_table.keys():
1511 for k in self.alias_table.keys():
1471 if k in no_alias:
1512 if k in no_alias:
1472 del self.alias_table[k]
1513 del self.alias_table[k]
1473 if verbose:
1514 if verbose:
1474 print ("Deleting alias <%s>, it's a Python "
1515 print ("Deleting alias <%s>, it's a Python "
1475 "keyword or builtin." % k)
1516 "keyword or builtin." % k)
1476
1517
1477 def set_next_input(self, s):
1518 def set_next_input(self, s):
1478 """ Sets the 'default' input string for the next command line.
1519 """ Sets the 'default' input string for the next command line.
1479
1520
1480 Requires readline.
1521 Requires readline.
1481
1522
1482 Example:
1523 Example:
1483
1524
1484 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1525 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1485 [D:\ipython]|2> Hello Word_ # cursor is here
1526 [D:\ipython]|2> Hello Word_ # cursor is here
1486 """
1527 """
1487
1528
1488 self.rl_next_input = s
1529 self.rl_next_input = s
1489
1530
1490 def set_autoindent(self,value=None):
1531 def set_autoindent(self,value=None):
1491 """Set the autoindent flag, checking for readline support.
1532 """Set the autoindent flag, checking for readline support.
1492
1533
1493 If called with no arguments, it acts as a toggle."""
1534 If called with no arguments, it acts as a toggle."""
1494
1535
1495 if not self.has_readline:
1536 if not self.has_readline:
1496 if os.name == 'posix':
1537 if os.name == 'posix':
1497 warn("The auto-indent feature requires the readline library")
1538 warn("The auto-indent feature requires the readline library")
1498 self.autoindent = 0
1539 self.autoindent = 0
1499 return
1540 return
1500 if value is None:
1541 if value is None:
1501 self.autoindent = not self.autoindent
1542 self.autoindent = not self.autoindent
1502 else:
1543 else:
1503 self.autoindent = value
1544 self.autoindent = value
1504
1545
1505 def atexit_operations(self):
1546 def atexit_operations(self):
1506 """This will be executed at the time of exit.
1547 """This will be executed at the time of exit.
1507
1548
1508 Saving of persistent data should be performed here. """
1549 Saving of persistent data should be performed here. """
1509
1550
1510 #print '*** IPython exit cleanup ***' # dbg
1551 #print '*** IPython exit cleanup ***' # dbg
1511 # input history
1552 # input history
1512 self.savehist()
1553 self.savehist()
1513
1554
1514 # Cleanup all tempfiles left around
1555 # Cleanup all tempfiles left around
1515 for tfile in self.tempfiles:
1556 for tfile in self.tempfiles:
1516 try:
1557 try:
1517 os.unlink(tfile)
1558 os.unlink(tfile)
1518 except OSError:
1559 except OSError:
1519 pass
1560 pass
1520
1561
1521 # Clear all user namespaces to release all references cleanly.
1562 # Clear all user namespaces to release all references cleanly.
1522 self.reset()
1563 self.reset()
1523
1564
1524 # Run user hooks
1565 # Run user hooks
1525 self.hooks.shutdown_hook()
1566 self.hooks.shutdown_hook()
1526
1567
1527 def reset(self):
1568 def reset(self):
1528 """Clear all internal namespaces.
1569 """Clear all internal namespaces.
1529
1570
1530 Note that this is much more aggressive than %reset, since it clears
1571 Note that this is much more aggressive than %reset, since it clears
1531 fully all namespaces, as well as all input/output lists.
1572 fully all namespaces, as well as all input/output lists.
1532 """
1573 """
1533 for ns in self.ns_refs_table:
1574 for ns in self.ns_refs_table:
1534 ns.clear()
1575 ns.clear()
1535
1576
1536 # Clear input and output histories
1577 # Clear input and output histories
1537 self.input_hist[:] = []
1578 self.input_hist[:] = []
1538 self.input_hist_raw[:] = []
1579 self.input_hist_raw[:] = []
1539 self.output_hist.clear()
1580 self.output_hist.clear()
1540 # Restore the user namespaces to minimal usability
1581 # Restore the user namespaces to minimal usability
1541 self.init_namespaces()
1582 self.init_user_ns()
1542
1583
1543 def savehist(self):
1584 def savehist(self):
1544 """Save input history to a file (via readline library)."""
1585 """Save input history to a file (via readline library)."""
1545
1586
1546 if not self.has_readline:
1587 if not self.has_readline:
1547 return
1588 return
1548
1589
1549 try:
1590 try:
1550 self.readline.write_history_file(self.histfile)
1591 self.readline.write_history_file(self.histfile)
1551 except:
1592 except:
1552 print 'Unable to save IPython command history to file: ' + \
1593 print 'Unable to save IPython command history to file: ' + \
1553 `self.histfile`
1594 `self.histfile`
1554
1595
1555 def reloadhist(self):
1596 def reloadhist(self):
1556 """Reload the input history from disk file."""
1597 """Reload the input history from disk file."""
1557
1598
1558 if self.has_readline:
1599 if self.has_readline:
1559 try:
1600 try:
1560 self.readline.clear_history()
1601 self.readline.clear_history()
1561 self.readline.read_history_file(self.shell.histfile)
1602 self.readline.read_history_file(self.shell.histfile)
1562 except AttributeError:
1603 except AttributeError:
1563 pass
1604 pass
1564
1605
1565
1606
1566 def history_saving_wrapper(self, func):
1607 def history_saving_wrapper(self, func):
1567 """ Wrap func for readline history saving
1608 """ Wrap func for readline history saving
1568
1609
1569 Convert func into callable that saves & restores
1610 Convert func into callable that saves & restores
1570 history around the call """
1611 history around the call """
1571
1612
1572 if not self.has_readline:
1613 if not self.has_readline:
1573 return func
1614 return func
1574
1615
1575 def wrapper():
1616 def wrapper():
1576 self.savehist()
1617 self.savehist()
1577 try:
1618 try:
1578 func()
1619 func()
1579 finally:
1620 finally:
1580 readline.read_history_file(self.histfile)
1621 readline.read_history_file(self.histfile)
1581 return wrapper
1622 return wrapper
1582
1623
1583 def pre_readline(self):
1624 def pre_readline(self):
1584 """readline hook to be used at the start of each line.
1625 """readline hook to be used at the start of each line.
1585
1626
1586 Currently it handles auto-indent only."""
1627 Currently it handles auto-indent only."""
1587
1628
1588 #debugx('self.indent_current_nsp','pre_readline:')
1629 #debugx('self.indent_current_nsp','pre_readline:')
1589
1630
1590 if self.rl_do_indent:
1631 if self.rl_do_indent:
1591 self.readline.insert_text(self.indent_current_str())
1632 self.readline.insert_text(self.indent_current_str())
1592 if self.rl_next_input is not None:
1633 if self.rl_next_input is not None:
1593 self.readline.insert_text(self.rl_next_input)
1634 self.readline.insert_text(self.rl_next_input)
1594 self.rl_next_input = None
1635 self.rl_next_input = None
1595
1636
1596 def ask_yes_no(self,prompt,default=True):
1637 def ask_yes_no(self,prompt,default=True):
1597 if self.quiet:
1638 if self.quiet:
1598 return True
1639 return True
1599 return ask_yes_no(prompt,default)
1640 return ask_yes_no(prompt,default)
1600
1641
1601 def new_main_mod(self,ns=None):
1642 def new_main_mod(self,ns=None):
1602 """Return a new 'main' module object for user code execution.
1643 """Return a new 'main' module object for user code execution.
1603 """
1644 """
1604 main_mod = self._user_main_module
1645 main_mod = self._user_main_module
1605 init_fakemod_dict(main_mod,ns)
1646 init_fakemod_dict(main_mod,ns)
1606 return main_mod
1647 return main_mod
1607
1648
1608 def cache_main_mod(self,ns,fname):
1649 def cache_main_mod(self,ns,fname):
1609 """Cache a main module's namespace.
1650 """Cache a main module's namespace.
1610
1651
1611 When scripts are executed via %run, we must keep a reference to the
1652 When scripts are executed via %run, we must keep a reference to the
1612 namespace of their __main__ module (a FakeModule instance) around so
1653 namespace of their __main__ module (a FakeModule instance) around so
1613 that Python doesn't clear it, rendering objects defined therein
1654 that Python doesn't clear it, rendering objects defined therein
1614 useless.
1655 useless.
1615
1656
1616 This method keeps said reference in a private dict, keyed by the
1657 This method keeps said reference in a private dict, keyed by the
1617 absolute path of the module object (which corresponds to the script
1658 absolute path of the module object (which corresponds to the script
1618 path). This way, for multiple executions of the same script we only
1659 path). This way, for multiple executions of the same script we only
1619 keep one copy of the namespace (the last one), thus preventing memory
1660 keep one copy of the namespace (the last one), thus preventing memory
1620 leaks from old references while allowing the objects from the last
1661 leaks from old references while allowing the objects from the last
1621 execution to be accessible.
1662 execution to be accessible.
1622
1663
1623 Note: we can not allow the actual FakeModule instances to be deleted,
1664 Note: we can not allow the actual FakeModule instances to be deleted,
1624 because of how Python tears down modules (it hard-sets all their
1665 because of how Python tears down modules (it hard-sets all their
1625 references to None without regard for reference counts). This method
1666 references to None without regard for reference counts). This method
1626 must therefore make a *copy* of the given namespace, to allow the
1667 must therefore make a *copy* of the given namespace, to allow the
1627 original module's __dict__ to be cleared and reused.
1668 original module's __dict__ to be cleared and reused.
1628
1669
1629
1670
1630 Parameters
1671 Parameters
1631 ----------
1672 ----------
1632 ns : a namespace (a dict, typically)
1673 ns : a namespace (a dict, typically)
1633
1674
1634 fname : str
1675 fname : str
1635 Filename associated with the namespace.
1676 Filename associated with the namespace.
1636
1677
1637 Examples
1678 Examples
1638 --------
1679 --------
1639
1680
1640 In [10]: import IPython
1681 In [10]: import IPython
1641
1682
1642 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1683 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1643
1684
1644 In [12]: IPython.__file__ in _ip._main_ns_cache
1685 In [12]: IPython.__file__ in _ip._main_ns_cache
1645 Out[12]: True
1686 Out[12]: True
1646 """
1687 """
1647 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1688 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1648
1689
1649 def clear_main_mod_cache(self):
1690 def clear_main_mod_cache(self):
1650 """Clear the cache of main modules.
1691 """Clear the cache of main modules.
1651
1692
1652 Mainly for use by utilities like %reset.
1693 Mainly for use by utilities like %reset.
1653
1694
1654 Examples
1695 Examples
1655 --------
1696 --------
1656
1697
1657 In [15]: import IPython
1698 In [15]: import IPython
1658
1699
1659 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1700 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1660
1701
1661 In [17]: len(_ip._main_ns_cache) > 0
1702 In [17]: len(_ip._main_ns_cache) > 0
1662 Out[17]: True
1703 Out[17]: True
1663
1704
1664 In [18]: _ip.clear_main_mod_cache()
1705 In [18]: _ip.clear_main_mod_cache()
1665
1706
1666 In [19]: len(_ip._main_ns_cache) == 0
1707 In [19]: len(_ip._main_ns_cache) == 0
1667 Out[19]: True
1708 Out[19]: True
1668 """
1709 """
1669 self._main_ns_cache.clear()
1710 self._main_ns_cache.clear()
1670
1711
1671 def _should_recompile(self,e):
1712 def _should_recompile(self,e):
1672 """Utility routine for edit_syntax_error"""
1713 """Utility routine for edit_syntax_error"""
1673
1714
1674 if e.filename in ('<ipython console>','<input>','<string>',
1715 if e.filename in ('<ipython console>','<input>','<string>',
1675 '<console>','<BackgroundJob compilation>',
1716 '<console>','<BackgroundJob compilation>',
1676 None):
1717 None):
1677
1718
1678 return False
1719 return False
1679 try:
1720 try:
1680 if (self.autoedit_syntax and
1721 if (self.autoedit_syntax and
1681 not self.ask_yes_no('Return to editor to correct syntax error? '
1722 not self.ask_yes_no('Return to editor to correct syntax error? '
1682 '[Y/n] ','y')):
1723 '[Y/n] ','y')):
1683 return False
1724 return False
1684 except EOFError:
1725 except EOFError:
1685 return False
1726 return False
1686
1727
1687 def int0(x):
1728 def int0(x):
1688 try:
1729 try:
1689 return int(x)
1730 return int(x)
1690 except TypeError:
1731 except TypeError:
1691 return 0
1732 return 0
1692 # always pass integer line and offset values to editor hook
1733 # always pass integer line and offset values to editor hook
1693 try:
1734 try:
1694 self.hooks.fix_error_editor(e.filename,
1735 self.hooks.fix_error_editor(e.filename,
1695 int0(e.lineno),int0(e.offset),e.msg)
1736 int0(e.lineno),int0(e.offset),e.msg)
1696 except TryNext:
1737 except TryNext:
1697 warn('Could not open editor')
1738 warn('Could not open editor')
1698 return False
1739 return False
1699 return True
1740 return True
1700
1741
1701 def edit_syntax_error(self):
1742 def edit_syntax_error(self):
1702 """The bottom half of the syntax error handler called in the main loop.
1743 """The bottom half of the syntax error handler called in the main loop.
1703
1744
1704 Loop until syntax error is fixed or user cancels.
1745 Loop until syntax error is fixed or user cancels.
1705 """
1746 """
1706
1747
1707 while self.SyntaxTB.last_syntax_error:
1748 while self.SyntaxTB.last_syntax_error:
1708 # copy and clear last_syntax_error
1749 # copy and clear last_syntax_error
1709 err = self.SyntaxTB.clear_err_state()
1750 err = self.SyntaxTB.clear_err_state()
1710 if not self._should_recompile(err):
1751 if not self._should_recompile(err):
1711 return
1752 return
1712 try:
1753 try:
1713 # may set last_syntax_error again if a SyntaxError is raised
1754 # may set last_syntax_error again if a SyntaxError is raised
1714 self.safe_execfile(err.filename,self.user_ns)
1755 self.safe_execfile(err.filename,self.user_ns)
1715 except:
1756 except:
1716 self.showtraceback()
1757 self.showtraceback()
1717 else:
1758 else:
1718 try:
1759 try:
1719 f = file(err.filename)
1760 f = file(err.filename)
1720 try:
1761 try:
1721 sys.displayhook(f.read())
1762 sys.displayhook(f.read())
1722 finally:
1763 finally:
1723 f.close()
1764 f.close()
1724 except:
1765 except:
1725 self.showtraceback()
1766 self.showtraceback()
1726
1767
1727 def showsyntaxerror(self, filename=None):
1768 def showsyntaxerror(self, filename=None):
1728 """Display the syntax error that just occurred.
1769 """Display the syntax error that just occurred.
1729
1770
1730 This doesn't display a stack trace because there isn't one.
1771 This doesn't display a stack trace because there isn't one.
1731
1772
1732 If a filename is given, it is stuffed in the exception instead
1773 If a filename is given, it is stuffed in the exception instead
1733 of what was there before (because Python's parser always uses
1774 of what was there before (because Python's parser always uses
1734 "<string>" when reading from a string).
1775 "<string>" when reading from a string).
1735 """
1776 """
1736 etype, value, last_traceback = sys.exc_info()
1777 etype, value, last_traceback = sys.exc_info()
1737
1778
1738 # See note about these variables in showtraceback() below
1779 # See note about these variables in showtraceback() below
1739 sys.last_type = etype
1780 sys.last_type = etype
1740 sys.last_value = value
1781 sys.last_value = value
1741 sys.last_traceback = last_traceback
1782 sys.last_traceback = last_traceback
1742
1783
1743 if filename and etype is SyntaxError:
1784 if filename and etype is SyntaxError:
1744 # Work hard to stuff the correct filename in the exception
1785 # Work hard to stuff the correct filename in the exception
1745 try:
1786 try:
1746 msg, (dummy_filename, lineno, offset, line) = value
1787 msg, (dummy_filename, lineno, offset, line) = value
1747 except:
1788 except:
1748 # Not the format we expect; leave it alone
1789 # Not the format we expect; leave it alone
1749 pass
1790 pass
1750 else:
1791 else:
1751 # Stuff in the right filename
1792 # Stuff in the right filename
1752 try:
1793 try:
1753 # Assume SyntaxError is a class exception
1794 # Assume SyntaxError is a class exception
1754 value = SyntaxError(msg, (filename, lineno, offset, line))
1795 value = SyntaxError(msg, (filename, lineno, offset, line))
1755 except:
1796 except:
1756 # If that failed, assume SyntaxError is a string
1797 # If that failed, assume SyntaxError is a string
1757 value = msg, (filename, lineno, offset, line)
1798 value = msg, (filename, lineno, offset, line)
1758 self.SyntaxTB(etype,value,[])
1799 self.SyntaxTB(etype,value,[])
1759
1800
1760 def debugger(self,force=False):
1801 def debugger(self,force=False):
1761 """Call the pydb/pdb debugger.
1802 """Call the pydb/pdb debugger.
1762
1803
1763 Keywords:
1804 Keywords:
1764
1805
1765 - force(False): by default, this routine checks the instance call_pdb
1806 - force(False): by default, this routine checks the instance call_pdb
1766 flag and does not actually invoke the debugger if the flag is false.
1807 flag and does not actually invoke the debugger if the flag is false.
1767 The 'force' option forces the debugger to activate even if the flag
1808 The 'force' option forces the debugger to activate even if the flag
1768 is false.
1809 is false.
1769 """
1810 """
1770
1811
1771 if not (force or self.call_pdb):
1812 if not (force or self.call_pdb):
1772 return
1813 return
1773
1814
1774 if not hasattr(sys,'last_traceback'):
1815 if not hasattr(sys,'last_traceback'):
1775 error('No traceback has been produced, nothing to debug.')
1816 error('No traceback has been produced, nothing to debug.')
1776 return
1817 return
1777
1818
1778 # use pydb if available
1819 # use pydb if available
1779 if debugger.has_pydb:
1820 if debugger.has_pydb:
1780 from pydb import pm
1821 from pydb import pm
1781 else:
1822 else:
1782 # fallback to our internal debugger
1823 # fallback to our internal debugger
1783 pm = lambda : self.InteractiveTB.debugger(force=True)
1824 pm = lambda : self.InteractiveTB.debugger(force=True)
1784 self.history_saving_wrapper(pm)()
1825 self.history_saving_wrapper(pm)()
1785
1826
1786 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1827 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1787 """Display the exception that just occurred.
1828 """Display the exception that just occurred.
1788
1829
1789 If nothing is known about the exception, this is the method which
1830 If nothing is known about the exception, this is the method which
1790 should be used throughout the code for presenting user tracebacks,
1831 should be used throughout the code for presenting user tracebacks,
1791 rather than directly invoking the InteractiveTB object.
1832 rather than directly invoking the InteractiveTB object.
1792
1833
1793 A specific showsyntaxerror() also exists, but this method can take
1834 A specific showsyntaxerror() also exists, but this method can take
1794 care of calling it if needed, so unless you are explicitly catching a
1835 care of calling it if needed, so unless you are explicitly catching a
1795 SyntaxError exception, don't try to analyze the stack manually and
1836 SyntaxError exception, don't try to analyze the stack manually and
1796 simply call this method."""
1837 simply call this method."""
1797
1838
1798
1839
1799 # Though this won't be called by syntax errors in the input line,
1840 # Though this won't be called by syntax errors in the input line,
1800 # there may be SyntaxError cases whith imported code.
1841 # there may be SyntaxError cases whith imported code.
1801
1842
1802 try:
1843 try:
1803 if exc_tuple is None:
1844 if exc_tuple is None:
1804 etype, value, tb = sys.exc_info()
1845 etype, value, tb = sys.exc_info()
1805 else:
1846 else:
1806 etype, value, tb = exc_tuple
1847 etype, value, tb = exc_tuple
1807
1848
1808 if etype is SyntaxError:
1849 if etype is SyntaxError:
1809 self.showsyntaxerror(filename)
1850 self.showsyntaxerror(filename)
1810 elif etype is UsageError:
1851 elif etype is UsageError:
1811 print "UsageError:", value
1852 print "UsageError:", value
1812 else:
1853 else:
1813 # WARNING: these variables are somewhat deprecated and not
1854 # WARNING: these variables are somewhat deprecated and not
1814 # necessarily safe to use in a threaded environment, but tools
1855 # necessarily safe to use in a threaded environment, but tools
1815 # like pdb depend on their existence, so let's set them. If we
1856 # like pdb depend on their existence, so let's set them. If we
1816 # find problems in the field, we'll need to revisit their use.
1857 # find problems in the field, we'll need to revisit their use.
1817 sys.last_type = etype
1858 sys.last_type = etype
1818 sys.last_value = value
1859 sys.last_value = value
1819 sys.last_traceback = tb
1860 sys.last_traceback = tb
1820
1861
1821 if etype in self.custom_exceptions:
1862 if etype in self.custom_exceptions:
1822 self.CustomTB(etype,value,tb)
1863 self.CustomTB(etype,value,tb)
1823 else:
1864 else:
1824 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1865 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1825 if self.InteractiveTB.call_pdb and self.has_readline:
1866 if self.InteractiveTB.call_pdb and self.has_readline:
1826 # pdb mucks up readline, fix it back
1867 # pdb mucks up readline, fix it back
1827 self.set_completer()
1868 self.set_completer()
1828 except KeyboardInterrupt:
1869 except KeyboardInterrupt:
1829 self.write("\nKeyboardInterrupt\n")
1870 self.write("\nKeyboardInterrupt\n")
1830
1871
1831 def mainloop(self, banner=None):
1872 def mainloop(self, banner=None):
1832 """Start the mainloop.
1873 """Start the mainloop.
1833
1874
1834 If an optional banner argument is given, it will override the
1875 If an optional banner argument is given, it will override the
1835 internally created default banner.
1876 internally created default banner.
1836 """
1877 """
1837 if self.c: # Emulate Python's -c option
1878 if self.c: # Emulate Python's -c option
1838 self.exec_init_cmd()
1879 self.exec_init_cmd()
1839
1880
1840 if self.display_banner:
1881 if self.display_banner:
1841 if banner is None:
1882 if banner is None:
1842 banner = self.banner
1883 banner = self.banner
1843
1884
1844 # if you run stuff with -c <cmd>, raw hist is not updated
1885 # if you run stuff with -c <cmd>, raw hist is not updated
1845 # ensure that it's in sync
1886 # ensure that it's in sync
1846 if len(self.input_hist) != len (self.input_hist_raw):
1887 if len(self.input_hist) != len (self.input_hist_raw):
1847 self.input_hist_raw = InputList(self.input_hist)
1888 self.input_hist_raw = InputList(self.input_hist)
1848
1889
1849 while 1:
1890 while 1:
1850 try:
1891 try:
1851 self.interact()
1892 self.interact()
1852 #self.interact_with_readline()
1893 #self.interact_with_readline()
1853 # XXX for testing of a readline-decoupled repl loop, call
1894 # XXX for testing of a readline-decoupled repl loop, call
1854 # interact_with_readline above
1895 # interact_with_readline above
1855 break
1896 break
1856 except KeyboardInterrupt:
1897 except KeyboardInterrupt:
1857 # this should not be necessary, but KeyboardInterrupt
1898 # this should not be necessary, but KeyboardInterrupt
1858 # handling seems rather unpredictable...
1899 # handling seems rather unpredictable...
1859 self.write("\nKeyboardInterrupt in interact()\n")
1900 self.write("\nKeyboardInterrupt in interact()\n")
1860
1901
1861 def exec_init_cmd(self):
1902 def exec_init_cmd(self):
1862 """Execute a command given at the command line.
1903 """Execute a command given at the command line.
1863
1904
1864 This emulates Python's -c option."""
1905 This emulates Python's -c option."""
1865
1906
1866 #sys.argv = ['-c']
1907 #sys.argv = ['-c']
1867 self.push_line(self.prefilter(self.c, False))
1908 self.push_line(self.prefilter(self.c, False))
1868 if not self.interactive:
1909 if not self.interactive:
1869 self.ask_exit()
1910 self.ask_exit()
1870
1911
1871 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1912 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1872 """Embeds IPython into a running python program.
1913 """Embeds IPython into a running python program.
1873
1914
1874 Input:
1915 Input:
1875
1916
1876 - header: An optional header message can be specified.
1917 - header: An optional header message can be specified.
1877
1918
1878 - local_ns, global_ns: working namespaces. If given as None, the
1919 - local_ns, global_ns: working namespaces. If given as None, the
1879 IPython-initialized one is updated with __main__.__dict__, so that
1920 IPython-initialized one is updated with __main__.__dict__, so that
1880 program variables become visible but user-specific configuration
1921 program variables become visible but user-specific configuration
1881 remains possible.
1922 remains possible.
1882
1923
1883 - stack_depth: specifies how many levels in the stack to go to
1924 - stack_depth: specifies how many levels in the stack to go to
1884 looking for namespaces (when local_ns and global_ns are None). This
1925 looking for namespaces (when local_ns and global_ns are None). This
1885 allows an intermediate caller to make sure that this function gets
1926 allows an intermediate caller to make sure that this function gets
1886 the namespace from the intended level in the stack. By default (0)
1927 the namespace from the intended level in the stack. By default (0)
1887 it will get its locals and globals from the immediate caller.
1928 it will get its locals and globals from the immediate caller.
1888
1929
1889 Warning: it's possible to use this in a program which is being run by
1930 Warning: it's possible to use this in a program which is being run by
1890 IPython itself (via %run), but some funny things will happen (a few
1931 IPython itself (via %run), but some funny things will happen (a few
1891 globals get overwritten). In the future this will be cleaned up, as
1932 globals get overwritten). In the future this will be cleaned up, as
1892 there is no fundamental reason why it can't work perfectly."""
1933 there is no fundamental reason why it can't work perfectly."""
1893
1934
1894 # Get locals and globals from caller
1935 # Get locals and globals from caller
1895 if local_ns is None or global_ns is None:
1936 if local_ns is None or global_ns is None:
1896 call_frame = sys._getframe(stack_depth).f_back
1937 call_frame = sys._getframe(stack_depth).f_back
1897
1938
1898 if local_ns is None:
1939 if local_ns is None:
1899 local_ns = call_frame.f_locals
1940 local_ns = call_frame.f_locals
1900 if global_ns is None:
1941 if global_ns is None:
1901 global_ns = call_frame.f_globals
1942 global_ns = call_frame.f_globals
1902
1943
1903 # Update namespaces and fire up interpreter
1944 # Update namespaces and fire up interpreter
1904
1945
1905 # The global one is easy, we can just throw it in
1946 # The global one is easy, we can just throw it in
1906 self.user_global_ns = global_ns
1947 self.user_global_ns = global_ns
1907
1948
1908 # but the user/local one is tricky: ipython needs it to store internal
1949 # but the user/local one is tricky: ipython needs it to store internal
1909 # data, but we also need the locals. We'll copy locals in the user
1950 # data, but we also need the locals. We'll copy locals in the user
1910 # one, but will track what got copied so we can delete them at exit.
1951 # one, but will track what got copied so we can delete them at exit.
1911 # This is so that a later embedded call doesn't see locals from a
1952 # This is so that a later embedded call doesn't see locals from a
1912 # previous call (which most likely existed in a separate scope).
1953 # previous call (which most likely existed in a separate scope).
1913 local_varnames = local_ns.keys()
1954 local_varnames = local_ns.keys()
1914 self.user_ns.update(local_ns)
1955 self.user_ns.update(local_ns)
1915 #self.user_ns['local_ns'] = local_ns # dbg
1956 #self.user_ns['local_ns'] = local_ns # dbg
1916
1957
1917 # Patch for global embedding to make sure that things don't overwrite
1958 # Patch for global embedding to make sure that things don't overwrite
1918 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1959 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1919 # FIXME. Test this a bit more carefully (the if.. is new)
1960 # FIXME. Test this a bit more carefully (the if.. is new)
1920 if local_ns is None and global_ns is None:
1961 if local_ns is None and global_ns is None:
1921 self.user_global_ns.update(__main__.__dict__)
1962 self.user_global_ns.update(__main__.__dict__)
1922
1963
1923 # make sure the tab-completer has the correct frame information, so it
1964 # make sure the tab-completer has the correct frame information, so it
1924 # actually completes using the frame's locals/globals
1965 # actually completes using the frame's locals/globals
1925 self.set_completer_frame()
1966 self.set_completer_frame()
1926
1967
1927 # before activating the interactive mode, we need to make sure that
1968 # before activating the interactive mode, we need to make sure that
1928 # all names in the builtin namespace needed by ipython point to
1969 # all names in the builtin namespace needed by ipython point to
1929 # ourselves, and not to other instances.
1970 # ourselves, and not to other instances.
1930 self.add_builtins()
1971 self.add_builtins()
1931
1972
1932 self.interact(header)
1973 self.interact(header)
1933
1974
1934 # now, purge out the user namespace from anything we might have added
1975 # now, purge out the user namespace from anything we might have added
1935 # from the caller's local namespace
1976 # from the caller's local namespace
1936 delvar = self.user_ns.pop
1977 delvar = self.user_ns.pop
1937 for var in local_varnames:
1978 for var in local_varnames:
1938 delvar(var,None)
1979 delvar(var,None)
1939 # and clean builtins we may have overridden
1980 # and clean builtins we may have overridden
1940 self.clean_builtins()
1981 self.remove_builtins()
1941
1982
1942 def interact_prompt(self):
1983 def interact_prompt(self):
1943 """ Print the prompt (in read-eval-print loop)
1984 """ Print the prompt (in read-eval-print loop)
1944
1985
1945 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1986 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1946 used in standard IPython flow.
1987 used in standard IPython flow.
1947 """
1988 """
1948 if self.more:
1989 if self.more:
1949 try:
1990 try:
1950 prompt = self.hooks.generate_prompt(True)
1991 prompt = self.hooks.generate_prompt(True)
1951 except:
1992 except:
1952 self.showtraceback()
1993 self.showtraceback()
1953 if self.autoindent:
1994 if self.autoindent:
1954 self.rl_do_indent = True
1995 self.rl_do_indent = True
1955
1996
1956 else:
1997 else:
1957 try:
1998 try:
1958 prompt = self.hooks.generate_prompt(False)
1999 prompt = self.hooks.generate_prompt(False)
1959 except:
2000 except:
1960 self.showtraceback()
2001 self.showtraceback()
1961 self.write(prompt)
2002 self.write(prompt)
1962
2003
1963 def interact_handle_input(self,line):
2004 def interact_handle_input(self,line):
1964 """ Handle the input line (in read-eval-print loop)
2005 """ Handle the input line (in read-eval-print loop)
1965
2006
1966 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
2007 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1967 used in standard IPython flow.
2008 used in standard IPython flow.
1968 """
2009 """
1969 if line.lstrip() == line:
2010 if line.lstrip() == line:
1970 self.shadowhist.add(line.strip())
2011 self.shadowhist.add(line.strip())
1971 lineout = self.prefilter(line,self.more)
2012 lineout = self.prefilter(line,self.more)
1972
2013
1973 if line.strip():
2014 if line.strip():
1974 if self.more:
2015 if self.more:
1975 self.input_hist_raw[-1] += '%s\n' % line
2016 self.input_hist_raw[-1] += '%s\n' % line
1976 else:
2017 else:
1977 self.input_hist_raw.append('%s\n' % line)
2018 self.input_hist_raw.append('%s\n' % line)
1978
2019
1979
2020
1980 self.more = self.push_line(lineout)
2021 self.more = self.push_line(lineout)
1981 if (self.SyntaxTB.last_syntax_error and
2022 if (self.SyntaxTB.last_syntax_error and
1982 self.autoedit_syntax):
2023 self.autoedit_syntax):
1983 self.edit_syntax_error()
2024 self.edit_syntax_error()
1984
2025
1985 def interact_with_readline(self):
2026 def interact_with_readline(self):
1986 """ Demo of using interact_handle_input, interact_prompt
2027 """ Demo of using interact_handle_input, interact_prompt
1987
2028
1988 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
2029 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1989 it should work like this.
2030 it should work like this.
1990 """
2031 """
1991 self.readline_startup_hook(self.pre_readline)
2032 self.readline_startup_hook(self.pre_readline)
1992 while not self.exit_now:
2033 while not self.exit_now:
1993 self.interact_prompt()
2034 self.interact_prompt()
1994 if self.more:
2035 if self.more:
1995 self.rl_do_indent = True
2036 self.rl_do_indent = True
1996 else:
2037 else:
1997 self.rl_do_indent = False
2038 self.rl_do_indent = False
1998 line = raw_input_original().decode(self.stdin_encoding)
2039 line = raw_input_original().decode(self.stdin_encoding)
1999 self.interact_handle_input(line)
2040 self.interact_handle_input(line)
2000
2041
2001 def interact(self, banner=None):
2042 def interact(self, banner=None):
2002 """Closely emulate the interactive Python console."""
2043 """Closely emulate the interactive Python console."""
2003
2044
2004 # batch run -> do not interact
2045 # batch run -> do not interact
2005 if self.exit_now:
2046 if self.exit_now:
2006 return
2047 return
2007
2048
2008 if self.display_banner:
2049 if self.display_banner:
2009 if banner is None:
2050 if banner is None:
2010 banner = self.banner
2051 banner = self.banner
2011 self.write(banner)
2052 self.write(banner)
2012
2053
2013 more = 0
2054 more = 0
2014
2055
2015 # Mark activity in the builtins
2056 # Mark activity in the builtins
2016 __builtin__.__dict__['__IPYTHON__active'] += 1
2057 __builtin__.__dict__['__IPYTHON__active'] += 1
2017
2058
2018 if self.has_readline:
2059 if self.has_readline:
2019 self.readline_startup_hook(self.pre_readline)
2060 self.readline_startup_hook(self.pre_readline)
2020 # exit_now is set by a call to %Exit or %Quit, through the
2061 # exit_now is set by a call to %Exit or %Quit, through the
2021 # ask_exit callback.
2062 # ask_exit callback.
2022
2063
2023 while not self.exit_now:
2064 while not self.exit_now:
2024 self.hooks.pre_prompt_hook()
2065 self.hooks.pre_prompt_hook()
2025 if more:
2066 if more:
2026 try:
2067 try:
2027 prompt = self.hooks.generate_prompt(True)
2068 prompt = self.hooks.generate_prompt(True)
2028 except:
2069 except:
2029 self.showtraceback()
2070 self.showtraceback()
2030 if self.autoindent:
2071 if self.autoindent:
2031 self.rl_do_indent = True
2072 self.rl_do_indent = True
2032
2073
2033 else:
2074 else:
2034 try:
2075 try:
2035 prompt = self.hooks.generate_prompt(False)
2076 prompt = self.hooks.generate_prompt(False)
2036 except:
2077 except:
2037 self.showtraceback()
2078 self.showtraceback()
2038 try:
2079 try:
2039 line = self.raw_input(prompt, more)
2080 line = self.raw_input(prompt, more)
2040 if self.exit_now:
2081 if self.exit_now:
2041 # quick exit on sys.std[in|out] close
2082 # quick exit on sys.std[in|out] close
2042 break
2083 break
2043 if self.autoindent:
2084 if self.autoindent:
2044 self.rl_do_indent = False
2085 self.rl_do_indent = False
2045
2086
2046 except KeyboardInterrupt:
2087 except KeyboardInterrupt:
2047 #double-guard against keyboardinterrupts during kbdint handling
2088 #double-guard against keyboardinterrupts during kbdint handling
2048 try:
2089 try:
2049 self.write('\nKeyboardInterrupt\n')
2090 self.write('\nKeyboardInterrupt\n')
2050 self.resetbuffer()
2091 self.resetbuffer()
2051 # keep cache in sync with the prompt counter:
2092 # keep cache in sync with the prompt counter:
2052 self.outputcache.prompt_count -= 1
2093 self.outputcache.prompt_count -= 1
2053
2094
2054 if self.autoindent:
2095 if self.autoindent:
2055 self.indent_current_nsp = 0
2096 self.indent_current_nsp = 0
2056 more = 0
2097 more = 0
2057 except KeyboardInterrupt:
2098 except KeyboardInterrupt:
2058 pass
2099 pass
2059 except EOFError:
2100 except EOFError:
2060 if self.autoindent:
2101 if self.autoindent:
2061 self.rl_do_indent = False
2102 self.rl_do_indent = False
2062 self.readline_startup_hook(None)
2103 self.readline_startup_hook(None)
2063 self.write('\n')
2104 self.write('\n')
2064 self.exit()
2105 self.exit()
2065 except bdb.BdbQuit:
2106 except bdb.BdbQuit:
2066 warn('The Python debugger has exited with a BdbQuit exception.\n'
2107 warn('The Python debugger has exited with a BdbQuit exception.\n'
2067 'Because of how pdb handles the stack, it is impossible\n'
2108 'Because of how pdb handles the stack, it is impossible\n'
2068 'for IPython to properly format this particular exception.\n'
2109 'for IPython to properly format this particular exception.\n'
2069 'IPython will resume normal operation.')
2110 'IPython will resume normal operation.')
2070 except:
2111 except:
2071 # exceptions here are VERY RARE, but they can be triggered
2112 # exceptions here are VERY RARE, but they can be triggered
2072 # asynchronously by signal handlers, for example.
2113 # asynchronously by signal handlers, for example.
2073 self.showtraceback()
2114 self.showtraceback()
2074 else:
2115 else:
2075 more = self.push_line(line)
2116 more = self.push_line(line)
2076 if (self.SyntaxTB.last_syntax_error and
2117 if (self.SyntaxTB.last_syntax_error and
2077 self.autoedit_syntax):
2118 self.autoedit_syntax):
2078 self.edit_syntax_error()
2119 self.edit_syntax_error()
2079
2120
2080 # We are off again...
2121 # We are off again...
2081 __builtin__.__dict__['__IPYTHON__active'] -= 1
2122 __builtin__.__dict__['__IPYTHON__active'] -= 1
2082
2123
2083 def excepthook(self, etype, value, tb):
2124 def excepthook(self, etype, value, tb):
2084 """One more defense for GUI apps that call sys.excepthook.
2125 """One more defense for GUI apps that call sys.excepthook.
2085
2126
2086 GUI frameworks like wxPython trap exceptions and call
2127 GUI frameworks like wxPython trap exceptions and call
2087 sys.excepthook themselves. I guess this is a feature that
2128 sys.excepthook themselves. I guess this is a feature that
2088 enables them to keep running after exceptions that would
2129 enables them to keep running after exceptions that would
2089 otherwise kill their mainloop. This is a bother for IPython
2130 otherwise kill their mainloop. This is a bother for IPython
2090 which excepts to catch all of the program exceptions with a try:
2131 which excepts to catch all of the program exceptions with a try:
2091 except: statement.
2132 except: statement.
2092
2133
2093 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2134 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2094 any app directly invokes sys.excepthook, it will look to the user like
2135 any app directly invokes sys.excepthook, it will look to the user like
2095 IPython crashed. In order to work around this, we can disable the
2136 IPython crashed. In order to work around this, we can disable the
2096 CrashHandler and replace it with this excepthook instead, which prints a
2137 CrashHandler and replace it with this excepthook instead, which prints a
2097 regular traceback using our InteractiveTB. In this fashion, apps which
2138 regular traceback using our InteractiveTB. In this fashion, apps which
2098 call sys.excepthook will generate a regular-looking exception from
2139 call sys.excepthook will generate a regular-looking exception from
2099 IPython, and the CrashHandler will only be triggered by real IPython
2140 IPython, and the CrashHandler will only be triggered by real IPython
2100 crashes.
2141 crashes.
2101
2142
2102 This hook should be used sparingly, only in places which are not likely
2143 This hook should be used sparingly, only in places which are not likely
2103 to be true IPython errors.
2144 to be true IPython errors.
2104 """
2145 """
2105 self.showtraceback((etype,value,tb),tb_offset=0)
2146 self.showtraceback((etype,value,tb),tb_offset=0)
2106
2147
2107 def expand_alias(self, line):
2148 def expand_alias(self, line):
2108 """ Expand an alias in the command line
2149 """ Expand an alias in the command line
2109
2150
2110 Returns the provided command line, possibly with the first word
2151 Returns the provided command line, possibly with the first word
2111 (command) translated according to alias expansion rules.
2152 (command) translated according to alias expansion rules.
2112
2153
2113 [ipython]|16> _ip.expand_aliases("np myfile.txt")
2154 [ipython]|16> _ip.expand_aliases("np myfile.txt")
2114 <16> 'q:/opt/np/notepad++.exe myfile.txt'
2155 <16> 'q:/opt/np/notepad++.exe myfile.txt'
2115 """
2156 """
2116
2157
2117 pre,fn,rest = self.split_user_input(line)
2158 pre,fn,rest = self.split_user_input(line)
2118 res = pre + self.expand_aliases(fn, rest)
2159 res = pre + self.expand_aliases(fn, rest)
2119 return res
2160 return res
2120
2161
2121 def expand_aliases(self, fn, rest):
2162 def expand_aliases(self, fn, rest):
2122 """Expand multiple levels of aliases:
2163 """Expand multiple levels of aliases:
2123
2164
2124 if:
2165 if:
2125
2166
2126 alias foo bar /tmp
2167 alias foo bar /tmp
2127 alias baz foo
2168 alias baz foo
2128
2169
2129 then:
2170 then:
2130
2171
2131 baz huhhahhei -> bar /tmp huhhahhei
2172 baz huhhahhei -> bar /tmp huhhahhei
2132
2173
2133 """
2174 """
2134 line = fn + " " + rest
2175 line = fn + " " + rest
2135
2176
2136 done = set()
2177 done = set()
2137 while 1:
2178 while 1:
2138 pre,fn,rest = prefilter.splitUserInput(line,
2179 pre,fn,rest = prefilter.splitUserInput(line,
2139 prefilter.shell_line_split)
2180 prefilter.shell_line_split)
2140 if fn in self.alias_table:
2181 if fn in self.alias_table:
2141 if fn in done:
2182 if fn in done:
2142 warn("Cyclic alias definition, repeated '%s'" % fn)
2183 warn("Cyclic alias definition, repeated '%s'" % fn)
2143 return ""
2184 return ""
2144 done.add(fn)
2185 done.add(fn)
2145
2186
2146 l2 = self.transform_alias(fn,rest)
2187 l2 = self.transform_alias(fn,rest)
2147 # dir -> dir
2188 # dir -> dir
2148 # print "alias",line, "->",l2 #dbg
2189 # print "alias",line, "->",l2 #dbg
2149 if l2 == line:
2190 if l2 == line:
2150 break
2191 break
2151 # ls -> ls -F should not recurse forever
2192 # ls -> ls -F should not recurse forever
2152 if l2.split(None,1)[0] == line.split(None,1)[0]:
2193 if l2.split(None,1)[0] == line.split(None,1)[0]:
2153 line = l2
2194 line = l2
2154 break
2195 break
2155
2196
2156 line=l2
2197 line=l2
2157
2198
2158
2199
2159 # print "al expand to",line #dbg
2200 # print "al expand to",line #dbg
2160 else:
2201 else:
2161 break
2202 break
2162
2203
2163 return line
2204 return line
2164
2205
2165 def transform_alias(self, alias,rest=''):
2206 def transform_alias(self, alias,rest=''):
2166 """ Transform alias to system command string.
2207 """ Transform alias to system command string.
2167 """
2208 """
2168 trg = self.alias_table[alias]
2209 trg = self.alias_table[alias]
2169
2210
2170 nargs,cmd = trg
2211 nargs,cmd = trg
2171 # print trg #dbg
2212 # print trg #dbg
2172 if ' ' in cmd and os.path.isfile(cmd):
2213 if ' ' in cmd and os.path.isfile(cmd):
2173 cmd = '"%s"' % cmd
2214 cmd = '"%s"' % cmd
2174
2215
2175 # Expand the %l special to be the user's input line
2216 # Expand the %l special to be the user's input line
2176 if cmd.find('%l') >= 0:
2217 if cmd.find('%l') >= 0:
2177 cmd = cmd.replace('%l',rest)
2218 cmd = cmd.replace('%l',rest)
2178 rest = ''
2219 rest = ''
2179 if nargs==0:
2220 if nargs==0:
2180 # Simple, argument-less aliases
2221 # Simple, argument-less aliases
2181 cmd = '%s %s' % (cmd,rest)
2222 cmd = '%s %s' % (cmd,rest)
2182 else:
2223 else:
2183 # Handle aliases with positional arguments
2224 # Handle aliases with positional arguments
2184 args = rest.split(None,nargs)
2225 args = rest.split(None,nargs)
2185 if len(args)< nargs:
2226 if len(args)< nargs:
2186 error('Alias <%s> requires %s arguments, %s given.' %
2227 error('Alias <%s> requires %s arguments, %s given.' %
2187 (alias,nargs,len(args)))
2228 (alias,nargs,len(args)))
2188 return None
2229 return None
2189 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2230 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2190 # Now call the macro, evaluating in the user's namespace
2231 # Now call the macro, evaluating in the user's namespace
2191 #print 'new command: <%r>' % cmd # dbg
2232 #print 'new command: <%r>' % cmd # dbg
2192 return cmd
2233 return cmd
2193
2234
2194 def call_alias(self,alias,rest=''):
2235 def call_alias(self,alias,rest=''):
2195 """Call an alias given its name and the rest of the line.
2236 """Call an alias given its name and the rest of the line.
2196
2237
2197 This is only used to provide backwards compatibility for users of
2238 This is only used to provide backwards compatibility for users of
2198 ipalias(), use of which is not recommended for anymore."""
2239 ipalias(), use of which is not recommended for anymore."""
2199
2240
2200 # Now call the macro, evaluating in the user's namespace
2241 # Now call the macro, evaluating in the user's namespace
2201 cmd = self.transform_alias(alias, rest)
2242 cmd = self.transform_alias(alias, rest)
2202 try:
2243 try:
2203 self.system(cmd)
2244 self.system(cmd)
2204 except:
2245 except:
2205 self.showtraceback()
2246 self.showtraceback()
2206
2247
2207 def indent_current_str(self):
2248 def indent_current_str(self):
2208 """return the current level of indentation as a string"""
2249 """return the current level of indentation as a string"""
2209 return self.indent_current_nsp * ' '
2250 return self.indent_current_nsp * ' '
2210
2251
2211 def autoindent_update(self,line):
2252 def autoindent_update(self,line):
2212 """Keep track of the indent level."""
2253 """Keep track of the indent level."""
2213
2254
2214 #debugx('line')
2255 #debugx('line')
2215 #debugx('self.indent_current_nsp')
2256 #debugx('self.indent_current_nsp')
2216 if self.autoindent:
2257 if self.autoindent:
2217 if line:
2258 if line:
2218 inisp = num_ini_spaces(line)
2259 inisp = num_ini_spaces(line)
2219 if inisp < self.indent_current_nsp:
2260 if inisp < self.indent_current_nsp:
2220 self.indent_current_nsp = inisp
2261 self.indent_current_nsp = inisp
2221
2262
2222 if line[-1] == ':':
2263 if line[-1] == ':':
2223 self.indent_current_nsp += 4
2264 self.indent_current_nsp += 4
2224 elif dedent_re.match(line):
2265 elif dedent_re.match(line):
2225 self.indent_current_nsp -= 4
2266 self.indent_current_nsp -= 4
2226 else:
2267 else:
2227 self.indent_current_nsp = 0
2268 self.indent_current_nsp = 0
2228
2269
2229 def push(self, variables, interactive=True):
2270 def push(self, variables, interactive=True):
2230 """Inject a group of variables into the IPython user namespace.
2271 """Inject a group of variables into the IPython user namespace.
2231
2272
2232 Parameters
2273 Parameters
2233 ----------
2274 ----------
2234 variables : dict, str or list/tuple of str
2275 variables : dict, str or list/tuple of str
2235 The variables to inject into the user's namespace. If a dict,
2276 The variables to inject into the user's namespace. If a dict,
2236 a simple update is done. If a str, the string is assumed to
2277 a simple update is done. If a str, the string is assumed to
2237 have variable names separated by spaces. A list/tuple of str
2278 have variable names separated by spaces. A list/tuple of str
2238 can also be used to give the variable names. If just the variable
2279 can also be used to give the variable names. If just the variable
2239 names are give (list/tuple/str) then the variable values looked
2280 names are give (list/tuple/str) then the variable values looked
2240 up in the callers frame.
2281 up in the callers frame.
2241 interactive : bool
2282 interactive : bool
2242 If True (default), the variables will be listed with the ``who``
2283 If True (default), the variables will be listed with the ``who``
2243 magic.
2284 magic.
2244 """
2285 """
2245 vdict = None
2286 vdict = None
2246
2287
2247 # We need a dict of name/value pairs to do namespace updates.
2288 # We need a dict of name/value pairs to do namespace updates.
2248 if isinstance(variables, dict):
2289 if isinstance(variables, dict):
2249 vdict = variables
2290 vdict = variables
2250 elif isinstance(variables, (basestring, list, tuple)):
2291 elif isinstance(variables, (basestring, list, tuple)):
2251 if isinstance(variables, basestring):
2292 if isinstance(variables, basestring):
2252 vlist = variables.split()
2293 vlist = variables.split()
2253 else:
2294 else:
2254 vlist = variables
2295 vlist = variables
2255 vdict = {}
2296 vdict = {}
2256 cf = sys._getframe(1)
2297 cf = sys._getframe(1)
2257 for name in vlist:
2298 for name in vlist:
2258 try:
2299 try:
2259 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
2300 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
2260 except:
2301 except:
2261 print ('Could not get variable %s from %s' %
2302 print ('Could not get variable %s from %s' %
2262 (name,cf.f_code.co_name))
2303 (name,cf.f_code.co_name))
2263 else:
2304 else:
2264 raise ValueError('variables must be a dict/str/list/tuple')
2305 raise ValueError('variables must be a dict/str/list/tuple')
2265
2306
2266 # Propagate variables to user namespace
2307 # Propagate variables to user namespace
2267 self.user_ns.update(vdict)
2308 self.user_ns.update(vdict)
2268
2309
2269 # And configure interactive visibility
2310 # And configure interactive visibility
2270 config_ns = self.user_config_ns
2311 config_ns = self.user_config_ns
2271 if interactive:
2312 if interactive:
2272 for name, val in vdict.iteritems():
2313 for name, val in vdict.iteritems():
2273 config_ns.pop(name, None)
2314 config_ns.pop(name, None)
2274 else:
2315 else:
2275 for name,val in vdict.iteritems():
2316 for name,val in vdict.iteritems():
2276 config_ns[name] = val
2317 config_ns[name] = val
2277
2318
2278 def cleanup_ipy_script(self, script):
2319 def cleanup_ipy_script(self, script):
2279 """Make a script safe for self.runlines()
2320 """Make a script safe for self.runlines()
2280
2321
2281 Notes
2322 Notes
2282 -----
2323 -----
2283 This was copied over from the old ipapi and probably can be done
2324 This was copied over from the old ipapi and probably can be done
2284 away with once we move to block based interpreter.
2325 away with once we move to block based interpreter.
2285
2326
2286 - Removes empty lines Suffixes all indented blocks that end with
2327 - Removes empty lines Suffixes all indented blocks that end with
2287 - unindented lines with empty lines
2328 - unindented lines with empty lines
2288 """
2329 """
2289
2330
2290 res = []
2331 res = []
2291 lines = script.splitlines()
2332 lines = script.splitlines()
2292
2333
2293 level = 0
2334 level = 0
2294 for l in lines:
2335 for l in lines:
2295 lstripped = l.lstrip()
2336 lstripped = l.lstrip()
2296 stripped = l.strip()
2337 stripped = l.strip()
2297 if not stripped:
2338 if not stripped:
2298 continue
2339 continue
2299 newlevel = len(l) - len(lstripped)
2340 newlevel = len(l) - len(lstripped)
2300 def is_secondary_block_start(s):
2341 def is_secondary_block_start(s):
2301 if not s.endswith(':'):
2342 if not s.endswith(':'):
2302 return False
2343 return False
2303 if (s.startswith('elif') or
2344 if (s.startswith('elif') or
2304 s.startswith('else') or
2345 s.startswith('else') or
2305 s.startswith('except') or
2346 s.startswith('except') or
2306 s.startswith('finally')):
2347 s.startswith('finally')):
2307 return True
2348 return True
2308
2349
2309 if level > 0 and newlevel == 0 and \
2350 if level > 0 and newlevel == 0 and \
2310 not is_secondary_block_start(stripped):
2351 not is_secondary_block_start(stripped):
2311 # add empty line
2352 # add empty line
2312 res.append('')
2353 res.append('')
2313
2354
2314 res.append(l)
2355 res.append(l)
2315 level = newlevel
2356 level = newlevel
2316 return '\n'.join(res) + '\n'
2357 return '\n'.join(res) + '\n'
2317
2358
2318 def runlines(self, lines, clean=False):
2359 def runlines(self, lines, clean=False):
2319 """Run a string of one or more lines of source.
2360 """Run a string of one or more lines of source.
2320
2361
2321 This method is capable of running a string containing multiple source
2362 This method is capable of running a string containing multiple source
2322 lines, as if they had been entered at the IPython prompt. Since it
2363 lines, as if they had been entered at the IPython prompt. Since it
2323 exposes IPython's processing machinery, the given strings can contain
2364 exposes IPython's processing machinery, the given strings can contain
2324 magic calls (%magic), special shell access (!cmd), etc.
2365 magic calls (%magic), special shell access (!cmd), etc.
2325 """
2366 """
2326
2367
2327 if isinstance(lines, (list, tuple)):
2368 if isinstance(lines, (list, tuple)):
2328 lines = '\n'.join(lines)
2369 lines = '\n'.join(lines)
2329
2370
2330 if clean:
2371 if clean:
2331 lines = self.cleanup_ipy_script(lines)
2372 lines = self.cleanup_ipy_script(lines)
2332
2373
2333 # We must start with a clean buffer, in case this is run from an
2374 # We must start with a clean buffer, in case this is run from an
2334 # interactive IPython session (via a magic, for example).
2375 # interactive IPython session (via a magic, for example).
2335 self.resetbuffer()
2376 self.resetbuffer()
2336 lines = lines.splitlines()
2377 lines = lines.splitlines()
2337 more = 0
2378 more = 0
2338
2379
2339 for line in lines:
2380 for line in lines:
2340 # skip blank lines so we don't mess up the prompt counter, but do
2381 # skip blank lines so we don't mess up the prompt counter, but do
2341 # NOT skip even a blank line if we are in a code block (more is
2382 # NOT skip even a blank line if we are in a code block (more is
2342 # true)
2383 # true)
2343
2384
2344 if line or more:
2385 if line or more:
2345 # push to raw history, so hist line numbers stay in sync
2386 # push to raw history, so hist line numbers stay in sync
2346 self.input_hist_raw.append("# " + line + "\n")
2387 self.input_hist_raw.append("# " + line + "\n")
2347 more = self.push_line(self.prefilter(line,more))
2388 more = self.push_line(self.prefilter(line,more))
2348 # IPython's runsource returns None if there was an error
2389 # IPython's runsource returns None if there was an error
2349 # compiling the code. This allows us to stop processing right
2390 # compiling the code. This allows us to stop processing right
2350 # away, so the user gets the error message at the right place.
2391 # away, so the user gets the error message at the right place.
2351 if more is None:
2392 if more is None:
2352 break
2393 break
2353 else:
2394 else:
2354 self.input_hist_raw.append("\n")
2395 self.input_hist_raw.append("\n")
2355 # final newline in case the input didn't have it, so that the code
2396 # final newline in case the input didn't have it, so that the code
2356 # actually does get executed
2397 # actually does get executed
2357 if more:
2398 if more:
2358 self.push_line('\n')
2399 self.push_line('\n')
2359
2400
2360 def runsource(self, source, filename='<input>', symbol='single'):
2401 def runsource(self, source, filename='<input>', symbol='single'):
2361 """Compile and run some source in the interpreter.
2402 """Compile and run some source in the interpreter.
2362
2403
2363 Arguments are as for compile_command().
2404 Arguments are as for compile_command().
2364
2405
2365 One several things can happen:
2406 One several things can happen:
2366
2407
2367 1) The input is incorrect; compile_command() raised an
2408 1) The input is incorrect; compile_command() raised an
2368 exception (SyntaxError or OverflowError). A syntax traceback
2409 exception (SyntaxError or OverflowError). A syntax traceback
2369 will be printed by calling the showsyntaxerror() method.
2410 will be printed by calling the showsyntaxerror() method.
2370
2411
2371 2) The input is incomplete, and more input is required;
2412 2) The input is incomplete, and more input is required;
2372 compile_command() returned None. Nothing happens.
2413 compile_command() returned None. Nothing happens.
2373
2414
2374 3) The input is complete; compile_command() returned a code
2415 3) The input is complete; compile_command() returned a code
2375 object. The code is executed by calling self.runcode() (which
2416 object. The code is executed by calling self.runcode() (which
2376 also handles run-time exceptions, except for SystemExit).
2417 also handles run-time exceptions, except for SystemExit).
2377
2418
2378 The return value is:
2419 The return value is:
2379
2420
2380 - True in case 2
2421 - True in case 2
2381
2422
2382 - False in the other cases, unless an exception is raised, where
2423 - False in the other cases, unless an exception is raised, where
2383 None is returned instead. This can be used by external callers to
2424 None is returned instead. This can be used by external callers to
2384 know whether to continue feeding input or not.
2425 know whether to continue feeding input or not.
2385
2426
2386 The return value can be used to decide whether to use sys.ps1 or
2427 The return value can be used to decide whether to use sys.ps1 or
2387 sys.ps2 to prompt the next line."""
2428 sys.ps2 to prompt the next line."""
2388
2429
2389 # if the source code has leading blanks, add 'if 1:\n' to it
2430 # if the source code has leading blanks, add 'if 1:\n' to it
2390 # this allows execution of indented pasted code. It is tempting
2431 # this allows execution of indented pasted code. It is tempting
2391 # to add '\n' at the end of source to run commands like ' a=1'
2432 # to add '\n' at the end of source to run commands like ' a=1'
2392 # directly, but this fails for more complicated scenarios
2433 # directly, but this fails for more complicated scenarios
2393 source=source.encode(self.stdin_encoding)
2434 source=source.encode(self.stdin_encoding)
2394 if source[:1] in [' ', '\t']:
2435 if source[:1] in [' ', '\t']:
2395 source = 'if 1:\n%s' % source
2436 source = 'if 1:\n%s' % source
2396
2437
2397 try:
2438 try:
2398 code = self.compile(source,filename,symbol)
2439 code = self.compile(source,filename,symbol)
2399 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2440 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2400 # Case 1
2441 # Case 1
2401 self.showsyntaxerror(filename)
2442 self.showsyntaxerror(filename)
2402 return None
2443 return None
2403
2444
2404 if code is None:
2445 if code is None:
2405 # Case 2
2446 # Case 2
2406 return True
2447 return True
2407
2448
2408 # Case 3
2449 # Case 3
2409 # We store the code object so that threaded shells and
2450 # We store the code object so that threaded shells and
2410 # custom exception handlers can access all this info if needed.
2451 # custom exception handlers can access all this info if needed.
2411 # The source corresponding to this can be obtained from the
2452 # The source corresponding to this can be obtained from the
2412 # buffer attribute as '\n'.join(self.buffer).
2453 # buffer attribute as '\n'.join(self.buffer).
2413 self.code_to_run = code
2454 self.code_to_run = code
2414 # now actually execute the code object
2455 # now actually execute the code object
2415 if self.runcode(code) == 0:
2456 if self.runcode(code) == 0:
2416 return False
2457 return False
2417 else:
2458 else:
2418 return None
2459 return None
2419
2460
2420 def runcode(self,code_obj):
2461 def runcode(self,code_obj):
2421 """Execute a code object.
2462 """Execute a code object.
2422
2463
2423 When an exception occurs, self.showtraceback() is called to display a
2464 When an exception occurs, self.showtraceback() is called to display a
2424 traceback.
2465 traceback.
2425
2466
2426 Return value: a flag indicating whether the code to be run completed
2467 Return value: a flag indicating whether the code to be run completed
2427 successfully:
2468 successfully:
2428
2469
2429 - 0: successful execution.
2470 - 0: successful execution.
2430 - 1: an error occurred.
2471 - 1: an error occurred.
2431 """
2472 """
2432
2473
2433 # Set our own excepthook in case the user code tries to call it
2474 # Set our own excepthook in case the user code tries to call it
2434 # directly, so that the IPython crash handler doesn't get triggered
2475 # directly, so that the IPython crash handler doesn't get triggered
2435 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2476 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2436
2477
2437 # we save the original sys.excepthook in the instance, in case config
2478 # we save the original sys.excepthook in the instance, in case config
2438 # code (such as magics) needs access to it.
2479 # code (such as magics) needs access to it.
2439 self.sys_excepthook = old_excepthook
2480 self.sys_excepthook = old_excepthook
2440 outflag = 1 # happens in more places, so it's easier as default
2481 outflag = 1 # happens in more places, so it's easier as default
2441 try:
2482 try:
2442 try:
2483 try:
2443 self.hooks.pre_runcode_hook()
2484 self.hooks.pre_runcode_hook()
2444 exec code_obj in self.user_global_ns, self.user_ns
2485 exec code_obj in self.user_global_ns, self.user_ns
2445 finally:
2486 finally:
2446 # Reset our crash handler in place
2487 # Reset our crash handler in place
2447 sys.excepthook = old_excepthook
2488 sys.excepthook = old_excepthook
2448 except SystemExit:
2489 except SystemExit:
2449 self.resetbuffer()
2490 self.resetbuffer()
2450 self.showtraceback()
2491 self.showtraceback()
2451 warn("Type %exit or %quit to exit IPython "
2492 warn("Type %exit or %quit to exit IPython "
2452 "(%Exit or %Quit do so unconditionally).",level=1)
2493 "(%Exit or %Quit do so unconditionally).",level=1)
2453 except self.custom_exceptions:
2494 except self.custom_exceptions:
2454 etype,value,tb = sys.exc_info()
2495 etype,value,tb = sys.exc_info()
2455 self.CustomTB(etype,value,tb)
2496 self.CustomTB(etype,value,tb)
2456 except:
2497 except:
2457 self.showtraceback()
2498 self.showtraceback()
2458 else:
2499 else:
2459 outflag = 0
2500 outflag = 0
2460 if softspace(sys.stdout, 0):
2501 if softspace(sys.stdout, 0):
2461 print
2502 print
2462 # Flush out code object which has been run (and source)
2503 # Flush out code object which has been run (and source)
2463 self.code_to_run = None
2504 self.code_to_run = None
2464 return outflag
2505 return outflag
2465
2506
2466 def push_line(self, line):
2507 def push_line(self, line):
2467 """Push a line to the interpreter.
2508 """Push a line to the interpreter.
2468
2509
2469 The line should not have a trailing newline; it may have
2510 The line should not have a trailing newline; it may have
2470 internal newlines. The line is appended to a buffer and the
2511 internal newlines. The line is appended to a buffer and the
2471 interpreter's runsource() method is called with the
2512 interpreter's runsource() method is called with the
2472 concatenated contents of the buffer as source. If this
2513 concatenated contents of the buffer as source. If this
2473 indicates that the command was executed or invalid, the buffer
2514 indicates that the command was executed or invalid, the buffer
2474 is reset; otherwise, the command is incomplete, and the buffer
2515 is reset; otherwise, the command is incomplete, and the buffer
2475 is left as it was after the line was appended. The return
2516 is left as it was after the line was appended. The return
2476 value is 1 if more input is required, 0 if the line was dealt
2517 value is 1 if more input is required, 0 if the line was dealt
2477 with in some way (this is the same as runsource()).
2518 with in some way (this is the same as runsource()).
2478 """
2519 """
2479
2520
2480 # autoindent management should be done here, and not in the
2521 # autoindent management should be done here, and not in the
2481 # interactive loop, since that one is only seen by keyboard input. We
2522 # interactive loop, since that one is only seen by keyboard input. We
2482 # need this done correctly even for code run via runlines (which uses
2523 # need this done correctly even for code run via runlines (which uses
2483 # push).
2524 # push).
2484
2525
2485 #print 'push line: <%s>' % line # dbg
2526 #print 'push line: <%s>' % line # dbg
2486 for subline in line.splitlines():
2527 for subline in line.splitlines():
2487 self.autoindent_update(subline)
2528 self.autoindent_update(subline)
2488 self.buffer.append(line)
2529 self.buffer.append(line)
2489 more = self.runsource('\n'.join(self.buffer), self.filename)
2530 more = self.runsource('\n'.join(self.buffer), self.filename)
2490 if not more:
2531 if not more:
2491 self.resetbuffer()
2532 self.resetbuffer()
2492 return more
2533 return more
2493
2534
2494 def split_user_input(self, line):
2535 def split_user_input(self, line):
2495 # This is really a hold-over to support ipapi and some extensions
2536 # This is really a hold-over to support ipapi and some extensions
2496 return prefilter.splitUserInput(line)
2537 return prefilter.splitUserInput(line)
2497
2538
2498 def resetbuffer(self):
2539 def resetbuffer(self):
2499 """Reset the input buffer."""
2540 """Reset the input buffer."""
2500 self.buffer[:] = []
2541 self.buffer[:] = []
2501
2542
2502 def raw_input(self,prompt='',continue_prompt=False):
2543 def raw_input(self,prompt='',continue_prompt=False):
2503 """Write a prompt and read a line.
2544 """Write a prompt and read a line.
2504
2545
2505 The returned line does not include the trailing newline.
2546 The returned line does not include the trailing newline.
2506 When the user enters the EOF key sequence, EOFError is raised.
2547 When the user enters the EOF key sequence, EOFError is raised.
2507
2548
2508 Optional inputs:
2549 Optional inputs:
2509
2550
2510 - prompt(''): a string to be printed to prompt the user.
2551 - prompt(''): a string to be printed to prompt the user.
2511
2552
2512 - continue_prompt(False): whether this line is the first one or a
2553 - continue_prompt(False): whether this line is the first one or a
2513 continuation in a sequence of inputs.
2554 continuation in a sequence of inputs.
2514 """
2555 """
2515
2556
2516 # Code run by the user may have modified the readline completer state.
2557 # Code run by the user may have modified the readline completer state.
2517 # We must ensure that our completer is back in place.
2558 # We must ensure that our completer is back in place.
2518 if self.has_readline:
2559 if self.has_readline:
2519 self.set_completer()
2560 self.set_completer()
2520
2561
2521 try:
2562 try:
2522 line = raw_input_original(prompt).decode(self.stdin_encoding)
2563 line = raw_input_original(prompt).decode(self.stdin_encoding)
2523 except ValueError:
2564 except ValueError:
2524 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2565 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2525 " or sys.stdout.close()!\nExiting IPython!")
2566 " or sys.stdout.close()!\nExiting IPython!")
2526 self.ask_exit()
2567 self.ask_exit()
2527 return ""
2568 return ""
2528
2569
2529 # Try to be reasonably smart about not re-indenting pasted input more
2570 # Try to be reasonably smart about not re-indenting pasted input more
2530 # than necessary. We do this by trimming out the auto-indent initial
2571 # than necessary. We do this by trimming out the auto-indent initial
2531 # spaces, if the user's actual input started itself with whitespace.
2572 # spaces, if the user's actual input started itself with whitespace.
2532 #debugx('self.buffer[-1]')
2573 #debugx('self.buffer[-1]')
2533
2574
2534 if self.autoindent:
2575 if self.autoindent:
2535 if num_ini_spaces(line) > self.indent_current_nsp:
2576 if num_ini_spaces(line) > self.indent_current_nsp:
2536 line = line[self.indent_current_nsp:]
2577 line = line[self.indent_current_nsp:]
2537 self.indent_current_nsp = 0
2578 self.indent_current_nsp = 0
2538
2579
2539 # store the unfiltered input before the user has any chance to modify
2580 # store the unfiltered input before the user has any chance to modify
2540 # it.
2581 # it.
2541 if line.strip():
2582 if line.strip():
2542 if continue_prompt:
2583 if continue_prompt:
2543 self.input_hist_raw[-1] += '%s\n' % line
2584 self.input_hist_raw[-1] += '%s\n' % line
2544 if self.has_readline: # and some config option is set?
2585 if self.has_readline: # and some config option is set?
2545 try:
2586 try:
2546 histlen = self.readline.get_current_history_length()
2587 histlen = self.readline.get_current_history_length()
2547 if histlen > 1:
2588 if histlen > 1:
2548 newhist = self.input_hist_raw[-1].rstrip()
2589 newhist = self.input_hist_raw[-1].rstrip()
2549 self.readline.remove_history_item(histlen-1)
2590 self.readline.remove_history_item(histlen-1)
2550 self.readline.replace_history_item(histlen-2,
2591 self.readline.replace_history_item(histlen-2,
2551 newhist.encode(self.stdin_encoding))
2592 newhist.encode(self.stdin_encoding))
2552 except AttributeError:
2593 except AttributeError:
2553 pass # re{move,place}_history_item are new in 2.4.
2594 pass # re{move,place}_history_item are new in 2.4.
2554 else:
2595 else:
2555 self.input_hist_raw.append('%s\n' % line)
2596 self.input_hist_raw.append('%s\n' % line)
2556 # only entries starting at first column go to shadow history
2597 # only entries starting at first column go to shadow history
2557 if line.lstrip() == line:
2598 if line.lstrip() == line:
2558 self.shadowhist.add(line.strip())
2599 self.shadowhist.add(line.strip())
2559 elif not continue_prompt:
2600 elif not continue_prompt:
2560 self.input_hist_raw.append('\n')
2601 self.input_hist_raw.append('\n')
2561 try:
2602 try:
2562 lineout = self.prefilter(line,continue_prompt)
2603 lineout = self.prefilter(line,continue_prompt)
2563 except:
2604 except:
2564 # blanket except, in case a user-defined prefilter crashes, so it
2605 # blanket except, in case a user-defined prefilter crashes, so it
2565 # can't take all of ipython with it.
2606 # can't take all of ipython with it.
2566 self.showtraceback()
2607 self.showtraceback()
2567 return ''
2608 return ''
2568 else:
2609 else:
2569 return lineout
2610 return lineout
2570
2611
2571 def _prefilter(self, line, continue_prompt):
2612 def _prefilter(self, line, continue_prompt):
2572 """Calls different preprocessors, depending on the form of line."""
2613 """Calls different preprocessors, depending on the form of line."""
2573
2614
2574 # All handlers *must* return a value, even if it's blank ('').
2615 # All handlers *must* return a value, even if it's blank ('').
2575
2616
2576 # Lines are NOT logged here. Handlers should process the line as
2617 # Lines are NOT logged here. Handlers should process the line as
2577 # needed, update the cache AND log it (so that the input cache array
2618 # needed, update the cache AND log it (so that the input cache array
2578 # stays synced).
2619 # stays synced).
2579
2620
2580 #.....................................................................
2621 #.....................................................................
2581 # Code begins
2622 # Code begins
2582
2623
2583 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2624 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2584
2625
2585 # save the line away in case we crash, so the post-mortem handler can
2626 # save the line away in case we crash, so the post-mortem handler can
2586 # record it
2627 # record it
2587 self._last_input_line = line
2628 self._last_input_line = line
2588
2629
2589 #print '***line: <%s>' % line # dbg
2630 #print '***line: <%s>' % line # dbg
2590
2631
2591 if not line:
2632 if not line:
2592 # Return immediately on purely empty lines, so that if the user
2633 # Return immediately on purely empty lines, so that if the user
2593 # previously typed some whitespace that started a continuation
2634 # previously typed some whitespace that started a continuation
2594 # prompt, he can break out of that loop with just an empty line.
2635 # prompt, he can break out of that loop with just an empty line.
2595 # This is how the default python prompt works.
2636 # This is how the default python prompt works.
2596
2637
2597 # Only return if the accumulated input buffer was just whitespace!
2638 # Only return if the accumulated input buffer was just whitespace!
2598 if ''.join(self.buffer).isspace():
2639 if ''.join(self.buffer).isspace():
2599 self.buffer[:] = []
2640 self.buffer[:] = []
2600 return ''
2641 return ''
2601
2642
2602 line_info = prefilter.LineInfo(line, continue_prompt)
2643 line_info = prefilter.LineInfo(line, continue_prompt)
2603
2644
2604 # the input history needs to track even empty lines
2645 # the input history needs to track even empty lines
2605 stripped = line.strip()
2646 stripped = line.strip()
2606
2647
2607 if not stripped:
2648 if not stripped:
2608 if not continue_prompt:
2649 if not continue_prompt:
2609 self.outputcache.prompt_count -= 1
2650 self.outputcache.prompt_count -= 1
2610 return self.handle_normal(line_info)
2651 return self.handle_normal(line_info)
2611
2652
2612 # print '***cont',continue_prompt # dbg
2653 # print '***cont',continue_prompt # dbg
2613 # special handlers are only allowed for single line statements
2654 # special handlers are only allowed for single line statements
2614 if continue_prompt and not self.multi_line_specials:
2655 if continue_prompt and not self.multi_line_specials:
2615 return self.handle_normal(line_info)
2656 return self.handle_normal(line_info)
2616
2657
2617
2658
2618 # See whether any pre-existing handler can take care of it
2659 # See whether any pre-existing handler can take care of it
2619 rewritten = self.hooks.input_prefilter(stripped)
2660 rewritten = self.hooks.input_prefilter(stripped)
2620 if rewritten != stripped: # ok, some prefilter did something
2661 if rewritten != stripped: # ok, some prefilter did something
2621 rewritten = line_info.pre + rewritten # add indentation
2662 rewritten = line_info.pre + rewritten # add indentation
2622 return self.handle_normal(prefilter.LineInfo(rewritten,
2663 return self.handle_normal(prefilter.LineInfo(rewritten,
2623 continue_prompt))
2664 continue_prompt))
2624
2665
2625 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2666 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2626
2667
2627 return prefilter.prefilter(line_info, self)
2668 return prefilter.prefilter(line_info, self)
2628
2669
2629
2670
2630 def _prefilter_dumb(self, line, continue_prompt):
2671 def _prefilter_dumb(self, line, continue_prompt):
2631 """simple prefilter function, for debugging"""
2672 """simple prefilter function, for debugging"""
2632 return self.handle_normal(line,continue_prompt)
2673 return self.handle_normal(line,continue_prompt)
2633
2674
2634
2675
2635 def multiline_prefilter(self, line, continue_prompt):
2676 def multiline_prefilter(self, line, continue_prompt):
2636 """ Run _prefilter for each line of input
2677 """ Run _prefilter for each line of input
2637
2678
2638 Covers cases where there are multiple lines in the user entry,
2679 Covers cases where there are multiple lines in the user entry,
2639 which is the case when the user goes back to a multiline history
2680 which is the case when the user goes back to a multiline history
2640 entry and presses enter.
2681 entry and presses enter.
2641
2682
2642 """
2683 """
2643 out = []
2684 out = []
2644 for l in line.rstrip('\n').split('\n'):
2685 for l in line.rstrip('\n').split('\n'):
2645 out.append(self._prefilter(l, continue_prompt))
2686 out.append(self._prefilter(l, continue_prompt))
2646 return '\n'.join(out)
2687 return '\n'.join(out)
2647
2688
2648 # Set the default prefilter() function (this can be user-overridden)
2689 # Set the default prefilter() function (this can be user-overridden)
2649 prefilter = multiline_prefilter
2690 prefilter = multiline_prefilter
2650
2691
2651 def handle_normal(self,line_info):
2692 def handle_normal(self,line_info):
2652 """Handle normal input lines. Use as a template for handlers."""
2693 """Handle normal input lines. Use as a template for handlers."""
2653
2694
2654 # With autoindent on, we need some way to exit the input loop, and I
2695 # With autoindent on, we need some way to exit the input loop, and I
2655 # don't want to force the user to have to backspace all the way to
2696 # don't want to force the user to have to backspace all the way to
2656 # clear the line. The rule will be in this case, that either two
2697 # clear the line. The rule will be in this case, that either two
2657 # lines of pure whitespace in a row, or a line of pure whitespace but
2698 # lines of pure whitespace in a row, or a line of pure whitespace but
2658 # of a size different to the indent level, will exit the input loop.
2699 # of a size different to the indent level, will exit the input loop.
2659 line = line_info.line
2700 line = line_info.line
2660 continue_prompt = line_info.continue_prompt
2701 continue_prompt = line_info.continue_prompt
2661
2702
2662 if (continue_prompt and self.autoindent and line.isspace() and
2703 if (continue_prompt and self.autoindent and line.isspace() and
2663 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2704 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2664 (self.buffer[-1]).isspace() )):
2705 (self.buffer[-1]).isspace() )):
2665 line = ''
2706 line = ''
2666
2707
2667 self.log(line,line,continue_prompt)
2708 self.log(line,line,continue_prompt)
2668 return line
2709 return line
2669
2710
2670 def handle_alias(self,line_info):
2711 def handle_alias(self,line_info):
2671 """Handle alias input lines. """
2712 """Handle alias input lines. """
2672 tgt = self.alias_table[line_info.iFun]
2713 tgt = self.alias_table[line_info.iFun]
2673 # print "=>",tgt #dbg
2714 # print "=>",tgt #dbg
2674 if callable(tgt):
2715 if callable(tgt):
2675 if '$' in line_info.line:
2716 if '$' in line_info.line:
2676 call_meth = '(_ip, _ip.var_expand(%s))'
2717 call_meth = '(_ip, _ip.var_expand(%s))'
2677 else:
2718 else:
2678 call_meth = '(_ip,%s)'
2719 call_meth = '(_ip,%s)'
2679 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2720 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2680 line_info.iFun,
2721 line_info.iFun,
2681 make_quoted_expr(line_info.line))
2722 make_quoted_expr(line_info.line))
2682 else:
2723 else:
2683 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2724 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2684
2725
2685 # pre is needed, because it carries the leading whitespace. Otherwise
2726 # pre is needed, because it carries the leading whitespace. Otherwise
2686 # aliases won't work in indented sections.
2727 # aliases won't work in indented sections.
2687 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2728 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2688 make_quoted_expr( transformed ))
2729 make_quoted_expr( transformed ))
2689
2730
2690 self.log(line_info.line,line_out,line_info.continue_prompt)
2731 self.log(line_info.line,line_out,line_info.continue_prompt)
2691 #print 'line out:',line_out # dbg
2732 #print 'line out:',line_out # dbg
2692 return line_out
2733 return line_out
2693
2734
2694 def handle_shell_escape(self, line_info):
2735 def handle_shell_escape(self, line_info):
2695 """Execute the line in a shell, empty return value"""
2736 """Execute the line in a shell, empty return value"""
2696 #print 'line in :', `line` # dbg
2737 #print 'line in :', `line` # dbg
2697 line = line_info.line
2738 line = line_info.line
2698 if line.lstrip().startswith('!!'):
2739 if line.lstrip().startswith('!!'):
2699 # rewrite LineInfo's line, iFun and theRest to properly hold the
2740 # rewrite LineInfo's line, iFun and theRest to properly hold the
2700 # call to %sx and the actual command to be executed, so
2741 # call to %sx and the actual command to be executed, so
2701 # handle_magic can work correctly. Note that this works even if
2742 # handle_magic can work correctly. Note that this works even if
2702 # the line is indented, so it handles multi_line_specials
2743 # the line is indented, so it handles multi_line_specials
2703 # properly.
2744 # properly.
2704 new_rest = line.lstrip()[2:]
2745 new_rest = line.lstrip()[2:]
2705 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2746 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2706 line_info.iFun = 'sx'
2747 line_info.iFun = 'sx'
2707 line_info.theRest = new_rest
2748 line_info.theRest = new_rest
2708 return self.handle_magic(line_info)
2749 return self.handle_magic(line_info)
2709 else:
2750 else:
2710 cmd = line.lstrip().lstrip('!')
2751 cmd = line.lstrip().lstrip('!')
2711 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2752 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2712 make_quoted_expr(cmd))
2753 make_quoted_expr(cmd))
2713 # update cache/log and return
2754 # update cache/log and return
2714 self.log(line,line_out,line_info.continue_prompt)
2755 self.log(line,line_out,line_info.continue_prompt)
2715 return line_out
2756 return line_out
2716
2757
2717 def handle_magic(self, line_info):
2758 def handle_magic(self, line_info):
2718 """Execute magic functions."""
2759 """Execute magic functions."""
2719 iFun = line_info.iFun
2760 iFun = line_info.iFun
2720 theRest = line_info.theRest
2761 theRest = line_info.theRest
2721 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2762 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2722 make_quoted_expr(iFun + " " + theRest))
2763 make_quoted_expr(iFun + " " + theRest))
2723 self.log(line_info.line,cmd,line_info.continue_prompt)
2764 self.log(line_info.line,cmd,line_info.continue_prompt)
2724 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2765 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2725 return cmd
2766 return cmd
2726
2767
2727 def handle_auto(self, line_info):
2768 def handle_auto(self, line_info):
2728 """Hande lines which can be auto-executed, quoting if requested."""
2769 """Hande lines which can be auto-executed, quoting if requested."""
2729
2770
2730 line = line_info.line
2771 line = line_info.line
2731 iFun = line_info.iFun
2772 iFun = line_info.iFun
2732 theRest = line_info.theRest
2773 theRest = line_info.theRest
2733 pre = line_info.pre
2774 pre = line_info.pre
2734 continue_prompt = line_info.continue_prompt
2775 continue_prompt = line_info.continue_prompt
2735 obj = line_info.ofind(self)['obj']
2776 obj = line_info.ofind(self)['obj']
2736
2777
2737 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2778 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2738
2779
2739 # This should only be active for single-line input!
2780 # This should only be active for single-line input!
2740 if continue_prompt:
2781 if continue_prompt:
2741 self.log(line,line,continue_prompt)
2782 self.log(line,line,continue_prompt)
2742 return line
2783 return line
2743
2784
2744 force_auto = isinstance(obj, IPyAutocall)
2785 force_auto = isinstance(obj, IPyAutocall)
2745 auto_rewrite = True
2786 auto_rewrite = True
2746
2787
2747 if pre == self.ESC_QUOTE:
2788 if pre == self.ESC_QUOTE:
2748 # Auto-quote splitting on whitespace
2789 # Auto-quote splitting on whitespace
2749 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2790 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2750 elif pre == self.ESC_QUOTE2:
2791 elif pre == self.ESC_QUOTE2:
2751 # Auto-quote whole string
2792 # Auto-quote whole string
2752 newcmd = '%s("%s")' % (iFun,theRest)
2793 newcmd = '%s("%s")' % (iFun,theRest)
2753 elif pre == self.ESC_PAREN:
2794 elif pre == self.ESC_PAREN:
2754 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2795 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2755 else:
2796 else:
2756 # Auto-paren.
2797 # Auto-paren.
2757 # We only apply it to argument-less calls if the autocall
2798 # We only apply it to argument-less calls if the autocall
2758 # parameter is set to 2. We only need to check that autocall is <
2799 # parameter is set to 2. We only need to check that autocall is <
2759 # 2, since this function isn't called unless it's at least 1.
2800 # 2, since this function isn't called unless it's at least 1.
2760 if not theRest and (self.autocall < 2) and not force_auto:
2801 if not theRest and (self.autocall < 2) and not force_auto:
2761 newcmd = '%s %s' % (iFun,theRest)
2802 newcmd = '%s %s' % (iFun,theRest)
2762 auto_rewrite = False
2803 auto_rewrite = False
2763 else:
2804 else:
2764 if not force_auto and theRest.startswith('['):
2805 if not force_auto and theRest.startswith('['):
2765 if hasattr(obj,'__getitem__'):
2806 if hasattr(obj,'__getitem__'):
2766 # Don't autocall in this case: item access for an object
2807 # Don't autocall in this case: item access for an object
2767 # which is BOTH callable and implements __getitem__.
2808 # which is BOTH callable and implements __getitem__.
2768 newcmd = '%s %s' % (iFun,theRest)
2809 newcmd = '%s %s' % (iFun,theRest)
2769 auto_rewrite = False
2810 auto_rewrite = False
2770 else:
2811 else:
2771 # if the object doesn't support [] access, go ahead and
2812 # if the object doesn't support [] access, go ahead and
2772 # autocall
2813 # autocall
2773 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2814 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2774 elif theRest.endswith(';'):
2815 elif theRest.endswith(';'):
2775 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2816 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2776 else:
2817 else:
2777 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2818 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2778
2819
2779 if auto_rewrite:
2820 if auto_rewrite:
2780 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2821 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2781
2822
2782 try:
2823 try:
2783 # plain ascii works better w/ pyreadline, on some machines, so
2824 # plain ascii works better w/ pyreadline, on some machines, so
2784 # we use it and only print uncolored rewrite if we have unicode
2825 # we use it and only print uncolored rewrite if we have unicode
2785 rw = str(rw)
2826 rw = str(rw)
2786 print >>Term.cout, rw
2827 print >>Term.cout, rw
2787 except UnicodeEncodeError:
2828 except UnicodeEncodeError:
2788 print "-------------->" + newcmd
2829 print "-------------->" + newcmd
2789
2830
2790 # log what is now valid Python, not the actual user input (without the
2831 # log what is now valid Python, not the actual user input (without the
2791 # final newline)
2832 # final newline)
2792 self.log(line,newcmd,continue_prompt)
2833 self.log(line,newcmd,continue_prompt)
2793 return newcmd
2834 return newcmd
2794
2835
2795 def handle_help(self, line_info):
2836 def handle_help(self, line_info):
2796 """Try to get some help for the object.
2837 """Try to get some help for the object.
2797
2838
2798 obj? or ?obj -> basic information.
2839 obj? or ?obj -> basic information.
2799 obj?? or ??obj -> more details.
2840 obj?? or ??obj -> more details.
2800 """
2841 """
2801
2842
2802 line = line_info.line
2843 line = line_info.line
2803 # We need to make sure that we don't process lines which would be
2844 # We need to make sure that we don't process lines which would be
2804 # otherwise valid python, such as "x=1 # what?"
2845 # otherwise valid python, such as "x=1 # what?"
2805 try:
2846 try:
2806 codeop.compile_command(line)
2847 codeop.compile_command(line)
2807 except SyntaxError:
2848 except SyntaxError:
2808 # We should only handle as help stuff which is NOT valid syntax
2849 # We should only handle as help stuff which is NOT valid syntax
2809 if line[0]==self.ESC_HELP:
2850 if line[0]==self.ESC_HELP:
2810 line = line[1:]
2851 line = line[1:]
2811 elif line[-1]==self.ESC_HELP:
2852 elif line[-1]==self.ESC_HELP:
2812 line = line[:-1]
2853 line = line[:-1]
2813 self.log(line,'#?'+line,line_info.continue_prompt)
2854 self.log(line,'#?'+line,line_info.continue_prompt)
2814 if line:
2855 if line:
2815 #print 'line:<%r>' % line # dbg
2856 #print 'line:<%r>' % line # dbg
2816 self.magic_pinfo(line)
2857 self.magic_pinfo(line)
2817 else:
2858 else:
2818 page(self.usage,screen_lines=self.usable_screen_length)
2859 page(self.usage,screen_lines=self.usable_screen_length)
2819 return '' # Empty string is needed here!
2860 return '' # Empty string is needed here!
2820 except:
2861 except:
2821 # Pass any other exceptions through to the normal handler
2862 # Pass any other exceptions through to the normal handler
2822 return self.handle_normal(line_info)
2863 return self.handle_normal(line_info)
2823 else:
2864 else:
2824 # If the code compiles ok, we should handle it normally
2865 # If the code compiles ok, we should handle it normally
2825 return self.handle_normal(line_info)
2866 return self.handle_normal(line_info)
2826
2867
2827 def handle_emacs(self, line_info):
2868 def handle_emacs(self, line_info):
2828 """Handle input lines marked by python-mode."""
2869 """Handle input lines marked by python-mode."""
2829
2870
2830 # Currently, nothing is done. Later more functionality can be added
2871 # Currently, nothing is done. Later more functionality can be added
2831 # here if needed.
2872 # here if needed.
2832
2873
2833 # The input cache shouldn't be updated
2874 # The input cache shouldn't be updated
2834 return line_info.line
2875 return line_info.line
2835
2876
2836 def var_expand(self,cmd,depth=0):
2877 def var_expand(self,cmd,depth=0):
2837 """Expand python variables in a string.
2878 """Expand python variables in a string.
2838
2879
2839 The depth argument indicates how many frames above the caller should
2880 The depth argument indicates how many frames above the caller should
2840 be walked to look for the local namespace where to expand variables.
2881 be walked to look for the local namespace where to expand variables.
2841
2882
2842 The global namespace for expansion is always the user's interactive
2883 The global namespace for expansion is always the user's interactive
2843 namespace.
2884 namespace.
2844 """
2885 """
2845
2886
2846 return str(ItplNS(cmd,
2887 return str(ItplNS(cmd,
2847 self.user_ns, # globals
2888 self.user_ns, # globals
2848 # Skip our own frame in searching for locals:
2889 # Skip our own frame in searching for locals:
2849 sys._getframe(depth+1).f_locals # locals
2890 sys._getframe(depth+1).f_locals # locals
2850 ))
2891 ))
2851
2892
2852 def mktempfile(self,data=None):
2893 def mktempfile(self,data=None):
2853 """Make a new tempfile and return its filename.
2894 """Make a new tempfile and return its filename.
2854
2895
2855 This makes a call to tempfile.mktemp, but it registers the created
2896 This makes a call to tempfile.mktemp, but it registers the created
2856 filename internally so ipython cleans it up at exit time.
2897 filename internally so ipython cleans it up at exit time.
2857
2898
2858 Optional inputs:
2899 Optional inputs:
2859
2900
2860 - data(None): if data is given, it gets written out to the temp file
2901 - data(None): if data is given, it gets written out to the temp file
2861 immediately, and the file is closed again."""
2902 immediately, and the file is closed again."""
2862
2903
2863 filename = tempfile.mktemp('.py','ipython_edit_')
2904 filename = tempfile.mktemp('.py','ipython_edit_')
2864 self.tempfiles.append(filename)
2905 self.tempfiles.append(filename)
2865
2906
2866 if data:
2907 if data:
2867 tmp_file = open(filename,'w')
2908 tmp_file = open(filename,'w')
2868 tmp_file.write(data)
2909 tmp_file.write(data)
2869 tmp_file.close()
2910 tmp_file.close()
2870 return filename
2911 return filename
2871
2912
2872 def write(self,data):
2913 def write(self,data):
2873 """Write a string to the default output"""
2914 """Write a string to the default output"""
2874 Term.cout.write(data)
2915 Term.cout.write(data)
2875
2916
2876 def write_err(self,data):
2917 def write_err(self,data):
2877 """Write a string to the default error output"""
2918 """Write a string to the default error output"""
2878 Term.cerr.write(data)
2919 Term.cerr.write(data)
2879
2920
2880 def ask_exit(self):
2921 def ask_exit(self):
2881 """ Call for exiting. Can be overiden and used as a callback. """
2922 """ Call for exiting. Can be overiden and used as a callback. """
2882 self.exit_now = True
2923 self.exit_now = True
2883
2924
2884 def exit(self):
2925 def exit(self):
2885 """Handle interactive exit.
2926 """Handle interactive exit.
2886
2927
2887 This method calls the ask_exit callback."""
2928 This method calls the ask_exit callback."""
2888 if self.confirm_exit:
2929 if self.confirm_exit:
2889 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2930 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2890 self.ask_exit()
2931 self.ask_exit()
2891 else:
2932 else:
2892 self.ask_exit()
2933 self.ask_exit()
2893
2934
2894 def safe_execfile(self,fname,*where,**kw):
2935 def safe_execfile(self,fname,*where,**kw):
2895 """A safe version of the builtin execfile().
2936 """A safe version of the builtin execfile().
2896
2937
2897 This version will never throw an exception, and knows how to handle
2938 This version will never throw an exception, and knows how to handle
2898 ipython logs as well.
2939 ipython logs as well.
2899
2940
2900 :Parameters:
2941 :Parameters:
2901 fname : string
2942 fname : string
2902 Name of the file to be executed.
2943 Name of the file to be executed.
2903
2944
2904 where : tuple
2945 where : tuple
2905 One or two namespaces, passed to execfile() as (globals,locals).
2946 One or two namespaces, passed to execfile() as (globals,locals).
2906 If only one is given, it is passed as both.
2947 If only one is given, it is passed as both.
2907
2948
2908 :Keywords:
2949 :Keywords:
2909 islog : boolean (False)
2950 islog : boolean (False)
2910
2951
2911 quiet : boolean (True)
2952 quiet : boolean (True)
2912
2953
2913 exit_ignore : boolean (False)
2954 exit_ignore : boolean (False)
2914 """
2955 """
2915
2956
2916 def syspath_cleanup():
2957 def syspath_cleanup():
2917 """Internal cleanup routine for sys.path."""
2958 """Internal cleanup routine for sys.path."""
2918 if add_dname:
2959 if add_dname:
2919 try:
2960 try:
2920 sys.path.remove(dname)
2961 sys.path.remove(dname)
2921 except ValueError:
2962 except ValueError:
2922 # For some reason the user has already removed it, ignore.
2963 # For some reason the user has already removed it, ignore.
2923 pass
2964 pass
2924
2965
2925 fname = os.path.expanduser(fname)
2966 fname = os.path.expanduser(fname)
2926
2967
2927 # Find things also in current directory. This is needed to mimic the
2968 # Find things also in current directory. This is needed to mimic the
2928 # behavior of running a script from the system command line, where
2969 # behavior of running a script from the system command line, where
2929 # Python inserts the script's directory into sys.path
2970 # Python inserts the script's directory into sys.path
2930 dname = os.path.dirname(os.path.abspath(fname))
2971 dname = os.path.dirname(os.path.abspath(fname))
2931 add_dname = False
2972 add_dname = False
2932 if dname not in sys.path:
2973 if dname not in sys.path:
2933 sys.path.insert(0,dname)
2974 sys.path.insert(0,dname)
2934 add_dname = True
2975 add_dname = True
2935
2976
2936 try:
2977 try:
2937 xfile = open(fname)
2978 xfile = open(fname)
2938 except:
2979 except:
2939 print >> Term.cerr, \
2980 print >> Term.cerr, \
2940 'Could not open file <%s> for safe execution.' % fname
2981 'Could not open file <%s> for safe execution.' % fname
2941 syspath_cleanup()
2982 syspath_cleanup()
2942 return None
2983 return None
2943
2984
2944 kw.setdefault('islog',0)
2985 kw.setdefault('islog',0)
2945 kw.setdefault('quiet',1)
2986 kw.setdefault('quiet',1)
2946 kw.setdefault('exit_ignore',0)
2987 kw.setdefault('exit_ignore',0)
2947
2988
2948 first = xfile.readline()
2989 first = xfile.readline()
2949 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2990 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2950 xfile.close()
2991 xfile.close()
2951 # line by line execution
2992 # line by line execution
2952 if first.startswith(loghead) or kw['islog']:
2993 if first.startswith(loghead) or kw['islog']:
2953 print 'Loading log file <%s> one line at a time...' % fname
2994 print 'Loading log file <%s> one line at a time...' % fname
2954 if kw['quiet']:
2995 if kw['quiet']:
2955 stdout_save = sys.stdout
2996 stdout_save = sys.stdout
2956 sys.stdout = StringIO.StringIO()
2997 sys.stdout = StringIO.StringIO()
2957 try:
2998 try:
2958 globs,locs = where[0:2]
2999 globs,locs = where[0:2]
2959 except:
3000 except:
2960 try:
3001 try:
2961 globs = locs = where[0]
3002 globs = locs = where[0]
2962 except:
3003 except:
2963 globs = locs = globals()
3004 globs = locs = globals()
2964 badblocks = []
3005 badblocks = []
2965
3006
2966 # we also need to identify indented blocks of code when replaying
3007 # we also need to identify indented blocks of code when replaying
2967 # logs and put them together before passing them to an exec
3008 # logs and put them together before passing them to an exec
2968 # statement. This takes a bit of regexp and look-ahead work in the
3009 # statement. This takes a bit of regexp and look-ahead work in the
2969 # file. It's easiest if we swallow the whole thing in memory
3010 # file. It's easiest if we swallow the whole thing in memory
2970 # first, and manually walk through the lines list moving the
3011 # first, and manually walk through the lines list moving the
2971 # counter ourselves.
3012 # counter ourselves.
2972 indent_re = re.compile('\s+\S')
3013 indent_re = re.compile('\s+\S')
2973 xfile = open(fname)
3014 xfile = open(fname)
2974 filelines = xfile.readlines()
3015 filelines = xfile.readlines()
2975 xfile.close()
3016 xfile.close()
2976 nlines = len(filelines)
3017 nlines = len(filelines)
2977 lnum = 0
3018 lnum = 0
2978 while lnum < nlines:
3019 while lnum < nlines:
2979 line = filelines[lnum]
3020 line = filelines[lnum]
2980 lnum += 1
3021 lnum += 1
2981 # don't re-insert logger status info into cache
3022 # don't re-insert logger status info into cache
2982 if line.startswith('#log#'):
3023 if line.startswith('#log#'):
2983 continue
3024 continue
2984 else:
3025 else:
2985 # build a block of code (maybe a single line) for execution
3026 # build a block of code (maybe a single line) for execution
2986 block = line
3027 block = line
2987 try:
3028 try:
2988 next = filelines[lnum] # lnum has already incremented
3029 next = filelines[lnum] # lnum has already incremented
2989 except:
3030 except:
2990 next = None
3031 next = None
2991 while next and indent_re.match(next):
3032 while next and indent_re.match(next):
2992 block += next
3033 block += next
2993 lnum += 1
3034 lnum += 1
2994 try:
3035 try:
2995 next = filelines[lnum]
3036 next = filelines[lnum]
2996 except:
3037 except:
2997 next = None
3038 next = None
2998 # now execute the block of one or more lines
3039 # now execute the block of one or more lines
2999 try:
3040 try:
3000 exec block in globs,locs
3041 exec block in globs,locs
3001 except SystemExit:
3042 except SystemExit:
3002 pass
3043 pass
3003 except:
3044 except:
3004 badblocks.append(block.rstrip())
3045 badblocks.append(block.rstrip())
3005 if kw['quiet']: # restore stdout
3046 if kw['quiet']: # restore stdout
3006 sys.stdout.close()
3047 sys.stdout.close()
3007 sys.stdout = stdout_save
3048 sys.stdout = stdout_save
3008 print 'Finished replaying log file <%s>' % fname
3049 print 'Finished replaying log file <%s>' % fname
3009 if badblocks:
3050 if badblocks:
3010 print >> sys.stderr, ('\nThe following lines/blocks in file '
3051 print >> sys.stderr, ('\nThe following lines/blocks in file '
3011 '<%s> reported errors:' % fname)
3052 '<%s> reported errors:' % fname)
3012
3053
3013 for badline in badblocks:
3054 for badline in badblocks:
3014 print >> sys.stderr, badline
3055 print >> sys.stderr, badline
3015 else: # regular file execution
3056 else: # regular file execution
3016 try:
3057 try:
3017 if sys.platform == 'win32' and sys.version_info < (2,5,1):
3058 if sys.platform == 'win32' and sys.version_info < (2,5,1):
3018 # Work around a bug in Python for Windows. The bug was
3059 # Work around a bug in Python for Windows. The bug was
3019 # fixed in in Python 2.5 r54159 and 54158, but that's still
3060 # fixed in in Python 2.5 r54159 and 54158, but that's still
3020 # SVN Python as of March/07. For details, see:
3061 # SVN Python as of March/07. For details, see:
3021 # http://projects.scipy.org/ipython/ipython/ticket/123
3062 # http://projects.scipy.org/ipython/ipython/ticket/123
3022 try:
3063 try:
3023 globs,locs = where[0:2]
3064 globs,locs = where[0:2]
3024 except:
3065 except:
3025 try:
3066 try:
3026 globs = locs = where[0]
3067 globs = locs = where[0]
3027 except:
3068 except:
3028 globs = locs = globals()
3069 globs = locs = globals()
3029 exec file(fname) in globs,locs
3070 exec file(fname) in globs,locs
3030 else:
3071 else:
3031 execfile(fname,*where)
3072 execfile(fname,*where)
3032 except SyntaxError:
3073 except SyntaxError:
3033 self.showsyntaxerror()
3074 self.showsyntaxerror()
3034 warn('Failure executing file: <%s>' % fname)
3075 warn('Failure executing file: <%s>' % fname)
3035 except SystemExit,status:
3076 except SystemExit,status:
3036 # Code that correctly sets the exit status flag to success (0)
3077 # Code that correctly sets the exit status flag to success (0)
3037 # shouldn't be bothered with a traceback. Note that a plain
3078 # shouldn't be bothered with a traceback. Note that a plain
3038 # sys.exit() does NOT set the message to 0 (it's empty) so that
3079 # sys.exit() does NOT set the message to 0 (it's empty) so that
3039 # will still get a traceback. Note that the structure of the
3080 # will still get a traceback. Note that the structure of the
3040 # SystemExit exception changed between Python 2.4 and 2.5, so
3081 # SystemExit exception changed between Python 2.4 and 2.5, so
3041 # the checks must be done in a version-dependent way.
3082 # the checks must be done in a version-dependent way.
3042 show = False
3083 show = False
3043
3084
3044 if sys.version_info[:2] > (2,5):
3085 if sys.version_info[:2] > (2,5):
3045 if status.message!=0 and not kw['exit_ignore']:
3086 if status.message!=0 and not kw['exit_ignore']:
3046 show = True
3087 show = True
3047 else:
3088 else:
3048 if status.code and not kw['exit_ignore']:
3089 if status.code and not kw['exit_ignore']:
3049 show = True
3090 show = True
3050 if show:
3091 if show:
3051 self.showtraceback()
3092 self.showtraceback()
3052 warn('Failure executing file: <%s>' % fname)
3093 warn('Failure executing file: <%s>' % fname)
3053 except:
3094 except:
3054 self.showtraceback()
3095 self.showtraceback()
3055 warn('Failure executing file: <%s>' % fname)
3096 warn('Failure executing file: <%s>' % fname)
3056
3097
3057 syspath_cleanup()
3098 syspath_cleanup()
3058
3099
3059 #************************* end of file <iplib.py> *****************************
3100 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now