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