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