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