##// END OF EJS Templates
Moved a few things back to InteractiveShell....
Brian Granger -
Show More
@@ -1,148 +1,148 b''
1 # Get the config being loaded so we can set attributes on it
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
2 c = get_config()
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Global options
5 # Global options
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # c.Global.display_banner = True
8 # c.Global.display_banner = True
9
9
10 # c.Global.classic = False
10 # c.Global.classic = False
11
11
12 # c.Global.nosep = True
12 # c.Global.nosep = True
13
13
14 # Set this to determine the detail of what is logged at startup.
14 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
16 # c.Global.log_level = 20
17
17
18 # This should be a list of importable Python modules that have an
18 # This should be a list of importable Python modules that have an
19 # load_in_ipython(ip) method. This method gets called when the extension
19 # load_in_ipython(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
20 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
21 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
22 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
23 # c.Global.extensions = [
24 # 'myextension'
24 # 'myextension'
25 # ]
25 # ]
26
26
27 # These lines are run in IPython in the user's namespace after extensions
27 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
28 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
29 # c.Global.exec_lines = [
30 # 'import numpy',
30 # 'import numpy',
31 # 'a = 10; b = 20',
31 # 'a = 10; b = 20',
32 # '1/0'
32 # '1/0'
33 # ]
33 # ]
34
34
35 # These files are run in IPython in the user's namespace. Files with a .py
35 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
36 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
37 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
39 # c.Global.exec_files = [
40 # 'mycode.py',
40 # 'mycode.py',
41 # 'fancy.ipy'
41 # 'fancy.ipy'
42 # ]
42 # ]
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # InteractiveShell options
45 # InteractiveShell options
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 # c.InteractiveShell.autocall = 1
48 # c.InteractiveShell.autocall = 1
49
49
50 # c.TerminalInteractiveShell.autoedit_syntax = False
50 # c.TerminalInteractiveShell.autoedit_syntax = False
51
51
52 # c.TerminalInteractiveShell.autoindent = True
52 # c.InteractiveShell.autoindent = True
53
53
54 # c.InteractiveShell.automagic = False
54 # c.InteractiveShell.automagic = False
55
55
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
57
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59
59
60 # c.InteractiveShell.cache_size = 1000
60 # c.InteractiveShell.cache_size = 1000
61
61
62 # c.InteractiveShell.colors = 'LightBG'
62 # c.InteractiveShell.colors = 'LightBG'
63
63
64 # c.InteractiveShell.color_info = True
64 # c.InteractiveShell.color_info = True
65
65
66 # c.TerminalInteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67
67
68 # c.InteractiveShell.deep_reload = False
68 # c.InteractiveShell.deep_reload = False
69
69
70 # c.TerminalInteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71
71
72 # c.InteractiveShell.logstart = True
72 # c.InteractiveShell.logstart = True
73
73
74 # c.InteractiveShell.logfile = u'ipython_log.py'
74 # c.InteractiveShell.logfile = u'ipython_log.py'
75
75
76 # c.InteractiveShell.logappend = u'mylog.py'
76 # c.InteractiveShell.logappend = u'mylog.py'
77
77
78 # c.InteractiveShell.object_info_string_level = 0
78 # c.InteractiveShell.object_info_string_level = 0
79
79
80 # c.TerminalInteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81
81
82 # c.InteractiveShell.pdb = False
82 # c.InteractiveShell.pdb = False
83
83
84 # c.InteractiveShell.pprint = True
84 # c.InteractiveShell.pprint = True
85
85
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 # c.InteractiveShell.prompts_pad_left = True
89 # c.InteractiveShell.prompts_pad_left = True
90
90
91 # c.InteractiveShell.quiet = False
91 # c.InteractiveShell.quiet = False
92
92
93 # Readline
93 # Readline
94 # c.InteractiveShell.readline_use = True
94 # c.InteractiveShell.readline_use = True
95
95
96 # c.InteractiveShell.readline_parse_and_bind = [
96 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
97 # 'tab: complete',
98 # '"\C-l": possible-completions',
98 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
99 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
100 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
101 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
102 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
104 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
105 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
106 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
107 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
108 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
109 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
110 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
111 # '"\C-u": unix-line-discard',
112 # ]
112 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit__names = 0
115 # c.InteractiveShell.readline_omit__names = 0
116
116
117 # c.TerminalInteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
118
118
119 # c.TerminalInteractiveShell.separate_in = '\n'
119 # c.InteractiveShell.separate_in = '\n'
120 # c.TerminalInteractiveShell.separate_out = ''
120 # c.InteractiveShell.separate_out = ''
121 # c.TerminalInteractiveShell.separate_out2 = ''
121 # c.InteractiveShell.separate_out2 = ''
122
122
123 # c.InteractiveShell.system_header = "IPython system call: "
123 # c.InteractiveShell.system_header = "IPython system call: "
124
124
125 # c.InteractiveShell.system_verbose = True
125 # c.InteractiveShell.system_verbose = True
126
126
127 # c.TerminalInteractiveShell.term_title = False
127 # c.TerminalInteractiveShell.term_title = False
128
128
129 # c.InteractiveShell.wildcards_case_sensitive = True
129 # c.InteractiveShell.wildcards_case_sensitive = True
130
130
131 # c.InteractiveShell.xmode = 'Context'
131 # c.InteractiveShell.xmode = 'Context'
132
132
133 #-----------------------------------------------------------------------------
133 #-----------------------------------------------------------------------------
134 # PrefilterManager options
134 # PrefilterManager options
135 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
136
136
137 # c.PrefilterManager.multi_line_specials = True
137 # c.PrefilterManager.multi_line_specials = True
138
138
139 #-----------------------------------------------------------------------------
139 #-----------------------------------------------------------------------------
140 # AliasManager options
140 # AliasManager options
141 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
142
142
143 # Do this to disable all defaults
143 # Do this to disable all defaults
144 # c.AliasManager.default_aliases = []
144 # c.AliasManager.default_aliases = []
145
145
146 # c.AliasManager.user_aliases = [
146 # c.AliasManager.user_aliases = [
147 # ('foo', 'echo Hi')
147 # ('foo', 'echo Hi')
148 # ]
148 # ]
@@ -1,29 +1,29 b''
1 c = get_config()
1 c = get_config()
2
2
3 # This can be used at any point in a config file to load a sub config
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
5 load_subconfig('ipython_config.py')
6
6
7 c.InteractiveShell.prompt_in1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
7 c.InteractiveShell.prompt_in1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
8 c.InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
8 c.InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
9 c.InteractiveShell.prompt_out = '<\#> '
9 c.InteractiveShell.prompt_out = '<\#> '
10
10
11 c.InteractiveShell.prompts_pad_left = True
11 c.InteractiveShell.prompts_pad_left = True
12
12
13 c.TerminalInteractiveShell.separate_in = ''
13 c.InteractiveShell.separate_in = ''
14 c.TerminalInteractiveShell.separate_out = ''
14 c.InteractiveShell.separate_out = ''
15 c.TerminalInteractiveShell.separate_out2 = ''
15 c.InteractiveShell.separate_out2 = ''
16
16
17 c.PrefilterManager.multi_line_specials = True
17 c.PrefilterManager.multi_line_specials = True
18
18
19 lines = """
19 lines = """
20 %rehashx
20 %rehashx
21 """
21 """
22
22
23 # You have to make sure that attributes that are containers already
23 # You have to make sure that attributes that are containers already
24 # exist before using them. Simple assigning a new list will override
24 # exist before using them. Simple assigning a new list will override
25 # all previous values.
25 # all previous values.
26 if hasattr(c.Global, 'exec_lines'):
26 if hasattr(c.Global, 'exec_lines'):
27 c.Global.exec_lines.append(lines)
27 c.Global.exec_lines.append(lines)
28 else:
28 else:
29 c.Global.exec_lines = [lines] No newline at end of file
29 c.Global.exec_lines = [lines]
@@ -1,2024 +1,2044 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import abc
22 import codeop
22 import codeop
23 import exceptions
23 import exceptions
24 import new
24 import new
25 import os
25 import os
26 import re
26 import re
27 import string
27 import string
28 import sys
28 import sys
29 import tempfile
29 import tempfile
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.core import debugger, oinspect
32 from IPython.core import debugger, oinspect
33 from IPython.core import history as ipcorehist
33 from IPython.core import history as ipcorehist
34 from IPython.core import prefilter
34 from IPython.core import prefilter
35 from IPython.core import shadowns
35 from IPython.core import shadowns
36 from IPython.core import ultratb
36 from IPython.core import ultratb
37 from IPython.core.alias import AliasManager
37 from IPython.core.alias import AliasManager
38 from IPython.core.builtin_trap import BuiltinTrap
38 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.config.configurable import Configurable
39 from IPython.config.configurable import Configurable
40 from IPython.core.display_trap import DisplayTrap
40 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.error import UsageError
41 from IPython.core.error import UsageError
42 from IPython.core.extensions import ExtensionManager
42 from IPython.core.extensions import ExtensionManager
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.inputlist import InputList
44 from IPython.core.inputlist import InputList
45 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
46 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
47 from IPython.core.plugin import PluginManager
47 from IPython.core.plugin import PluginManager
48 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prefilter import PrefilterManager
49 from IPython.core.prompts import CachedOutput
49 from IPython.core.prompts import CachedOutput
50 import IPython.core.hooks
50 import IPython.core.hooks
51 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
52 from IPython.utils import PyColorize
52 from IPython.utils import PyColorize
53 from IPython.utils import pickleshare
53 from IPython.utils import pickleshare
54 from IPython.utils.doctestreload import doctest_reload
54 from IPython.utils.doctestreload import doctest_reload
55 from IPython.utils.ipstruct import Struct
55 from IPython.utils.ipstruct import Struct
56 from IPython.utils.io import Term, ask_yes_no
56 from IPython.utils.io import Term, ask_yes_no
57 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
57 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
58 from IPython.utils.process import getoutput, getoutputerror
58 from IPython.utils.process import getoutput, getoutputerror
59 from IPython.utils.strdispatch import StrDispatch
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
60 from IPython.utils.syspathcontext import prepended_to_syspath
61 from IPython.utils.text import num_ini_spaces
61 from IPython.utils.text import num_ini_spaces
62 from IPython.utils.warn import warn, error, fatal
62 from IPython.utils.warn import warn, error, fatal
63 from IPython.utils.traitlets import (
63 from IPython.utils.traitlets import (
64 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
64 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
65 )
65 )
66
66
67 # from IPython.utils import growl
67 # from IPython.utils import growl
68 # growl.start("IPython")
68 # growl.start("IPython")
69
69
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71 # Globals
71 # Globals
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73
73
74 # compiled regexps for autoindent management
74 # compiled regexps for autoindent management
75 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
75 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Utilities
78 # Utilities
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 # store the builtin raw_input globally, and use this always, in case user code
81 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
82 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
83 raw_input_original = raw_input
84
84
85 def softspace(file, newvalue):
85 def softspace(file, newvalue):
86 """Copied from code.py, to remove the dependency"""
86 """Copied from code.py, to remove the dependency"""
87
87
88 oldvalue = 0
88 oldvalue = 0
89 try:
89 try:
90 oldvalue = file.softspace
90 oldvalue = file.softspace
91 except AttributeError:
91 except AttributeError:
92 pass
92 pass
93 try:
93 try:
94 file.softspace = newvalue
94 file.softspace = newvalue
95 except (AttributeError, TypeError):
95 except (AttributeError, TypeError):
96 # "attribute-less object" or "read-only attributes"
96 # "attribute-less object" or "read-only attributes"
97 pass
97 pass
98 return oldvalue
98 return oldvalue
99
99
100
100
101 def no_op(*a, **kw): pass
101 def no_op(*a, **kw): pass
102
102
103 class SpaceInInput(exceptions.Exception): pass
103 class SpaceInInput(exceptions.Exception): pass
104
104
105 class Bunch: pass
105 class Bunch: pass
106
106
107 class SyntaxTB(ultratb.ListTB):
107 class SyntaxTB(ultratb.ListTB):
108 """Extension which holds some state: the last exception value"""
108 """Extension which holds some state: the last exception value"""
109
109
110 def __init__(self,color_scheme = 'NoColor'):
110 def __init__(self,color_scheme = 'NoColor'):
111 ultratb.ListTB.__init__(self,color_scheme)
111 ultratb.ListTB.__init__(self,color_scheme)
112 self.last_syntax_error = None
112 self.last_syntax_error = None
113
113
114 def __call__(self, etype, value, elist):
114 def __call__(self, etype, value, elist):
115 self.last_syntax_error = value
115 self.last_syntax_error = value
116 ultratb.ListTB.__call__(self,etype,value,elist)
116 ultratb.ListTB.__call__(self,etype,value,elist)
117
117
118 def clear_err_state(self):
118 def clear_err_state(self):
119 """Return the current error state and clear it"""
119 """Return the current error state and clear it"""
120 e = self.last_syntax_error
120 e = self.last_syntax_error
121 self.last_syntax_error = None
121 self.last_syntax_error = None
122 return e
122 return e
123
123
124
124
125 def get_default_colors():
125 def get_default_colors():
126 if sys.platform=='darwin':
126 if sys.platform=='darwin':
127 return "LightBG"
127 return "LightBG"
128 elif os.name=='nt':
128 elif os.name=='nt':
129 return 'Linux'
129 return 'Linux'
130 else:
130 else:
131 return 'Linux'
131 return 'Linux'
132
132
133
133
134 class SeparateStr(Str):
135 """A Str subclass to validate separate_in, separate_out, etc.
136
137 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
138 """
139
140 def validate(self, obj, value):
141 if value == '0': value = ''
142 value = value.replace('\\n','\n')
143 return super(SeparateStr, self).validate(obj, value)
144
145
134 #-----------------------------------------------------------------------------
146 #-----------------------------------------------------------------------------
135 # Main IPython class
147 # Main IPython class
136 #-----------------------------------------------------------------------------
148 #-----------------------------------------------------------------------------
137
149
138
150
139 class InteractiveShell(Configurable, Magic):
151 class InteractiveShell(Configurable, Magic):
140 """An enhanced, interactive shell for Python."""
152 """An enhanced, interactive shell for Python."""
141
153
142 autocall = Enum((0,1,2), default_value=1, config=True)
154 autocall = Enum((0,1,2), default_value=1, config=True)
155 # TODO: remove all autoindent logic and put into frontends.
156 # We can't do this yet because even runlines uses the autoindent.
157 autoindent = CBool(True, config=True)
143 automagic = CBool(True, config=True)
158 automagic = CBool(True, config=True)
144 cache_size = Int(1000, config=True)
159 cache_size = Int(1000, config=True)
145 color_info = CBool(True, config=True)
160 color_info = CBool(True, config=True)
146 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
161 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
147 default_value=get_default_colors(), config=True)
162 default_value=get_default_colors(), config=True)
148 debug = CBool(False, config=True)
163 debug = CBool(False, config=True)
149 deep_reload = CBool(False, config=True)
164 deep_reload = CBool(False, config=True)
150 filename = Str("<ipython console>")
165 filename = Str("<ipython console>")
151 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
166 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
152 logstart = CBool(False, config=True)
167 logstart = CBool(False, config=True)
153 logfile = Str('', config=True)
168 logfile = Str('', config=True)
154 logappend = Str('', config=True)
169 logappend = Str('', config=True)
155 object_info_string_level = Enum((0,1,2), default_value=0,
170 object_info_string_level = Enum((0,1,2), default_value=0,
156 config=True)
171 config=True)
157 pdb = CBool(False, config=True)
172 pdb = CBool(False, config=True)
158 pprint = CBool(True, config=True)
173 pprint = CBool(True, config=True)
159 profile = Str('', config=True)
174 profile = Str('', config=True)
160 prompt_in1 = Str('In [\\#]: ', config=True)
175 prompt_in1 = Str('In [\\#]: ', config=True)
161 prompt_in2 = Str(' .\\D.: ', config=True)
176 prompt_in2 = Str(' .\\D.: ', config=True)
162 prompt_out = Str('Out[\\#]: ', config=True)
177 prompt_out = Str('Out[\\#]: ', config=True)
163 prompts_pad_left = CBool(True, config=True)
178 prompts_pad_left = CBool(True, config=True)
164 quiet = CBool(False, config=True)
179 quiet = CBool(False, config=True)
165
180
166 # The readline stuff will eventually be moved to the terminal subclass
181 # The readline stuff will eventually be moved to the terminal subclass
167 # but for now, we can't do that as readline is welded in everywhere.
182 # but for now, we can't do that as readline is welded in everywhere.
168 readline_use = CBool(True, config=True)
183 readline_use = CBool(True, config=True)
169 readline_merge_completions = CBool(True, config=True)
184 readline_merge_completions = CBool(True, config=True)
170 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
185 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
171 readline_remove_delims = Str('-/~', config=True)
186 readline_remove_delims = Str('-/~', config=True)
172 readline_parse_and_bind = List([
187 readline_parse_and_bind = List([
173 'tab: complete',
188 'tab: complete',
174 '"\C-l": clear-screen',
189 '"\C-l": clear-screen',
175 'set show-all-if-ambiguous on',
190 'set show-all-if-ambiguous on',
176 '"\C-o": tab-insert',
191 '"\C-o": tab-insert',
177 '"\M-i": " "',
192 '"\M-i": " "',
178 '"\M-o": "\d\d\d\d"',
193 '"\M-o": "\d\d\d\d"',
179 '"\M-I": "\d\d\d\d"',
194 '"\M-I": "\d\d\d\d"',
180 '"\C-r": reverse-search-history',
195 '"\C-r": reverse-search-history',
181 '"\C-s": forward-search-history',
196 '"\C-s": forward-search-history',
182 '"\C-p": history-search-backward',
197 '"\C-p": history-search-backward',
183 '"\C-n": history-search-forward',
198 '"\C-n": history-search-forward',
184 '"\e[A": history-search-backward',
199 '"\e[A": history-search-backward',
185 '"\e[B": history-search-forward',
200 '"\e[B": history-search-forward',
186 '"\C-k": kill-line',
201 '"\C-k": kill-line',
187 '"\C-u": unix-line-discard',
202 '"\C-u": unix-line-discard',
188 ], allow_none=False, config=True)
203 ], allow_none=False, config=True)
189
204
205 # TODO: this part of prompt management should be moved to the frontends.
206 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 separate_in = SeparateStr('\n', config=True)
208 separate_out = SeparateStr('', config=True)
209 separate_out2 = SeparateStr('', config=True)
190 system_header = Str('IPython system call: ', config=True)
210 system_header = Str('IPython system call: ', config=True)
191 system_verbose = CBool(False, config=True)
211 system_verbose = CBool(False, config=True)
192 wildcards_case_sensitive = CBool(True, config=True)
212 wildcards_case_sensitive = CBool(True, config=True)
193 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
213 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
194 default_value='Context', config=True)
214 default_value='Context', config=True)
195
215
196 # Subcomponents of InteractiveShell
216 # Subcomponents of InteractiveShell
197 alias_manager = Instance('IPython.core.alias.AliasManager')
217 alias_manager = Instance('IPython.core.alias.AliasManager')
198 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
218 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
199 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
219 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
200 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
220 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
201 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
221 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
202 plugin_manager = Instance('IPython.core.plugin.PluginManager')
222 plugin_manager = Instance('IPython.core.plugin.PluginManager')
203
223
204 def __init__(self, config=None, ipython_dir=None,
224 def __init__(self, config=None, ipython_dir=None,
205 user_ns=None, user_global_ns=None,
225 user_ns=None, user_global_ns=None,
206 custom_exceptions=((),None)):
226 custom_exceptions=((),None)):
207
227
208 # This is where traits with a config_key argument are updated
228 # This is where traits with a config_key argument are updated
209 # from the values on config.
229 # from the values on config.
210 super(InteractiveShell, self).__init__(config=config)
230 super(InteractiveShell, self).__init__(config=config)
211
231
212 # These are relatively independent and stateless
232 # These are relatively independent and stateless
213 self.init_ipython_dir(ipython_dir)
233 self.init_ipython_dir(ipython_dir)
214 self.init_instance_attrs()
234 self.init_instance_attrs()
215
235
216 # Create namespaces (user_ns, user_global_ns, etc.)
236 # Create namespaces (user_ns, user_global_ns, etc.)
217 self.init_create_namespaces(user_ns, user_global_ns)
237 self.init_create_namespaces(user_ns, user_global_ns)
218 # This has to be done after init_create_namespaces because it uses
238 # This has to be done after init_create_namespaces because it uses
219 # something in self.user_ns, but before init_sys_modules, which
239 # something in self.user_ns, but before init_sys_modules, which
220 # is the first thing to modify sys.
240 # is the first thing to modify sys.
221 self.save_sys_module_state()
241 self.save_sys_module_state()
222 self.init_sys_modules()
242 self.init_sys_modules()
223
243
224 self.init_history()
244 self.init_history()
225 self.init_encoding()
245 self.init_encoding()
226 self.init_prefilter()
246 self.init_prefilter()
227
247
228 Magic.__init__(self, self)
248 Magic.__init__(self, self)
229
249
230 self.init_syntax_highlighting()
250 self.init_syntax_highlighting()
231 self.init_hooks()
251 self.init_hooks()
232 self.init_pushd_popd_magic()
252 self.init_pushd_popd_magic()
233 self.init_traceback_handlers(custom_exceptions)
253 self.init_traceback_handlers(custom_exceptions)
234 self.init_user_ns()
254 self.init_user_ns()
235 self.init_logger()
255 self.init_logger()
236 self.init_alias()
256 self.init_alias()
237 self.init_builtins()
257 self.init_builtins()
238
258
239 # pre_config_initialization
259 # pre_config_initialization
240 self.init_shadow_hist()
260 self.init_shadow_hist()
241
261
242 # The next section should contain averything that was in ipmaker.
262 # The next section should contain averything that was in ipmaker.
243 self.init_logstart()
263 self.init_logstart()
244
264
245 # The following was in post_config_initialization
265 # The following was in post_config_initialization
246 self.init_inspector()
266 self.init_inspector()
247 self.init_readline()
267 self.init_readline()
248 self.init_prompts()
268 self.init_prompts()
249 self.init_displayhook()
269 self.init_displayhook()
250 self.init_reload_doctest()
270 self.init_reload_doctest()
251 self.init_magics()
271 self.init_magics()
252 self.init_pdb()
272 self.init_pdb()
253 self.init_extension_manager()
273 self.init_extension_manager()
254 self.init_plugin_manager()
274 self.init_plugin_manager()
255 self.hooks.late_startup_hook()
275 self.hooks.late_startup_hook()
256
276
257 @classmethod
277 @classmethod
258 def instance(cls, *args, **kwargs):
278 def instance(cls, *args, **kwargs):
259 """Returns a global InteractiveShell instance."""
279 """Returns a global InteractiveShell instance."""
260 if not hasattr(cls, "_instance"):
280 if not hasattr(cls, "_instance"):
261 cls._instance = cls(*args, **kwargs)
281 cls._instance = cls(*args, **kwargs)
262 return cls._instance
282 return cls._instance
263
283
264 @classmethod
284 @classmethod
265 def initialized(cls):
285 def initialized(cls):
266 return hasattr(cls, "_instance")
286 return hasattr(cls, "_instance")
267
287
268 def get_ipython(self):
288 def get_ipython(self):
269 """Return the currently running IPython instance."""
289 """Return the currently running IPython instance."""
270 return self
290 return self
271
291
272 #-------------------------------------------------------------------------
292 #-------------------------------------------------------------------------
273 # Trait changed handlers
293 # Trait changed handlers
274 #-------------------------------------------------------------------------
294 #-------------------------------------------------------------------------
275
295
276 def _ipython_dir_changed(self, name, new):
296 def _ipython_dir_changed(self, name, new):
277 if not os.path.isdir(new):
297 if not os.path.isdir(new):
278 os.makedirs(new, mode = 0777)
298 os.makedirs(new, mode = 0777)
279
299
280 def set_autoindent(self,value=None):
300 def set_autoindent(self,value=None):
281 """Set the autoindent flag, checking for readline support.
301 """Set the autoindent flag, checking for readline support.
282
302
283 If called with no arguments, it acts as a toggle."""
303 If called with no arguments, it acts as a toggle."""
284
304
285 if not self.has_readline:
305 if not self.has_readline:
286 if os.name == 'posix':
306 if os.name == 'posix':
287 warn("The auto-indent feature requires the readline library")
307 warn("The auto-indent feature requires the readline library")
288 self.autoindent = 0
308 self.autoindent = 0
289 return
309 return
290 if value is None:
310 if value is None:
291 self.autoindent = not self.autoindent
311 self.autoindent = not self.autoindent
292 else:
312 else:
293 self.autoindent = value
313 self.autoindent = value
294
314
295 #-------------------------------------------------------------------------
315 #-------------------------------------------------------------------------
296 # init_* methods called by __init__
316 # init_* methods called by __init__
297 #-------------------------------------------------------------------------
317 #-------------------------------------------------------------------------
298
318
299 def init_ipython_dir(self, ipython_dir):
319 def init_ipython_dir(self, ipython_dir):
300 if ipython_dir is not None:
320 if ipython_dir is not None:
301 self.ipython_dir = ipython_dir
321 self.ipython_dir = ipython_dir
302 self.config.Global.ipython_dir = self.ipython_dir
322 self.config.Global.ipython_dir = self.ipython_dir
303 return
323 return
304
324
305 if hasattr(self.config.Global, 'ipython_dir'):
325 if hasattr(self.config.Global, 'ipython_dir'):
306 self.ipython_dir = self.config.Global.ipython_dir
326 self.ipython_dir = self.config.Global.ipython_dir
307 else:
327 else:
308 self.ipython_dir = get_ipython_dir()
328 self.ipython_dir = get_ipython_dir()
309
329
310 # All children can just read this
330 # All children can just read this
311 self.config.Global.ipython_dir = self.ipython_dir
331 self.config.Global.ipython_dir = self.ipython_dir
312
332
313 def init_instance_attrs(self):
333 def init_instance_attrs(self):
314 self.more = False
334 self.more = False
315
335
316 # command compiler
336 # command compiler
317 self.compile = codeop.CommandCompiler()
337 self.compile = codeop.CommandCompiler()
318
338
319 # User input buffer
339 # User input buffer
320 self.buffer = []
340 self.buffer = []
321
341
322 # Make an empty namespace, which extension writers can rely on both
342 # Make an empty namespace, which extension writers can rely on both
323 # existing and NEVER being used by ipython itself. This gives them a
343 # existing and NEVER being used by ipython itself. This gives them a
324 # convenient location for storing additional information and state
344 # convenient location for storing additional information and state
325 # their extensions may require, without fear of collisions with other
345 # their extensions may require, without fear of collisions with other
326 # ipython names that may develop later.
346 # ipython names that may develop later.
327 self.meta = Struct()
347 self.meta = Struct()
328
348
329 # Object variable to store code object waiting execution. This is
349 # Object variable to store code object waiting execution. This is
330 # used mainly by the multithreaded shells, but it can come in handy in
350 # used mainly by the multithreaded shells, but it can come in handy in
331 # other situations. No need to use a Queue here, since it's a single
351 # other situations. No need to use a Queue here, since it's a single
332 # item which gets cleared once run.
352 # item which gets cleared once run.
333 self.code_to_run = None
353 self.code_to_run = None
334
354
335 # Temporary files used for various purposes. Deleted at exit.
355 # Temporary files used for various purposes. Deleted at exit.
336 self.tempfiles = []
356 self.tempfiles = []
337
357
338 # Keep track of readline usage (later set by init_readline)
358 # Keep track of readline usage (later set by init_readline)
339 self.has_readline = False
359 self.has_readline = False
340
360
341 # keep track of where we started running (mainly for crash post-mortem)
361 # keep track of where we started running (mainly for crash post-mortem)
342 # This is not being used anywhere currently.
362 # This is not being used anywhere currently.
343 self.starting_dir = os.getcwd()
363 self.starting_dir = os.getcwd()
344
364
345 # Indentation management
365 # Indentation management
346 self.indent_current_nsp = 0
366 self.indent_current_nsp = 0
347
367
348 def init_encoding(self):
368 def init_encoding(self):
349 # Get system encoding at startup time. Certain terminals (like Emacs
369 # Get system encoding at startup time. Certain terminals (like Emacs
350 # under Win32 have it set to None, and we need to have a known valid
370 # under Win32 have it set to None, and we need to have a known valid
351 # encoding to use in the raw_input() method
371 # encoding to use in the raw_input() method
352 try:
372 try:
353 self.stdin_encoding = sys.stdin.encoding or 'ascii'
373 self.stdin_encoding = sys.stdin.encoding or 'ascii'
354 except AttributeError:
374 except AttributeError:
355 self.stdin_encoding = 'ascii'
375 self.stdin_encoding = 'ascii'
356
376
357 def init_syntax_highlighting(self):
377 def init_syntax_highlighting(self):
358 # Python source parser/formatter for syntax highlighting
378 # Python source parser/formatter for syntax highlighting
359 pyformat = PyColorize.Parser().format
379 pyformat = PyColorize.Parser().format
360 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
380 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
361
381
362 def init_pushd_popd_magic(self):
382 def init_pushd_popd_magic(self):
363 # for pushd/popd management
383 # for pushd/popd management
364 try:
384 try:
365 self.home_dir = get_home_dir()
385 self.home_dir = get_home_dir()
366 except HomeDirError, msg:
386 except HomeDirError, msg:
367 fatal(msg)
387 fatal(msg)
368
388
369 self.dir_stack = []
389 self.dir_stack = []
370
390
371 def init_logger(self):
391 def init_logger(self):
372 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
392 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
373 # local shortcut, this is used a LOT
393 # local shortcut, this is used a LOT
374 self.log = self.logger.log
394 self.log = self.logger.log
375
395
376 def init_logstart(self):
396 def init_logstart(self):
377 if self.logappend:
397 if self.logappend:
378 self.magic_logstart(self.logappend + ' append')
398 self.magic_logstart(self.logappend + ' append')
379 elif self.logfile:
399 elif self.logfile:
380 self.magic_logstart(self.logfile)
400 self.magic_logstart(self.logfile)
381 elif self.logstart:
401 elif self.logstart:
382 self.magic_logstart()
402 self.magic_logstart()
383
403
384 def init_builtins(self):
404 def init_builtins(self):
385 self.builtin_trap = BuiltinTrap(shell=self)
405 self.builtin_trap = BuiltinTrap(shell=self)
386
406
387 def init_inspector(self):
407 def init_inspector(self):
388 # Object inspector
408 # Object inspector
389 self.inspector = oinspect.Inspector(oinspect.InspectColors,
409 self.inspector = oinspect.Inspector(oinspect.InspectColors,
390 PyColorize.ANSICodeColors,
410 PyColorize.ANSICodeColors,
391 'NoColor',
411 'NoColor',
392 self.object_info_string_level)
412 self.object_info_string_level)
393
413
394 def init_prompts(self):
414 def init_prompts(self):
395 # Initialize cache, set in/out prompts and printing system
415 # Initialize cache, set in/out prompts and printing system
396 self.outputcache = CachedOutput(self,
416 self.outputcache = CachedOutput(self,
397 self.cache_size,
417 self.cache_size,
398 self.pprint,
418 self.pprint,
399 input_sep = self.separate_in,
419 input_sep = self.separate_in,
400 output_sep = self.separate_out,
420 output_sep = self.separate_out,
401 output_sep2 = self.separate_out2,
421 output_sep2 = self.separate_out2,
402 ps1 = self.prompt_in1,
422 ps1 = self.prompt_in1,
403 ps2 = self.prompt_in2,
423 ps2 = self.prompt_in2,
404 ps_out = self.prompt_out,
424 ps_out = self.prompt_out,
405 pad_left = self.prompts_pad_left)
425 pad_left = self.prompts_pad_left)
406
426
407 # user may have over-ridden the default print hook:
427 # user may have over-ridden the default print hook:
408 try:
428 try:
409 self.outputcache.__class__.display = self.hooks.display
429 self.outputcache.__class__.display = self.hooks.display
410 except AttributeError:
430 except AttributeError:
411 pass
431 pass
412
432
413 def init_displayhook(self):
433 def init_displayhook(self):
414 self.display_trap = DisplayTrap(hook=self.outputcache)
434 self.display_trap = DisplayTrap(hook=self.outputcache)
415
435
416 def init_reload_doctest(self):
436 def init_reload_doctest(self):
417 # Do a proper resetting of doctest, including the necessary displayhook
437 # Do a proper resetting of doctest, including the necessary displayhook
418 # monkeypatching
438 # monkeypatching
419 try:
439 try:
420 doctest_reload()
440 doctest_reload()
421 except ImportError:
441 except ImportError:
422 warn("doctest module does not exist.")
442 warn("doctest module does not exist.")
423
443
424 #-------------------------------------------------------------------------
444 #-------------------------------------------------------------------------
425 # Things related to injections into the sys module
445 # Things related to injections into the sys module
426 #-------------------------------------------------------------------------
446 #-------------------------------------------------------------------------
427
447
428 def save_sys_module_state(self):
448 def save_sys_module_state(self):
429 """Save the state of hooks in the sys module.
449 """Save the state of hooks in the sys module.
430
450
431 This has to be called after self.user_ns is created.
451 This has to be called after self.user_ns is created.
432 """
452 """
433 self._orig_sys_module_state = {}
453 self._orig_sys_module_state = {}
434 self._orig_sys_module_state['stdin'] = sys.stdin
454 self._orig_sys_module_state['stdin'] = sys.stdin
435 self._orig_sys_module_state['stdout'] = sys.stdout
455 self._orig_sys_module_state['stdout'] = sys.stdout
436 self._orig_sys_module_state['stderr'] = sys.stderr
456 self._orig_sys_module_state['stderr'] = sys.stderr
437 self._orig_sys_module_state['excepthook'] = sys.excepthook
457 self._orig_sys_module_state['excepthook'] = sys.excepthook
438 try:
458 try:
439 self._orig_sys_modules_main_name = self.user_ns['__name__']
459 self._orig_sys_modules_main_name = self.user_ns['__name__']
440 except KeyError:
460 except KeyError:
441 pass
461 pass
442
462
443 def restore_sys_module_state(self):
463 def restore_sys_module_state(self):
444 """Restore the state of the sys module."""
464 """Restore the state of the sys module."""
445 try:
465 try:
446 for k, v in self._orig_sys_module_state.items():
466 for k, v in self._orig_sys_module_state.items():
447 setattr(sys, k, v)
467 setattr(sys, k, v)
448 except AttributeError:
468 except AttributeError:
449 pass
469 pass
450 try:
470 try:
451 delattr(sys, 'ipcompleter')
471 delattr(sys, 'ipcompleter')
452 except AttributeError:
472 except AttributeError:
453 pass
473 pass
454 # Reset what what done in self.init_sys_modules
474 # Reset what what done in self.init_sys_modules
455 try:
475 try:
456 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
476 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
457 except (AttributeError, KeyError):
477 except (AttributeError, KeyError):
458 pass
478 pass
459
479
460 #-------------------------------------------------------------------------
480 #-------------------------------------------------------------------------
461 # Things related to hooks
481 # Things related to hooks
462 #-------------------------------------------------------------------------
482 #-------------------------------------------------------------------------
463
483
464 def init_hooks(self):
484 def init_hooks(self):
465 # hooks holds pointers used for user-side customizations
485 # hooks holds pointers used for user-side customizations
466 self.hooks = Struct()
486 self.hooks = Struct()
467
487
468 self.strdispatchers = {}
488 self.strdispatchers = {}
469
489
470 # Set all default hooks, defined in the IPython.hooks module.
490 # Set all default hooks, defined in the IPython.hooks module.
471 hooks = IPython.core.hooks
491 hooks = IPython.core.hooks
472 for hook_name in hooks.__all__:
492 for hook_name in hooks.__all__:
473 # default hooks have priority 100, i.e. low; user hooks should have
493 # default hooks have priority 100, i.e. low; user hooks should have
474 # 0-100 priority
494 # 0-100 priority
475 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
495 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
476
496
477 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
497 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
478 """set_hook(name,hook) -> sets an internal IPython hook.
498 """set_hook(name,hook) -> sets an internal IPython hook.
479
499
480 IPython exposes some of its internal API as user-modifiable hooks. By
500 IPython exposes some of its internal API as user-modifiable hooks. By
481 adding your function to one of these hooks, you can modify IPython's
501 adding your function to one of these hooks, you can modify IPython's
482 behavior to call at runtime your own routines."""
502 behavior to call at runtime your own routines."""
483
503
484 # At some point in the future, this should validate the hook before it
504 # At some point in the future, this should validate the hook before it
485 # accepts it. Probably at least check that the hook takes the number
505 # accepts it. Probably at least check that the hook takes the number
486 # of args it's supposed to.
506 # of args it's supposed to.
487
507
488 f = new.instancemethod(hook,self,self.__class__)
508 f = new.instancemethod(hook,self,self.__class__)
489
509
490 # check if the hook is for strdispatcher first
510 # check if the hook is for strdispatcher first
491 if str_key is not None:
511 if str_key is not None:
492 sdp = self.strdispatchers.get(name, StrDispatch())
512 sdp = self.strdispatchers.get(name, StrDispatch())
493 sdp.add_s(str_key, f, priority )
513 sdp.add_s(str_key, f, priority )
494 self.strdispatchers[name] = sdp
514 self.strdispatchers[name] = sdp
495 return
515 return
496 if re_key is not None:
516 if re_key is not None:
497 sdp = self.strdispatchers.get(name, StrDispatch())
517 sdp = self.strdispatchers.get(name, StrDispatch())
498 sdp.add_re(re.compile(re_key), f, priority )
518 sdp.add_re(re.compile(re_key), f, priority )
499 self.strdispatchers[name] = sdp
519 self.strdispatchers[name] = sdp
500 return
520 return
501
521
502 dp = getattr(self.hooks, name, None)
522 dp = getattr(self.hooks, name, None)
503 if name not in IPython.core.hooks.__all__:
523 if name not in IPython.core.hooks.__all__:
504 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
524 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
505 if not dp:
525 if not dp:
506 dp = IPython.core.hooks.CommandChainDispatcher()
526 dp = IPython.core.hooks.CommandChainDispatcher()
507
527
508 try:
528 try:
509 dp.add(f,priority)
529 dp.add(f,priority)
510 except AttributeError:
530 except AttributeError:
511 # it was not commandchain, plain old func - replace
531 # it was not commandchain, plain old func - replace
512 dp = f
532 dp = f
513
533
514 setattr(self.hooks,name, dp)
534 setattr(self.hooks,name, dp)
515
535
516 #-------------------------------------------------------------------------
536 #-------------------------------------------------------------------------
517 # Things related to the "main" module
537 # Things related to the "main" module
518 #-------------------------------------------------------------------------
538 #-------------------------------------------------------------------------
519
539
520 def new_main_mod(self,ns=None):
540 def new_main_mod(self,ns=None):
521 """Return a new 'main' module object for user code execution.
541 """Return a new 'main' module object for user code execution.
522 """
542 """
523 main_mod = self._user_main_module
543 main_mod = self._user_main_module
524 init_fakemod_dict(main_mod,ns)
544 init_fakemod_dict(main_mod,ns)
525 return main_mod
545 return main_mod
526
546
527 def cache_main_mod(self,ns,fname):
547 def cache_main_mod(self,ns,fname):
528 """Cache a main module's namespace.
548 """Cache a main module's namespace.
529
549
530 When scripts are executed via %run, we must keep a reference to the
550 When scripts are executed via %run, we must keep a reference to the
531 namespace of their __main__ module (a FakeModule instance) around so
551 namespace of their __main__ module (a FakeModule instance) around so
532 that Python doesn't clear it, rendering objects defined therein
552 that Python doesn't clear it, rendering objects defined therein
533 useless.
553 useless.
534
554
535 This method keeps said reference in a private dict, keyed by the
555 This method keeps said reference in a private dict, keyed by the
536 absolute path of the module object (which corresponds to the script
556 absolute path of the module object (which corresponds to the script
537 path). This way, for multiple executions of the same script we only
557 path). This way, for multiple executions of the same script we only
538 keep one copy of the namespace (the last one), thus preventing memory
558 keep one copy of the namespace (the last one), thus preventing memory
539 leaks from old references while allowing the objects from the last
559 leaks from old references while allowing the objects from the last
540 execution to be accessible.
560 execution to be accessible.
541
561
542 Note: we can not allow the actual FakeModule instances to be deleted,
562 Note: we can not allow the actual FakeModule instances to be deleted,
543 because of how Python tears down modules (it hard-sets all their
563 because of how Python tears down modules (it hard-sets all their
544 references to None without regard for reference counts). This method
564 references to None without regard for reference counts). This method
545 must therefore make a *copy* of the given namespace, to allow the
565 must therefore make a *copy* of the given namespace, to allow the
546 original module's __dict__ to be cleared and reused.
566 original module's __dict__ to be cleared and reused.
547
567
548
568
549 Parameters
569 Parameters
550 ----------
570 ----------
551 ns : a namespace (a dict, typically)
571 ns : a namespace (a dict, typically)
552
572
553 fname : str
573 fname : str
554 Filename associated with the namespace.
574 Filename associated with the namespace.
555
575
556 Examples
576 Examples
557 --------
577 --------
558
578
559 In [10]: import IPython
579 In [10]: import IPython
560
580
561 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
581 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
562
582
563 In [12]: IPython.__file__ in _ip._main_ns_cache
583 In [12]: IPython.__file__ in _ip._main_ns_cache
564 Out[12]: True
584 Out[12]: True
565 """
585 """
566 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
586 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
567
587
568 def clear_main_mod_cache(self):
588 def clear_main_mod_cache(self):
569 """Clear the cache of main modules.
589 """Clear the cache of main modules.
570
590
571 Mainly for use by utilities like %reset.
591 Mainly for use by utilities like %reset.
572
592
573 Examples
593 Examples
574 --------
594 --------
575
595
576 In [15]: import IPython
596 In [15]: import IPython
577
597
578 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
598 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
579
599
580 In [17]: len(_ip._main_ns_cache) > 0
600 In [17]: len(_ip._main_ns_cache) > 0
581 Out[17]: True
601 Out[17]: True
582
602
583 In [18]: _ip.clear_main_mod_cache()
603 In [18]: _ip.clear_main_mod_cache()
584
604
585 In [19]: len(_ip._main_ns_cache) == 0
605 In [19]: len(_ip._main_ns_cache) == 0
586 Out[19]: True
606 Out[19]: True
587 """
607 """
588 self._main_ns_cache.clear()
608 self._main_ns_cache.clear()
589
609
590 #-------------------------------------------------------------------------
610 #-------------------------------------------------------------------------
591 # Things related to debugging
611 # Things related to debugging
592 #-------------------------------------------------------------------------
612 #-------------------------------------------------------------------------
593
613
594 def init_pdb(self):
614 def init_pdb(self):
595 # Set calling of pdb on exceptions
615 # Set calling of pdb on exceptions
596 # self.call_pdb is a property
616 # self.call_pdb is a property
597 self.call_pdb = self.pdb
617 self.call_pdb = self.pdb
598
618
599 def _get_call_pdb(self):
619 def _get_call_pdb(self):
600 return self._call_pdb
620 return self._call_pdb
601
621
602 def _set_call_pdb(self,val):
622 def _set_call_pdb(self,val):
603
623
604 if val not in (0,1,False,True):
624 if val not in (0,1,False,True):
605 raise ValueError,'new call_pdb value must be boolean'
625 raise ValueError,'new call_pdb value must be boolean'
606
626
607 # store value in instance
627 # store value in instance
608 self._call_pdb = val
628 self._call_pdb = val
609
629
610 # notify the actual exception handlers
630 # notify the actual exception handlers
611 self.InteractiveTB.call_pdb = val
631 self.InteractiveTB.call_pdb = val
612
632
613 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
633 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
614 'Control auto-activation of pdb at exceptions')
634 'Control auto-activation of pdb at exceptions')
615
635
616 def debugger(self,force=False):
636 def debugger(self,force=False):
617 """Call the pydb/pdb debugger.
637 """Call the pydb/pdb debugger.
618
638
619 Keywords:
639 Keywords:
620
640
621 - force(False): by default, this routine checks the instance call_pdb
641 - force(False): by default, this routine checks the instance call_pdb
622 flag and does not actually invoke the debugger if the flag is false.
642 flag and does not actually invoke the debugger if the flag is false.
623 The 'force' option forces the debugger to activate even if the flag
643 The 'force' option forces the debugger to activate even if the flag
624 is false.
644 is false.
625 """
645 """
626
646
627 if not (force or self.call_pdb):
647 if not (force or self.call_pdb):
628 return
648 return
629
649
630 if not hasattr(sys,'last_traceback'):
650 if not hasattr(sys,'last_traceback'):
631 error('No traceback has been produced, nothing to debug.')
651 error('No traceback has been produced, nothing to debug.')
632 return
652 return
633
653
634 # use pydb if available
654 # use pydb if available
635 if debugger.has_pydb:
655 if debugger.has_pydb:
636 from pydb import pm
656 from pydb import pm
637 else:
657 else:
638 # fallback to our internal debugger
658 # fallback to our internal debugger
639 pm = lambda : self.InteractiveTB.debugger(force=True)
659 pm = lambda : self.InteractiveTB.debugger(force=True)
640 self.history_saving_wrapper(pm)()
660 self.history_saving_wrapper(pm)()
641
661
642 #-------------------------------------------------------------------------
662 #-------------------------------------------------------------------------
643 # Things related to IPython's various namespaces
663 # Things related to IPython's various namespaces
644 #-------------------------------------------------------------------------
664 #-------------------------------------------------------------------------
645
665
646 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
666 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
647 # Create the namespace where the user will operate. user_ns is
667 # Create the namespace where the user will operate. user_ns is
648 # normally the only one used, and it is passed to the exec calls as
668 # normally the only one used, and it is passed to the exec calls as
649 # the locals argument. But we do carry a user_global_ns namespace
669 # the locals argument. But we do carry a user_global_ns namespace
650 # given as the exec 'globals' argument, This is useful in embedding
670 # given as the exec 'globals' argument, This is useful in embedding
651 # situations where the ipython shell opens in a context where the
671 # situations where the ipython shell opens in a context where the
652 # distinction between locals and globals is meaningful. For
672 # distinction between locals and globals is meaningful. For
653 # non-embedded contexts, it is just the same object as the user_ns dict.
673 # non-embedded contexts, it is just the same object as the user_ns dict.
654
674
655 # FIXME. For some strange reason, __builtins__ is showing up at user
675 # FIXME. For some strange reason, __builtins__ is showing up at user
656 # level as a dict instead of a module. This is a manual fix, but I
676 # level as a dict instead of a module. This is a manual fix, but I
657 # should really track down where the problem is coming from. Alex
677 # should really track down where the problem is coming from. Alex
658 # Schmolck reported this problem first.
678 # Schmolck reported this problem first.
659
679
660 # A useful post by Alex Martelli on this topic:
680 # A useful post by Alex Martelli on this topic:
661 # Re: inconsistent value from __builtins__
681 # Re: inconsistent value from __builtins__
662 # Von: Alex Martelli <aleaxit@yahoo.com>
682 # Von: Alex Martelli <aleaxit@yahoo.com>
663 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
683 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
664 # Gruppen: comp.lang.python
684 # Gruppen: comp.lang.python
665
685
666 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
686 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
667 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
687 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
668 # > <type 'dict'>
688 # > <type 'dict'>
669 # > >>> print type(__builtins__)
689 # > >>> print type(__builtins__)
670 # > <type 'module'>
690 # > <type 'module'>
671 # > Is this difference in return value intentional?
691 # > Is this difference in return value intentional?
672
692
673 # Well, it's documented that '__builtins__' can be either a dictionary
693 # Well, it's documented that '__builtins__' can be either a dictionary
674 # or a module, and it's been that way for a long time. Whether it's
694 # or a module, and it's been that way for a long time. Whether it's
675 # intentional (or sensible), I don't know. In any case, the idea is
695 # intentional (or sensible), I don't know. In any case, the idea is
676 # that if you need to access the built-in namespace directly, you
696 # that if you need to access the built-in namespace directly, you
677 # should start with "import __builtin__" (note, no 's') which will
697 # should start with "import __builtin__" (note, no 's') which will
678 # definitely give you a module. Yeah, it's somewhat confusing:-(.
698 # definitely give you a module. Yeah, it's somewhat confusing:-(.
679
699
680 # These routines return properly built dicts as needed by the rest of
700 # These routines return properly built dicts as needed by the rest of
681 # the code, and can also be used by extension writers to generate
701 # the code, and can also be used by extension writers to generate
682 # properly initialized namespaces.
702 # properly initialized namespaces.
683 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
703 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
684
704
685 # Assign namespaces
705 # Assign namespaces
686 # This is the namespace where all normal user variables live
706 # This is the namespace where all normal user variables live
687 self.user_ns = user_ns
707 self.user_ns = user_ns
688 self.user_global_ns = user_global_ns
708 self.user_global_ns = user_global_ns
689
709
690 # An auxiliary namespace that checks what parts of the user_ns were
710 # An auxiliary namespace that checks what parts of the user_ns were
691 # loaded at startup, so we can list later only variables defined in
711 # loaded at startup, so we can list later only variables defined in
692 # actual interactive use. Since it is always a subset of user_ns, it
712 # actual interactive use. Since it is always a subset of user_ns, it
693 # doesn't need to be separately tracked in the ns_table.
713 # doesn't need to be separately tracked in the ns_table.
694 self.user_ns_hidden = {}
714 self.user_ns_hidden = {}
695
715
696 # A namespace to keep track of internal data structures to prevent
716 # A namespace to keep track of internal data structures to prevent
697 # them from cluttering user-visible stuff. Will be updated later
717 # them from cluttering user-visible stuff. Will be updated later
698 self.internal_ns = {}
718 self.internal_ns = {}
699
719
700 # Now that FakeModule produces a real module, we've run into a nasty
720 # Now that FakeModule produces a real module, we've run into a nasty
701 # problem: after script execution (via %run), the module where the user
721 # problem: after script execution (via %run), the module where the user
702 # code ran is deleted. Now that this object is a true module (needed
722 # code ran is deleted. Now that this object is a true module (needed
703 # so docetst and other tools work correctly), the Python module
723 # so docetst and other tools work correctly), the Python module
704 # teardown mechanism runs over it, and sets to None every variable
724 # teardown mechanism runs over it, and sets to None every variable
705 # present in that module. Top-level references to objects from the
725 # present in that module. Top-level references to objects from the
706 # script survive, because the user_ns is updated with them. However,
726 # script survive, because the user_ns is updated with them. However,
707 # calling functions defined in the script that use other things from
727 # calling functions defined in the script that use other things from
708 # the script will fail, because the function's closure had references
728 # the script will fail, because the function's closure had references
709 # to the original objects, which are now all None. So we must protect
729 # to the original objects, which are now all None. So we must protect
710 # these modules from deletion by keeping a cache.
730 # these modules from deletion by keeping a cache.
711 #
731 #
712 # To avoid keeping stale modules around (we only need the one from the
732 # To avoid keeping stale modules around (we only need the one from the
713 # last run), we use a dict keyed with the full path to the script, so
733 # last run), we use a dict keyed with the full path to the script, so
714 # only the last version of the module is held in the cache. Note,
734 # only the last version of the module is held in the cache. Note,
715 # however, that we must cache the module *namespace contents* (their
735 # however, that we must cache the module *namespace contents* (their
716 # __dict__). Because if we try to cache the actual modules, old ones
736 # __dict__). Because if we try to cache the actual modules, old ones
717 # (uncached) could be destroyed while still holding references (such as
737 # (uncached) could be destroyed while still holding references (such as
718 # those held by GUI objects that tend to be long-lived)>
738 # those held by GUI objects that tend to be long-lived)>
719 #
739 #
720 # The %reset command will flush this cache. See the cache_main_mod()
740 # The %reset command will flush this cache. See the cache_main_mod()
721 # and clear_main_mod_cache() methods for details on use.
741 # and clear_main_mod_cache() methods for details on use.
722
742
723 # This is the cache used for 'main' namespaces
743 # This is the cache used for 'main' namespaces
724 self._main_ns_cache = {}
744 self._main_ns_cache = {}
725 # And this is the single instance of FakeModule whose __dict__ we keep
745 # And this is the single instance of FakeModule whose __dict__ we keep
726 # copying and clearing for reuse on each %run
746 # copying and clearing for reuse on each %run
727 self._user_main_module = FakeModule()
747 self._user_main_module = FakeModule()
728
748
729 # A table holding all the namespaces IPython deals with, so that
749 # A table holding all the namespaces IPython deals with, so that
730 # introspection facilities can search easily.
750 # introspection facilities can search easily.
731 self.ns_table = {'user':user_ns,
751 self.ns_table = {'user':user_ns,
732 'user_global':user_global_ns,
752 'user_global':user_global_ns,
733 'internal':self.internal_ns,
753 'internal':self.internal_ns,
734 'builtin':__builtin__.__dict__
754 'builtin':__builtin__.__dict__
735 }
755 }
736
756
737 # Similarly, track all namespaces where references can be held and that
757 # Similarly, track all namespaces where references can be held and that
738 # we can safely clear (so it can NOT include builtin). This one can be
758 # we can safely clear (so it can NOT include builtin). This one can be
739 # a simple list.
759 # a simple list.
740 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
760 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
741 self.internal_ns, self._main_ns_cache ]
761 self.internal_ns, self._main_ns_cache ]
742
762
743 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
763 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
744 """Return a valid local and global user interactive namespaces.
764 """Return a valid local and global user interactive namespaces.
745
765
746 This builds a dict with the minimal information needed to operate as a
766 This builds a dict with the minimal information needed to operate as a
747 valid IPython user namespace, which you can pass to the various
767 valid IPython user namespace, which you can pass to the various
748 embedding classes in ipython. The default implementation returns the
768 embedding classes in ipython. The default implementation returns the
749 same dict for both the locals and the globals to allow functions to
769 same dict for both the locals and the globals to allow functions to
750 refer to variables in the namespace. Customized implementations can
770 refer to variables in the namespace. Customized implementations can
751 return different dicts. The locals dictionary can actually be anything
771 return different dicts. The locals dictionary can actually be anything
752 following the basic mapping protocol of a dict, but the globals dict
772 following the basic mapping protocol of a dict, but the globals dict
753 must be a true dict, not even a subclass. It is recommended that any
773 must be a true dict, not even a subclass. It is recommended that any
754 custom object for the locals namespace synchronize with the globals
774 custom object for the locals namespace synchronize with the globals
755 dict somehow.
775 dict somehow.
756
776
757 Raises TypeError if the provided globals namespace is not a true dict.
777 Raises TypeError if the provided globals namespace is not a true dict.
758
778
759 Parameters
779 Parameters
760 ----------
780 ----------
761 user_ns : dict-like, optional
781 user_ns : dict-like, optional
762 The current user namespace. The items in this namespace should
782 The current user namespace. The items in this namespace should
763 be included in the output. If None, an appropriate blank
783 be included in the output. If None, an appropriate blank
764 namespace should be created.
784 namespace should be created.
765 user_global_ns : dict, optional
785 user_global_ns : dict, optional
766 The current user global namespace. The items in this namespace
786 The current user global namespace. The items in this namespace
767 should be included in the output. If None, an appropriate
787 should be included in the output. If None, an appropriate
768 blank namespace should be created.
788 blank namespace should be created.
769
789
770 Returns
790 Returns
771 -------
791 -------
772 A pair of dictionary-like object to be used as the local namespace
792 A pair of dictionary-like object to be used as the local namespace
773 of the interpreter and a dict to be used as the global namespace.
793 of the interpreter and a dict to be used as the global namespace.
774 """
794 """
775
795
776
796
777 # We must ensure that __builtin__ (without the final 's') is always
797 # We must ensure that __builtin__ (without the final 's') is always
778 # available and pointing to the __builtin__ *module*. For more details:
798 # available and pointing to the __builtin__ *module*. For more details:
779 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
799 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
780
800
781 if user_ns is None:
801 if user_ns is None:
782 # Set __name__ to __main__ to better match the behavior of the
802 # Set __name__ to __main__ to better match the behavior of the
783 # normal interpreter.
803 # normal interpreter.
784 user_ns = {'__name__' :'__main__',
804 user_ns = {'__name__' :'__main__',
785 '__builtin__' : __builtin__,
805 '__builtin__' : __builtin__,
786 '__builtins__' : __builtin__,
806 '__builtins__' : __builtin__,
787 }
807 }
788 else:
808 else:
789 user_ns.setdefault('__name__','__main__')
809 user_ns.setdefault('__name__','__main__')
790 user_ns.setdefault('__builtin__',__builtin__)
810 user_ns.setdefault('__builtin__',__builtin__)
791 user_ns.setdefault('__builtins__',__builtin__)
811 user_ns.setdefault('__builtins__',__builtin__)
792
812
793 if user_global_ns is None:
813 if user_global_ns is None:
794 user_global_ns = user_ns
814 user_global_ns = user_ns
795 if type(user_global_ns) is not dict:
815 if type(user_global_ns) is not dict:
796 raise TypeError("user_global_ns must be a true dict; got %r"
816 raise TypeError("user_global_ns must be a true dict; got %r"
797 % type(user_global_ns))
817 % type(user_global_ns))
798
818
799 return user_ns, user_global_ns
819 return user_ns, user_global_ns
800
820
801 def init_sys_modules(self):
821 def init_sys_modules(self):
802 # We need to insert into sys.modules something that looks like a
822 # We need to insert into sys.modules something that looks like a
803 # module but which accesses the IPython namespace, for shelve and
823 # module but which accesses the IPython namespace, for shelve and
804 # pickle to work interactively. Normally they rely on getting
824 # pickle to work interactively. Normally they rely on getting
805 # everything out of __main__, but for embedding purposes each IPython
825 # everything out of __main__, but for embedding purposes each IPython
806 # instance has its own private namespace, so we can't go shoving
826 # instance has its own private namespace, so we can't go shoving
807 # everything into __main__.
827 # everything into __main__.
808
828
809 # note, however, that we should only do this for non-embedded
829 # note, however, that we should only do this for non-embedded
810 # ipythons, which really mimic the __main__.__dict__ with their own
830 # ipythons, which really mimic the __main__.__dict__ with their own
811 # namespace. Embedded instances, on the other hand, should not do
831 # namespace. Embedded instances, on the other hand, should not do
812 # this because they need to manage the user local/global namespaces
832 # this because they need to manage the user local/global namespaces
813 # only, but they live within a 'normal' __main__ (meaning, they
833 # only, but they live within a 'normal' __main__ (meaning, they
814 # shouldn't overtake the execution environment of the script they're
834 # shouldn't overtake the execution environment of the script they're
815 # embedded in).
835 # embedded in).
816
836
817 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
837 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
818
838
819 try:
839 try:
820 main_name = self.user_ns['__name__']
840 main_name = self.user_ns['__name__']
821 except KeyError:
841 except KeyError:
822 raise KeyError('user_ns dictionary MUST have a "__name__" key')
842 raise KeyError('user_ns dictionary MUST have a "__name__" key')
823 else:
843 else:
824 sys.modules[main_name] = FakeModule(self.user_ns)
844 sys.modules[main_name] = FakeModule(self.user_ns)
825
845
826 def init_user_ns(self):
846 def init_user_ns(self):
827 """Initialize all user-visible namespaces to their minimum defaults.
847 """Initialize all user-visible namespaces to their minimum defaults.
828
848
829 Certain history lists are also initialized here, as they effectively
849 Certain history lists are also initialized here, as they effectively
830 act as user namespaces.
850 act as user namespaces.
831
851
832 Notes
852 Notes
833 -----
853 -----
834 All data structures here are only filled in, they are NOT reset by this
854 All data structures here are only filled in, they are NOT reset by this
835 method. If they were not empty before, data will simply be added to
855 method. If they were not empty before, data will simply be added to
836 therm.
856 therm.
837 """
857 """
838 # This function works in two parts: first we put a few things in
858 # This function works in two parts: first we put a few things in
839 # user_ns, and we sync that contents into user_ns_hidden so that these
859 # user_ns, and we sync that contents into user_ns_hidden so that these
840 # initial variables aren't shown by %who. After the sync, we add the
860 # initial variables aren't shown by %who. After the sync, we add the
841 # rest of what we *do* want the user to see with %who even on a new
861 # rest of what we *do* want the user to see with %who even on a new
842 # session (probably nothing, so theye really only see their own stuff)
862 # session (probably nothing, so theye really only see their own stuff)
843
863
844 # The user dict must *always* have a __builtin__ reference to the
864 # The user dict must *always* have a __builtin__ reference to the
845 # Python standard __builtin__ namespace, which must be imported.
865 # Python standard __builtin__ namespace, which must be imported.
846 # This is so that certain operations in prompt evaluation can be
866 # This is so that certain operations in prompt evaluation can be
847 # reliably executed with builtins. Note that we can NOT use
867 # reliably executed with builtins. Note that we can NOT use
848 # __builtins__ (note the 's'), because that can either be a dict or a
868 # __builtins__ (note the 's'), because that can either be a dict or a
849 # module, and can even mutate at runtime, depending on the context
869 # module, and can even mutate at runtime, depending on the context
850 # (Python makes no guarantees on it). In contrast, __builtin__ is
870 # (Python makes no guarantees on it). In contrast, __builtin__ is
851 # always a module object, though it must be explicitly imported.
871 # always a module object, though it must be explicitly imported.
852
872
853 # For more details:
873 # For more details:
854 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
874 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
855 ns = dict(__builtin__ = __builtin__)
875 ns = dict(__builtin__ = __builtin__)
856
876
857 # Put 'help' in the user namespace
877 # Put 'help' in the user namespace
858 try:
878 try:
859 from site import _Helper
879 from site import _Helper
860 ns['help'] = _Helper()
880 ns['help'] = _Helper()
861 except ImportError:
881 except ImportError:
862 warn('help() not available - check site.py')
882 warn('help() not available - check site.py')
863
883
864 # make global variables for user access to the histories
884 # make global variables for user access to the histories
865 ns['_ih'] = self.input_hist
885 ns['_ih'] = self.input_hist
866 ns['_oh'] = self.output_hist
886 ns['_oh'] = self.output_hist
867 ns['_dh'] = self.dir_hist
887 ns['_dh'] = self.dir_hist
868
888
869 ns['_sh'] = shadowns
889 ns['_sh'] = shadowns
870
890
871 # user aliases to input and output histories. These shouldn't show up
891 # user aliases to input and output histories. These shouldn't show up
872 # in %who, as they can have very large reprs.
892 # in %who, as they can have very large reprs.
873 ns['In'] = self.input_hist
893 ns['In'] = self.input_hist
874 ns['Out'] = self.output_hist
894 ns['Out'] = self.output_hist
875
895
876 # Store myself as the public api!!!
896 # Store myself as the public api!!!
877 ns['get_ipython'] = self.get_ipython
897 ns['get_ipython'] = self.get_ipython
878
898
879 # Sync what we've added so far to user_ns_hidden so these aren't seen
899 # Sync what we've added so far to user_ns_hidden so these aren't seen
880 # by %who
900 # by %who
881 self.user_ns_hidden.update(ns)
901 self.user_ns_hidden.update(ns)
882
902
883 # Anything put into ns now would show up in %who. Think twice before
903 # Anything put into ns now would show up in %who. Think twice before
884 # putting anything here, as we really want %who to show the user their
904 # putting anything here, as we really want %who to show the user their
885 # stuff, not our variables.
905 # stuff, not our variables.
886
906
887 # Finally, update the real user's namespace
907 # Finally, update the real user's namespace
888 self.user_ns.update(ns)
908 self.user_ns.update(ns)
889
909
890
910
891 def reset(self):
911 def reset(self):
892 """Clear all internal namespaces.
912 """Clear all internal namespaces.
893
913
894 Note that this is much more aggressive than %reset, since it clears
914 Note that this is much more aggressive than %reset, since it clears
895 fully all namespaces, as well as all input/output lists.
915 fully all namespaces, as well as all input/output lists.
896 """
916 """
897 for ns in self.ns_refs_table:
917 for ns in self.ns_refs_table:
898 ns.clear()
918 ns.clear()
899
919
900 self.alias_manager.clear_aliases()
920 self.alias_manager.clear_aliases()
901
921
902 # Clear input and output histories
922 # Clear input and output histories
903 self.input_hist[:] = []
923 self.input_hist[:] = []
904 self.input_hist_raw[:] = []
924 self.input_hist_raw[:] = []
905 self.output_hist.clear()
925 self.output_hist.clear()
906
926
907 # Restore the user namespaces to minimal usability
927 # Restore the user namespaces to minimal usability
908 self.init_user_ns()
928 self.init_user_ns()
909
929
910 # Restore the default and user aliases
930 # Restore the default and user aliases
911 self.alias_manager.init_aliases()
931 self.alias_manager.init_aliases()
912
932
913 def reset_selective(self, regex=None):
933 def reset_selective(self, regex=None):
914 """Clear selective variables from internal namespaces based on a specified regular expression.
934 """Clear selective variables from internal namespaces based on a specified regular expression.
915
935
916 Parameters
936 Parameters
917 ----------
937 ----------
918 regex : string or compiled pattern, optional
938 regex : string or compiled pattern, optional
919 A regular expression pattern that will be used in searching variable names in the users
939 A regular expression pattern that will be used in searching variable names in the users
920 namespaces.
940 namespaces.
921 """
941 """
922 if regex is not None:
942 if regex is not None:
923 try:
943 try:
924 m = re.compile(regex)
944 m = re.compile(regex)
925 except TypeError:
945 except TypeError:
926 raise TypeError('regex must be a string or compiled pattern')
946 raise TypeError('regex must be a string or compiled pattern')
927 # Search for keys in each namespace that match the given regex
947 # Search for keys in each namespace that match the given regex
928 # If a match is found, delete the key/value pair.
948 # If a match is found, delete the key/value pair.
929 for ns in self.ns_refs_table:
949 for ns in self.ns_refs_table:
930 for var in ns:
950 for var in ns:
931 if m.search(var):
951 if m.search(var):
932 del ns[var]
952 del ns[var]
933
953
934 def push(self, variables, interactive=True):
954 def push(self, variables, interactive=True):
935 """Inject a group of variables into the IPython user namespace.
955 """Inject a group of variables into the IPython user namespace.
936
956
937 Parameters
957 Parameters
938 ----------
958 ----------
939 variables : dict, str or list/tuple of str
959 variables : dict, str or list/tuple of str
940 The variables to inject into the user's namespace. If a dict,
960 The variables to inject into the user's namespace. If a dict,
941 a simple update is done. If a str, the string is assumed to
961 a simple update is done. If a str, the string is assumed to
942 have variable names separated by spaces. A list/tuple of str
962 have variable names separated by spaces. A list/tuple of str
943 can also be used to give the variable names. If just the variable
963 can also be used to give the variable names. If just the variable
944 names are give (list/tuple/str) then the variable values looked
964 names are give (list/tuple/str) then the variable values looked
945 up in the callers frame.
965 up in the callers frame.
946 interactive : bool
966 interactive : bool
947 If True (default), the variables will be listed with the ``who``
967 If True (default), the variables will be listed with the ``who``
948 magic.
968 magic.
949 """
969 """
950 vdict = None
970 vdict = None
951
971
952 # We need a dict of name/value pairs to do namespace updates.
972 # We need a dict of name/value pairs to do namespace updates.
953 if isinstance(variables, dict):
973 if isinstance(variables, dict):
954 vdict = variables
974 vdict = variables
955 elif isinstance(variables, (basestring, list, tuple)):
975 elif isinstance(variables, (basestring, list, tuple)):
956 if isinstance(variables, basestring):
976 if isinstance(variables, basestring):
957 vlist = variables.split()
977 vlist = variables.split()
958 else:
978 else:
959 vlist = variables
979 vlist = variables
960 vdict = {}
980 vdict = {}
961 cf = sys._getframe(1)
981 cf = sys._getframe(1)
962 for name in vlist:
982 for name in vlist:
963 try:
983 try:
964 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
984 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
965 except:
985 except:
966 print ('Could not get variable %s from %s' %
986 print ('Could not get variable %s from %s' %
967 (name,cf.f_code.co_name))
987 (name,cf.f_code.co_name))
968 else:
988 else:
969 raise ValueError('variables must be a dict/str/list/tuple')
989 raise ValueError('variables must be a dict/str/list/tuple')
970
990
971 # Propagate variables to user namespace
991 # Propagate variables to user namespace
972 self.user_ns.update(vdict)
992 self.user_ns.update(vdict)
973
993
974 # And configure interactive visibility
994 # And configure interactive visibility
975 config_ns = self.user_ns_hidden
995 config_ns = self.user_ns_hidden
976 if interactive:
996 if interactive:
977 for name, val in vdict.iteritems():
997 for name, val in vdict.iteritems():
978 config_ns.pop(name, None)
998 config_ns.pop(name, None)
979 else:
999 else:
980 for name,val in vdict.iteritems():
1000 for name,val in vdict.iteritems():
981 config_ns[name] = val
1001 config_ns[name] = val
982
1002
983 #-------------------------------------------------------------------------
1003 #-------------------------------------------------------------------------
984 # Things related to history management
1004 # Things related to history management
985 #-------------------------------------------------------------------------
1005 #-------------------------------------------------------------------------
986
1006
987 def init_history(self):
1007 def init_history(self):
988 # List of input with multi-line handling.
1008 # List of input with multi-line handling.
989 self.input_hist = InputList()
1009 self.input_hist = InputList()
990 # This one will hold the 'raw' input history, without any
1010 # This one will hold the 'raw' input history, without any
991 # pre-processing. This will allow users to retrieve the input just as
1011 # pre-processing. This will allow users to retrieve the input just as
992 # it was exactly typed in by the user, with %hist -r.
1012 # it was exactly typed in by the user, with %hist -r.
993 self.input_hist_raw = InputList()
1013 self.input_hist_raw = InputList()
994
1014
995 # list of visited directories
1015 # list of visited directories
996 try:
1016 try:
997 self.dir_hist = [os.getcwd()]
1017 self.dir_hist = [os.getcwd()]
998 except OSError:
1018 except OSError:
999 self.dir_hist = []
1019 self.dir_hist = []
1000
1020
1001 # dict of output history
1021 # dict of output history
1002 self.output_hist = {}
1022 self.output_hist = {}
1003
1023
1004 # Now the history file
1024 # Now the history file
1005 if self.profile:
1025 if self.profile:
1006 histfname = 'history-%s' % self.profile
1026 histfname = 'history-%s' % self.profile
1007 else:
1027 else:
1008 histfname = 'history'
1028 histfname = 'history'
1009 self.histfile = os.path.join(self.ipython_dir, histfname)
1029 self.histfile = os.path.join(self.ipython_dir, histfname)
1010
1030
1011 # Fill the history zero entry, user counter starts at 1
1031 # Fill the history zero entry, user counter starts at 1
1012 self.input_hist.append('\n')
1032 self.input_hist.append('\n')
1013 self.input_hist_raw.append('\n')
1033 self.input_hist_raw.append('\n')
1014
1034
1015 def init_shadow_hist(self):
1035 def init_shadow_hist(self):
1016 try:
1036 try:
1017 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1037 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1018 except exceptions.UnicodeDecodeError:
1038 except exceptions.UnicodeDecodeError:
1019 print "Your ipython_dir can't be decoded to unicode!"
1039 print "Your ipython_dir can't be decoded to unicode!"
1020 print "Please set HOME environment variable to something that"
1040 print "Please set HOME environment variable to something that"
1021 print r"only has ASCII characters, e.g. c:\home"
1041 print r"only has ASCII characters, e.g. c:\home"
1022 print "Now it is", self.ipython_dir
1042 print "Now it is", self.ipython_dir
1023 sys.exit()
1043 sys.exit()
1024 self.shadowhist = ipcorehist.ShadowHist(self.db)
1044 self.shadowhist = ipcorehist.ShadowHist(self.db)
1025
1045
1026 def savehist(self):
1046 def savehist(self):
1027 """Save input history to a file (via readline library)."""
1047 """Save input history to a file (via readline library)."""
1028
1048
1029 try:
1049 try:
1030 self.readline.write_history_file(self.histfile)
1050 self.readline.write_history_file(self.histfile)
1031 except:
1051 except:
1032 print 'Unable to save IPython command history to file: ' + \
1052 print 'Unable to save IPython command history to file: ' + \
1033 `self.histfile`
1053 `self.histfile`
1034
1054
1035 def reloadhist(self):
1055 def reloadhist(self):
1036 """Reload the input history from disk file."""
1056 """Reload the input history from disk file."""
1037
1057
1038 try:
1058 try:
1039 self.readline.clear_history()
1059 self.readline.clear_history()
1040 self.readline.read_history_file(self.shell.histfile)
1060 self.readline.read_history_file(self.shell.histfile)
1041 except AttributeError:
1061 except AttributeError:
1042 pass
1062 pass
1043
1063
1044 def history_saving_wrapper(self, func):
1064 def history_saving_wrapper(self, func):
1045 """ Wrap func for readline history saving
1065 """ Wrap func for readline history saving
1046
1066
1047 Convert func into callable that saves & restores
1067 Convert func into callable that saves & restores
1048 history around the call """
1068 history around the call """
1049
1069
1050 if self.has_readline:
1070 if self.has_readline:
1051 from IPython.utils import rlineimpl as readline
1071 from IPython.utils import rlineimpl as readline
1052 else:
1072 else:
1053 return func
1073 return func
1054
1074
1055 def wrapper():
1075 def wrapper():
1056 self.savehist()
1076 self.savehist()
1057 try:
1077 try:
1058 func()
1078 func()
1059 finally:
1079 finally:
1060 readline.read_history_file(self.histfile)
1080 readline.read_history_file(self.histfile)
1061 return wrapper
1081 return wrapper
1062
1082
1063 #-------------------------------------------------------------------------
1083 #-------------------------------------------------------------------------
1064 # Things related to exception handling and tracebacks (not debugging)
1084 # Things related to exception handling and tracebacks (not debugging)
1065 #-------------------------------------------------------------------------
1085 #-------------------------------------------------------------------------
1066
1086
1067 def init_traceback_handlers(self, custom_exceptions):
1087 def init_traceback_handlers(self, custom_exceptions):
1068 # Syntax error handler.
1088 # Syntax error handler.
1069 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1089 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1070
1090
1071 # The interactive one is initialized with an offset, meaning we always
1091 # The interactive one is initialized with an offset, meaning we always
1072 # want to remove the topmost item in the traceback, which is our own
1092 # want to remove the topmost item in the traceback, which is our own
1073 # internal code. Valid modes: ['Plain','Context','Verbose']
1093 # internal code. Valid modes: ['Plain','Context','Verbose']
1074 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1094 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1075 color_scheme='NoColor',
1095 color_scheme='NoColor',
1076 tb_offset = 1)
1096 tb_offset = 1)
1077
1097
1078 # The instance will store a pointer to the system-wide exception hook,
1098 # The instance will store a pointer to the system-wide exception hook,
1079 # so that runtime code (such as magics) can access it. This is because
1099 # so that runtime code (such as magics) can access it. This is because
1080 # during the read-eval loop, it may get temporarily overwritten.
1100 # during the read-eval loop, it may get temporarily overwritten.
1081 self.sys_excepthook = sys.excepthook
1101 self.sys_excepthook = sys.excepthook
1082
1102
1083 # and add any custom exception handlers the user may have specified
1103 # and add any custom exception handlers the user may have specified
1084 self.set_custom_exc(*custom_exceptions)
1104 self.set_custom_exc(*custom_exceptions)
1085
1105
1086 # Set the exception mode
1106 # Set the exception mode
1087 self.InteractiveTB.set_mode(mode=self.xmode)
1107 self.InteractiveTB.set_mode(mode=self.xmode)
1088
1108
1089 def set_custom_exc(self,exc_tuple,handler):
1109 def set_custom_exc(self,exc_tuple,handler):
1090 """set_custom_exc(exc_tuple,handler)
1110 """set_custom_exc(exc_tuple,handler)
1091
1111
1092 Set a custom exception handler, which will be called if any of the
1112 Set a custom exception handler, which will be called if any of the
1093 exceptions in exc_tuple occur in the mainloop (specifically, in the
1113 exceptions in exc_tuple occur in the mainloop (specifically, in the
1094 runcode() method.
1114 runcode() method.
1095
1115
1096 Inputs:
1116 Inputs:
1097
1117
1098 - exc_tuple: a *tuple* of valid exceptions to call the defined
1118 - exc_tuple: a *tuple* of valid exceptions to call the defined
1099 handler for. It is very important that you use a tuple, and NOT A
1119 handler for. It is very important that you use a tuple, and NOT A
1100 LIST here, because of the way Python's except statement works. If
1120 LIST here, because of the way Python's except statement works. If
1101 you only want to trap a single exception, use a singleton tuple:
1121 you only want to trap a single exception, use a singleton tuple:
1102
1122
1103 exc_tuple == (MyCustomException,)
1123 exc_tuple == (MyCustomException,)
1104
1124
1105 - handler: this must be defined as a function with the following
1125 - handler: this must be defined as a function with the following
1106 basic interface: def my_handler(self,etype,value,tb).
1126 basic interface: def my_handler(self,etype,value,tb).
1107
1127
1108 This will be made into an instance method (via new.instancemethod)
1128 This will be made into an instance method (via new.instancemethod)
1109 of IPython itself, and it will be called if any of the exceptions
1129 of IPython itself, and it will be called if any of the exceptions
1110 listed in the exc_tuple are caught. If the handler is None, an
1130 listed in the exc_tuple are caught. If the handler is None, an
1111 internal basic one is used, which just prints basic info.
1131 internal basic one is used, which just prints basic info.
1112
1132
1113 WARNING: by putting in your own exception handler into IPython's main
1133 WARNING: by putting in your own exception handler into IPython's main
1114 execution loop, you run a very good chance of nasty crashes. This
1134 execution loop, you run a very good chance of nasty crashes. This
1115 facility should only be used if you really know what you are doing."""
1135 facility should only be used if you really know what you are doing."""
1116
1136
1117 assert type(exc_tuple)==type(()) , \
1137 assert type(exc_tuple)==type(()) , \
1118 "The custom exceptions must be given AS A TUPLE."
1138 "The custom exceptions must be given AS A TUPLE."
1119
1139
1120 def dummy_handler(self,etype,value,tb):
1140 def dummy_handler(self,etype,value,tb):
1121 print '*** Simple custom exception handler ***'
1141 print '*** Simple custom exception handler ***'
1122 print 'Exception type :',etype
1142 print 'Exception type :',etype
1123 print 'Exception value:',value
1143 print 'Exception value:',value
1124 print 'Traceback :',tb
1144 print 'Traceback :',tb
1125 print 'Source code :','\n'.join(self.buffer)
1145 print 'Source code :','\n'.join(self.buffer)
1126
1146
1127 if handler is None: handler = dummy_handler
1147 if handler is None: handler = dummy_handler
1128
1148
1129 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1149 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1130 self.custom_exceptions = exc_tuple
1150 self.custom_exceptions = exc_tuple
1131
1151
1132 def excepthook(self, etype, value, tb):
1152 def excepthook(self, etype, value, tb):
1133 """One more defense for GUI apps that call sys.excepthook.
1153 """One more defense for GUI apps that call sys.excepthook.
1134
1154
1135 GUI frameworks like wxPython trap exceptions and call
1155 GUI frameworks like wxPython trap exceptions and call
1136 sys.excepthook themselves. I guess this is a feature that
1156 sys.excepthook themselves. I guess this is a feature that
1137 enables them to keep running after exceptions that would
1157 enables them to keep running after exceptions that would
1138 otherwise kill their mainloop. This is a bother for IPython
1158 otherwise kill their mainloop. This is a bother for IPython
1139 which excepts to catch all of the program exceptions with a try:
1159 which excepts to catch all of the program exceptions with a try:
1140 except: statement.
1160 except: statement.
1141
1161
1142 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1162 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1143 any app directly invokes sys.excepthook, it will look to the user like
1163 any app directly invokes sys.excepthook, it will look to the user like
1144 IPython crashed. In order to work around this, we can disable the
1164 IPython crashed. In order to work around this, we can disable the
1145 CrashHandler and replace it with this excepthook instead, which prints a
1165 CrashHandler and replace it with this excepthook instead, which prints a
1146 regular traceback using our InteractiveTB. In this fashion, apps which
1166 regular traceback using our InteractiveTB. In this fashion, apps which
1147 call sys.excepthook will generate a regular-looking exception from
1167 call sys.excepthook will generate a regular-looking exception from
1148 IPython, and the CrashHandler will only be triggered by real IPython
1168 IPython, and the CrashHandler will only be triggered by real IPython
1149 crashes.
1169 crashes.
1150
1170
1151 This hook should be used sparingly, only in places which are not likely
1171 This hook should be used sparingly, only in places which are not likely
1152 to be true IPython errors.
1172 to be true IPython errors.
1153 """
1173 """
1154 self.showtraceback((etype,value,tb),tb_offset=0)
1174 self.showtraceback((etype,value,tb),tb_offset=0)
1155
1175
1156 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1176 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1157 exception_only=False):
1177 exception_only=False):
1158 """Display the exception that just occurred.
1178 """Display the exception that just occurred.
1159
1179
1160 If nothing is known about the exception, this is the method which
1180 If nothing is known about the exception, this is the method which
1161 should be used throughout the code for presenting user tracebacks,
1181 should be used throughout the code for presenting user tracebacks,
1162 rather than directly invoking the InteractiveTB object.
1182 rather than directly invoking the InteractiveTB object.
1163
1183
1164 A specific showsyntaxerror() also exists, but this method can take
1184 A specific showsyntaxerror() also exists, but this method can take
1165 care of calling it if needed, so unless you are explicitly catching a
1185 care of calling it if needed, so unless you are explicitly catching a
1166 SyntaxError exception, don't try to analyze the stack manually and
1186 SyntaxError exception, don't try to analyze the stack manually and
1167 simply call this method."""
1187 simply call this method."""
1168
1188
1169 try:
1189 try:
1170 if exc_tuple is None:
1190 if exc_tuple is None:
1171 etype, value, tb = sys.exc_info()
1191 etype, value, tb = sys.exc_info()
1172 else:
1192 else:
1173 etype, value, tb = exc_tuple
1193 etype, value, tb = exc_tuple
1174
1194
1175 if etype is None:
1195 if etype is None:
1176 if hasattr(sys, 'last_type'):
1196 if hasattr(sys, 'last_type'):
1177 etype, value, tb = sys.last_type, sys.last_value, \
1197 etype, value, tb = sys.last_type, sys.last_value, \
1178 sys.last_traceback
1198 sys.last_traceback
1179 else:
1199 else:
1180 self.write('No traceback available to show.\n')
1200 self.write('No traceback available to show.\n')
1181 return
1201 return
1182
1202
1183 if etype is SyntaxError:
1203 if etype is SyntaxError:
1184 # Though this won't be called by syntax errors in the input
1204 # Though this won't be called by syntax errors in the input
1185 # line, there may be SyntaxError cases whith imported code.
1205 # line, there may be SyntaxError cases whith imported code.
1186 self.showsyntaxerror(filename)
1206 self.showsyntaxerror(filename)
1187 elif etype is UsageError:
1207 elif etype is UsageError:
1188 print "UsageError:", value
1208 print "UsageError:", value
1189 else:
1209 else:
1190 # WARNING: these variables are somewhat deprecated and not
1210 # WARNING: these variables are somewhat deprecated and not
1191 # necessarily safe to use in a threaded environment, but tools
1211 # necessarily safe to use in a threaded environment, but tools
1192 # like pdb depend on their existence, so let's set them. If we
1212 # like pdb depend on their existence, so let's set them. If we
1193 # find problems in the field, we'll need to revisit their use.
1213 # find problems in the field, we'll need to revisit their use.
1194 sys.last_type = etype
1214 sys.last_type = etype
1195 sys.last_value = value
1215 sys.last_value = value
1196 sys.last_traceback = tb
1216 sys.last_traceback = tb
1197
1217
1198 if etype in self.custom_exceptions:
1218 if etype in self.custom_exceptions:
1199 self.CustomTB(etype,value,tb)
1219 self.CustomTB(etype,value,tb)
1200 else:
1220 else:
1201 if exception_only:
1221 if exception_only:
1202 m = ('An exception has occurred, use %tb to see the '
1222 m = ('An exception has occurred, use %tb to see the '
1203 'full traceback.')
1223 'full traceback.')
1204 print m
1224 print m
1205 self.InteractiveTB.show_exception_only(etype, value)
1225 self.InteractiveTB.show_exception_only(etype, value)
1206 else:
1226 else:
1207 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1227 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1208 if self.InteractiveTB.call_pdb:
1228 if self.InteractiveTB.call_pdb:
1209 # pdb mucks up readline, fix it back
1229 # pdb mucks up readline, fix it back
1210 self.set_completer()
1230 self.set_completer()
1211
1231
1212 except KeyboardInterrupt:
1232 except KeyboardInterrupt:
1213 self.write("\nKeyboardInterrupt\n")
1233 self.write("\nKeyboardInterrupt\n")
1214
1234
1215
1235
1216 def showsyntaxerror(self, filename=None):
1236 def showsyntaxerror(self, filename=None):
1217 """Display the syntax error that just occurred.
1237 """Display the syntax error that just occurred.
1218
1238
1219 This doesn't display a stack trace because there isn't one.
1239 This doesn't display a stack trace because there isn't one.
1220
1240
1221 If a filename is given, it is stuffed in the exception instead
1241 If a filename is given, it is stuffed in the exception instead
1222 of what was there before (because Python's parser always uses
1242 of what was there before (because Python's parser always uses
1223 "<string>" when reading from a string).
1243 "<string>" when reading from a string).
1224 """
1244 """
1225 etype, value, last_traceback = sys.exc_info()
1245 etype, value, last_traceback = sys.exc_info()
1226
1246
1227 # See note about these variables in showtraceback() above
1247 # See note about these variables in showtraceback() above
1228 sys.last_type = etype
1248 sys.last_type = etype
1229 sys.last_value = value
1249 sys.last_value = value
1230 sys.last_traceback = last_traceback
1250 sys.last_traceback = last_traceback
1231
1251
1232 if filename and etype is SyntaxError:
1252 if filename and etype is SyntaxError:
1233 # Work hard to stuff the correct filename in the exception
1253 # Work hard to stuff the correct filename in the exception
1234 try:
1254 try:
1235 msg, (dummy_filename, lineno, offset, line) = value
1255 msg, (dummy_filename, lineno, offset, line) = value
1236 except:
1256 except:
1237 # Not the format we expect; leave it alone
1257 # Not the format we expect; leave it alone
1238 pass
1258 pass
1239 else:
1259 else:
1240 # Stuff in the right filename
1260 # Stuff in the right filename
1241 try:
1261 try:
1242 # Assume SyntaxError is a class exception
1262 # Assume SyntaxError is a class exception
1243 value = SyntaxError(msg, (filename, lineno, offset, line))
1263 value = SyntaxError(msg, (filename, lineno, offset, line))
1244 except:
1264 except:
1245 # If that failed, assume SyntaxError is a string
1265 # If that failed, assume SyntaxError is a string
1246 value = msg, (filename, lineno, offset, line)
1266 value = msg, (filename, lineno, offset, line)
1247 self.SyntaxTB(etype,value,[])
1267 self.SyntaxTB(etype,value,[])
1248
1268
1249 #-------------------------------------------------------------------------
1269 #-------------------------------------------------------------------------
1250 # Things related to tab completion
1270 # Things related to tab completion
1251 #-------------------------------------------------------------------------
1271 #-------------------------------------------------------------------------
1252
1272
1253 def complete(self, text):
1273 def complete(self, text):
1254 """Return a sorted list of all possible completions on text.
1274 """Return a sorted list of all possible completions on text.
1255
1275
1256 Inputs:
1276 Inputs:
1257
1277
1258 - text: a string of text to be completed on.
1278 - text: a string of text to be completed on.
1259
1279
1260 This is a wrapper around the completion mechanism, similar to what
1280 This is a wrapper around the completion mechanism, similar to what
1261 readline does at the command line when the TAB key is hit. By
1281 readline does at the command line when the TAB key is hit. By
1262 exposing it as a method, it can be used by other non-readline
1282 exposing it as a method, it can be used by other non-readline
1263 environments (such as GUIs) for text completion.
1283 environments (such as GUIs) for text completion.
1264
1284
1265 Simple usage example:
1285 Simple usage example:
1266
1286
1267 In [7]: x = 'hello'
1287 In [7]: x = 'hello'
1268
1288
1269 In [8]: x
1289 In [8]: x
1270 Out[8]: 'hello'
1290 Out[8]: 'hello'
1271
1291
1272 In [9]: print x
1292 In [9]: print x
1273 hello
1293 hello
1274
1294
1275 In [10]: _ip.complete('x.l')
1295 In [10]: _ip.complete('x.l')
1276 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1296 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1277 """
1297 """
1278
1298
1279 # Inject names into __builtin__ so we can complete on the added names.
1299 # Inject names into __builtin__ so we can complete on the added names.
1280 with self.builtin_trap:
1300 with self.builtin_trap:
1281 complete = self.Completer.complete
1301 complete = self.Completer.complete
1282 state = 0
1302 state = 0
1283 # use a dict so we get unique keys, since ipyhton's multiple
1303 # use a dict so we get unique keys, since ipyhton's multiple
1284 # completers can return duplicates. When we make 2.4 a requirement,
1304 # completers can return duplicates. When we make 2.4 a requirement,
1285 # start using sets instead, which are faster.
1305 # start using sets instead, which are faster.
1286 comps = {}
1306 comps = {}
1287 while True:
1307 while True:
1288 newcomp = complete(text,state,line_buffer=text)
1308 newcomp = complete(text,state,line_buffer=text)
1289 if newcomp is None:
1309 if newcomp is None:
1290 break
1310 break
1291 comps[newcomp] = 1
1311 comps[newcomp] = 1
1292 state += 1
1312 state += 1
1293 outcomps = comps.keys()
1313 outcomps = comps.keys()
1294 outcomps.sort()
1314 outcomps.sort()
1295 #print "T:",text,"OC:",outcomps # dbg
1315 #print "T:",text,"OC:",outcomps # dbg
1296 #print "vars:",self.user_ns.keys()
1316 #print "vars:",self.user_ns.keys()
1297 return outcomps
1317 return outcomps
1298
1318
1299 def set_custom_completer(self,completer,pos=0):
1319 def set_custom_completer(self,completer,pos=0):
1300 """Adds a new custom completer function.
1320 """Adds a new custom completer function.
1301
1321
1302 The position argument (defaults to 0) is the index in the completers
1322 The position argument (defaults to 0) is the index in the completers
1303 list where you want the completer to be inserted."""
1323 list where you want the completer to be inserted."""
1304
1324
1305 newcomp = new.instancemethod(completer,self.Completer,
1325 newcomp = new.instancemethod(completer,self.Completer,
1306 self.Completer.__class__)
1326 self.Completer.__class__)
1307 self.Completer.matchers.insert(pos,newcomp)
1327 self.Completer.matchers.insert(pos,newcomp)
1308
1328
1309 def set_completer(self):
1329 def set_completer(self):
1310 """Reset readline's completer to be our own."""
1330 """Reset readline's completer to be our own."""
1311 self.readline.set_completer(self.Completer.complete)
1331 self.readline.set_completer(self.Completer.complete)
1312
1332
1313 def set_completer_frame(self, frame=None):
1333 def set_completer_frame(self, frame=None):
1314 """Set the frame of the completer."""
1334 """Set the frame of the completer."""
1315 if frame:
1335 if frame:
1316 self.Completer.namespace = frame.f_locals
1336 self.Completer.namespace = frame.f_locals
1317 self.Completer.global_namespace = frame.f_globals
1337 self.Completer.global_namespace = frame.f_globals
1318 else:
1338 else:
1319 self.Completer.namespace = self.user_ns
1339 self.Completer.namespace = self.user_ns
1320 self.Completer.global_namespace = self.user_global_ns
1340 self.Completer.global_namespace = self.user_global_ns
1321
1341
1322 #-------------------------------------------------------------------------
1342 #-------------------------------------------------------------------------
1323 # Things related to readline
1343 # Things related to readline
1324 #-------------------------------------------------------------------------
1344 #-------------------------------------------------------------------------
1325
1345
1326 def init_readline(self):
1346 def init_readline(self):
1327 """Command history completion/saving/reloading."""
1347 """Command history completion/saving/reloading."""
1328
1348
1329 if self.readline_use:
1349 if self.readline_use:
1330 import IPython.utils.rlineimpl as readline
1350 import IPython.utils.rlineimpl as readline
1331
1351
1332 self.rl_next_input = None
1352 self.rl_next_input = None
1333 self.rl_do_indent = False
1353 self.rl_do_indent = False
1334
1354
1335 if not self.readline_use or not readline.have_readline:
1355 if not self.readline_use or not readline.have_readline:
1336 self.has_readline = False
1356 self.has_readline = False
1337 self.readline = None
1357 self.readline = None
1338 # Set a number of methods that depend on readline to be no-op
1358 # Set a number of methods that depend on readline to be no-op
1339 self.savehist = no_op
1359 self.savehist = no_op
1340 self.reloadhist = no_op
1360 self.reloadhist = no_op
1341 self.set_completer = no_op
1361 self.set_completer = no_op
1342 self.set_custom_completer = no_op
1362 self.set_custom_completer = no_op
1343 self.set_completer_frame = no_op
1363 self.set_completer_frame = no_op
1344 warn('Readline services not available or not loaded.')
1364 warn('Readline services not available or not loaded.')
1345 else:
1365 else:
1346 self.has_readline = True
1366 self.has_readline = True
1347 self.readline = readline
1367 self.readline = readline
1348 sys.modules['readline'] = readline
1368 sys.modules['readline'] = readline
1349 import atexit
1369 import atexit
1350 from IPython.core.completer import IPCompleter
1370 from IPython.core.completer import IPCompleter
1351 self.Completer = IPCompleter(self,
1371 self.Completer = IPCompleter(self,
1352 self.user_ns,
1372 self.user_ns,
1353 self.user_global_ns,
1373 self.user_global_ns,
1354 self.readline_omit__names,
1374 self.readline_omit__names,
1355 self.alias_manager.alias_table)
1375 self.alias_manager.alias_table)
1356 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1376 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1357 self.strdispatchers['complete_command'] = sdisp
1377 self.strdispatchers['complete_command'] = sdisp
1358 self.Completer.custom_completers = sdisp
1378 self.Completer.custom_completers = sdisp
1359 # Platform-specific configuration
1379 # Platform-specific configuration
1360 if os.name == 'nt':
1380 if os.name == 'nt':
1361 self.readline_startup_hook = readline.set_pre_input_hook
1381 self.readline_startup_hook = readline.set_pre_input_hook
1362 else:
1382 else:
1363 self.readline_startup_hook = readline.set_startup_hook
1383 self.readline_startup_hook = readline.set_startup_hook
1364
1384
1365 # Load user's initrc file (readline config)
1385 # Load user's initrc file (readline config)
1366 # Or if libedit is used, load editrc.
1386 # Or if libedit is used, load editrc.
1367 inputrc_name = os.environ.get('INPUTRC')
1387 inputrc_name = os.environ.get('INPUTRC')
1368 if inputrc_name is None:
1388 if inputrc_name is None:
1369 home_dir = get_home_dir()
1389 home_dir = get_home_dir()
1370 if home_dir is not None:
1390 if home_dir is not None:
1371 inputrc_name = '.inputrc'
1391 inputrc_name = '.inputrc'
1372 if readline.uses_libedit:
1392 if readline.uses_libedit:
1373 inputrc_name = '.editrc'
1393 inputrc_name = '.editrc'
1374 inputrc_name = os.path.join(home_dir, inputrc_name)
1394 inputrc_name = os.path.join(home_dir, inputrc_name)
1375 if os.path.isfile(inputrc_name):
1395 if os.path.isfile(inputrc_name):
1376 try:
1396 try:
1377 readline.read_init_file(inputrc_name)
1397 readline.read_init_file(inputrc_name)
1378 except:
1398 except:
1379 warn('Problems reading readline initialization file <%s>'
1399 warn('Problems reading readline initialization file <%s>'
1380 % inputrc_name)
1400 % inputrc_name)
1381
1401
1382 # save this in sys so embedded copies can restore it properly
1402 # save this in sys so embedded copies can restore it properly
1383 sys.ipcompleter = self.Completer.complete
1403 sys.ipcompleter = self.Completer.complete
1384 self.set_completer()
1404 self.set_completer()
1385
1405
1386 # Configure readline according to user's prefs
1406 # Configure readline according to user's prefs
1387 # This is only done if GNU readline is being used. If libedit
1407 # This is only done if GNU readline is being used. If libedit
1388 # is being used (as on Leopard) the readline config is
1408 # is being used (as on Leopard) the readline config is
1389 # not run as the syntax for libedit is different.
1409 # not run as the syntax for libedit is different.
1390 if not readline.uses_libedit:
1410 if not readline.uses_libedit:
1391 for rlcommand in self.readline_parse_and_bind:
1411 for rlcommand in self.readline_parse_and_bind:
1392 #print "loading rl:",rlcommand # dbg
1412 #print "loading rl:",rlcommand # dbg
1393 readline.parse_and_bind(rlcommand)
1413 readline.parse_and_bind(rlcommand)
1394
1414
1395 # Remove some chars from the delimiters list. If we encounter
1415 # Remove some chars from the delimiters list. If we encounter
1396 # unicode chars, discard them.
1416 # unicode chars, discard them.
1397 delims = readline.get_completer_delims().encode("ascii", "ignore")
1417 delims = readline.get_completer_delims().encode("ascii", "ignore")
1398 delims = delims.translate(string._idmap,
1418 delims = delims.translate(string._idmap,
1399 self.readline_remove_delims)
1419 self.readline_remove_delims)
1400 readline.set_completer_delims(delims)
1420 readline.set_completer_delims(delims)
1401 # otherwise we end up with a monster history after a while:
1421 # otherwise we end up with a monster history after a while:
1402 readline.set_history_length(1000)
1422 readline.set_history_length(1000)
1403 try:
1423 try:
1404 #print '*** Reading readline history' # dbg
1424 #print '*** Reading readline history' # dbg
1405 readline.read_history_file(self.histfile)
1425 readline.read_history_file(self.histfile)
1406 except IOError:
1426 except IOError:
1407 pass # It doesn't exist yet.
1427 pass # It doesn't exist yet.
1408
1428
1409 atexit.register(self.atexit_operations)
1429 atexit.register(self.atexit_operations)
1410 del atexit
1430 del atexit
1411
1431
1412 # Configure auto-indent for all platforms
1432 # Configure auto-indent for all platforms
1413 self.set_autoindent(self.autoindent)
1433 self.set_autoindent(self.autoindent)
1414
1434
1415 def set_next_input(self, s):
1435 def set_next_input(self, s):
1416 """ Sets the 'default' input string for the next command line.
1436 """ Sets the 'default' input string for the next command line.
1417
1437
1418 Requires readline.
1438 Requires readline.
1419
1439
1420 Example:
1440 Example:
1421
1441
1422 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1442 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1423 [D:\ipython]|2> Hello Word_ # cursor is here
1443 [D:\ipython]|2> Hello Word_ # cursor is here
1424 """
1444 """
1425
1445
1426 self.rl_next_input = s
1446 self.rl_next_input = s
1427
1447
1428 # Maybe move this to the terminal subclass?
1448 # Maybe move this to the terminal subclass?
1429 def pre_readline(self):
1449 def pre_readline(self):
1430 """readline hook to be used at the start of each line.
1450 """readline hook to be used at the start of each line.
1431
1451
1432 Currently it handles auto-indent only."""
1452 Currently it handles auto-indent only."""
1433
1453
1434 if self.rl_do_indent:
1454 if self.rl_do_indent:
1435 self.readline.insert_text(self._indent_current_str())
1455 self.readline.insert_text(self._indent_current_str())
1436 if self.rl_next_input is not None:
1456 if self.rl_next_input is not None:
1437 self.readline.insert_text(self.rl_next_input)
1457 self.readline.insert_text(self.rl_next_input)
1438 self.rl_next_input = None
1458 self.rl_next_input = None
1439
1459
1440 def _indent_current_str(self):
1460 def _indent_current_str(self):
1441 """return the current level of indentation as a string"""
1461 """return the current level of indentation as a string"""
1442 return self.indent_current_nsp * ' '
1462 return self.indent_current_nsp * ' '
1443
1463
1444 #-------------------------------------------------------------------------
1464 #-------------------------------------------------------------------------
1445 # Things related to magics
1465 # Things related to magics
1446 #-------------------------------------------------------------------------
1466 #-------------------------------------------------------------------------
1447
1467
1448 def init_magics(self):
1468 def init_magics(self):
1449 # Set user colors (don't do it in the constructor above so that it
1469 # Set user colors (don't do it in the constructor above so that it
1450 # doesn't crash if colors option is invalid)
1470 # doesn't crash if colors option is invalid)
1451 self.magic_colors(self.colors)
1471 self.magic_colors(self.colors)
1452 # History was moved to a separate module
1472 # History was moved to a separate module
1453 from . import history
1473 from . import history
1454 history.init_ipython(self)
1474 history.init_ipython(self)
1455
1475
1456 def magic(self,arg_s):
1476 def magic(self,arg_s):
1457 """Call a magic function by name.
1477 """Call a magic function by name.
1458
1478
1459 Input: a string containing the name of the magic function to call and any
1479 Input: a string containing the name of the magic function to call and any
1460 additional arguments to be passed to the magic.
1480 additional arguments to be passed to the magic.
1461
1481
1462 magic('name -opt foo bar') is equivalent to typing at the ipython
1482 magic('name -opt foo bar') is equivalent to typing at the ipython
1463 prompt:
1483 prompt:
1464
1484
1465 In[1]: %name -opt foo bar
1485 In[1]: %name -opt foo bar
1466
1486
1467 To call a magic without arguments, simply use magic('name').
1487 To call a magic without arguments, simply use magic('name').
1468
1488
1469 This provides a proper Python function to call IPython's magics in any
1489 This provides a proper Python function to call IPython's magics in any
1470 valid Python code you can type at the interpreter, including loops and
1490 valid Python code you can type at the interpreter, including loops and
1471 compound statements.
1491 compound statements.
1472 """
1492 """
1473 args = arg_s.split(' ',1)
1493 args = arg_s.split(' ',1)
1474 magic_name = args[0]
1494 magic_name = args[0]
1475 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1495 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1476
1496
1477 try:
1497 try:
1478 magic_args = args[1]
1498 magic_args = args[1]
1479 except IndexError:
1499 except IndexError:
1480 magic_args = ''
1500 magic_args = ''
1481 fn = getattr(self,'magic_'+magic_name,None)
1501 fn = getattr(self,'magic_'+magic_name,None)
1482 if fn is None:
1502 if fn is None:
1483 error("Magic function `%s` not found." % magic_name)
1503 error("Magic function `%s` not found." % magic_name)
1484 else:
1504 else:
1485 magic_args = self.var_expand(magic_args,1)
1505 magic_args = self.var_expand(magic_args,1)
1486 with nested(self.builtin_trap,):
1506 with nested(self.builtin_trap,):
1487 result = fn(magic_args)
1507 result = fn(magic_args)
1488 return result
1508 return result
1489
1509
1490 def define_magic(self, magicname, func):
1510 def define_magic(self, magicname, func):
1491 """Expose own function as magic function for ipython
1511 """Expose own function as magic function for ipython
1492
1512
1493 def foo_impl(self,parameter_s=''):
1513 def foo_impl(self,parameter_s=''):
1494 'My very own magic!. (Use docstrings, IPython reads them).'
1514 'My very own magic!. (Use docstrings, IPython reads them).'
1495 print 'Magic function. Passed parameter is between < >:'
1515 print 'Magic function. Passed parameter is between < >:'
1496 print '<%s>' % parameter_s
1516 print '<%s>' % parameter_s
1497 print 'The self object is:',self
1517 print 'The self object is:',self
1498
1518
1499 self.define_magic('foo',foo_impl)
1519 self.define_magic('foo',foo_impl)
1500 """
1520 """
1501
1521
1502 import new
1522 import new
1503 im = new.instancemethod(func,self, self.__class__)
1523 im = new.instancemethod(func,self, self.__class__)
1504 old = getattr(self, "magic_" + magicname, None)
1524 old = getattr(self, "magic_" + magicname, None)
1505 setattr(self, "magic_" + magicname, im)
1525 setattr(self, "magic_" + magicname, im)
1506 return old
1526 return old
1507
1527
1508 #-------------------------------------------------------------------------
1528 #-------------------------------------------------------------------------
1509 # Things related to macros
1529 # Things related to macros
1510 #-------------------------------------------------------------------------
1530 #-------------------------------------------------------------------------
1511
1531
1512 def define_macro(self, name, themacro):
1532 def define_macro(self, name, themacro):
1513 """Define a new macro
1533 """Define a new macro
1514
1534
1515 Parameters
1535 Parameters
1516 ----------
1536 ----------
1517 name : str
1537 name : str
1518 The name of the macro.
1538 The name of the macro.
1519 themacro : str or Macro
1539 themacro : str or Macro
1520 The action to do upon invoking the macro. If a string, a new
1540 The action to do upon invoking the macro. If a string, a new
1521 Macro object is created by passing the string to it.
1541 Macro object is created by passing the string to it.
1522 """
1542 """
1523
1543
1524 from IPython.core import macro
1544 from IPython.core import macro
1525
1545
1526 if isinstance(themacro, basestring):
1546 if isinstance(themacro, basestring):
1527 themacro = macro.Macro(themacro)
1547 themacro = macro.Macro(themacro)
1528 if not isinstance(themacro, macro.Macro):
1548 if not isinstance(themacro, macro.Macro):
1529 raise ValueError('A macro must be a string or a Macro instance.')
1549 raise ValueError('A macro must be a string or a Macro instance.')
1530 self.user_ns[name] = themacro
1550 self.user_ns[name] = themacro
1531
1551
1532 #-------------------------------------------------------------------------
1552 #-------------------------------------------------------------------------
1533 # Things related to the running of system commands
1553 # Things related to the running of system commands
1534 #-------------------------------------------------------------------------
1554 #-------------------------------------------------------------------------
1535
1555
1536 def system(self, cmd):
1556 def system(self, cmd):
1537 """Make a system call, using IPython."""
1557 """Make a system call, using IPython."""
1538 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1558 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1539
1559
1540 #-------------------------------------------------------------------------
1560 #-------------------------------------------------------------------------
1541 # Things related to aliases
1561 # Things related to aliases
1542 #-------------------------------------------------------------------------
1562 #-------------------------------------------------------------------------
1543
1563
1544 def init_alias(self):
1564 def init_alias(self):
1545 self.alias_manager = AliasManager(shell=self, config=self.config)
1565 self.alias_manager = AliasManager(shell=self, config=self.config)
1546 self.ns_table['alias'] = self.alias_manager.alias_table,
1566 self.ns_table['alias'] = self.alias_manager.alias_table,
1547
1567
1548 #-------------------------------------------------------------------------
1568 #-------------------------------------------------------------------------
1549 # Things related to extensions and plugins
1569 # Things related to extensions and plugins
1550 #-------------------------------------------------------------------------
1570 #-------------------------------------------------------------------------
1551
1571
1552 def init_extension_manager(self):
1572 def init_extension_manager(self):
1553 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1573 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1554
1574
1555 def init_plugin_manager(self):
1575 def init_plugin_manager(self):
1556 self.plugin_manager = PluginManager(config=self.config)
1576 self.plugin_manager = PluginManager(config=self.config)
1557
1577
1558 #-------------------------------------------------------------------------
1578 #-------------------------------------------------------------------------
1559 # Things related to the prefilter
1579 # Things related to the prefilter
1560 #-------------------------------------------------------------------------
1580 #-------------------------------------------------------------------------
1561
1581
1562 def init_prefilter(self):
1582 def init_prefilter(self):
1563 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1583 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1564 # Ultimately this will be refactored in the new interpreter code, but
1584 # Ultimately this will be refactored in the new interpreter code, but
1565 # for now, we should expose the main prefilter method (there's legacy
1585 # for now, we should expose the main prefilter method (there's legacy
1566 # code out there that may rely on this).
1586 # code out there that may rely on this).
1567 self.prefilter = self.prefilter_manager.prefilter_lines
1587 self.prefilter = self.prefilter_manager.prefilter_lines
1568
1588
1569 #-------------------------------------------------------------------------
1589 #-------------------------------------------------------------------------
1570 # Things related to the running of code
1590 # Things related to the running of code
1571 #-------------------------------------------------------------------------
1591 #-------------------------------------------------------------------------
1572
1592
1573 def ex(self, cmd):
1593 def ex(self, cmd):
1574 """Execute a normal python statement in user namespace."""
1594 """Execute a normal python statement in user namespace."""
1575 with nested(self.builtin_trap,):
1595 with nested(self.builtin_trap,):
1576 exec cmd in self.user_global_ns, self.user_ns
1596 exec cmd in self.user_global_ns, self.user_ns
1577
1597
1578 def ev(self, expr):
1598 def ev(self, expr):
1579 """Evaluate python expression expr in user namespace.
1599 """Evaluate python expression expr in user namespace.
1580
1600
1581 Returns the result of evaluation
1601 Returns the result of evaluation
1582 """
1602 """
1583 with nested(self.builtin_trap,):
1603 with nested(self.builtin_trap,):
1584 return eval(expr, self.user_global_ns, self.user_ns)
1604 return eval(expr, self.user_global_ns, self.user_ns)
1585
1605
1586 def safe_execfile(self, fname, *where, **kw):
1606 def safe_execfile(self, fname, *where, **kw):
1587 """A safe version of the builtin execfile().
1607 """A safe version of the builtin execfile().
1588
1608
1589 This version will never throw an exception, but instead print
1609 This version will never throw an exception, but instead print
1590 helpful error messages to the screen. This only works on pure
1610 helpful error messages to the screen. This only works on pure
1591 Python files with the .py extension.
1611 Python files with the .py extension.
1592
1612
1593 Parameters
1613 Parameters
1594 ----------
1614 ----------
1595 fname : string
1615 fname : string
1596 The name of the file to be executed.
1616 The name of the file to be executed.
1597 where : tuple
1617 where : tuple
1598 One or two namespaces, passed to execfile() as (globals,locals).
1618 One or two namespaces, passed to execfile() as (globals,locals).
1599 If only one is given, it is passed as both.
1619 If only one is given, it is passed as both.
1600 exit_ignore : bool (False)
1620 exit_ignore : bool (False)
1601 If True, then silence SystemExit for non-zero status (it is always
1621 If True, then silence SystemExit for non-zero status (it is always
1602 silenced for zero status, as it is so common).
1622 silenced for zero status, as it is so common).
1603 """
1623 """
1604 kw.setdefault('exit_ignore', False)
1624 kw.setdefault('exit_ignore', False)
1605
1625
1606 fname = os.path.abspath(os.path.expanduser(fname))
1626 fname = os.path.abspath(os.path.expanduser(fname))
1607
1627
1608 # Make sure we have a .py file
1628 # Make sure we have a .py file
1609 if not fname.endswith('.py'):
1629 if not fname.endswith('.py'):
1610 warn('File must end with .py to be run using execfile: <%s>' % fname)
1630 warn('File must end with .py to be run using execfile: <%s>' % fname)
1611
1631
1612 # Make sure we can open the file
1632 # Make sure we can open the file
1613 try:
1633 try:
1614 with open(fname) as thefile:
1634 with open(fname) as thefile:
1615 pass
1635 pass
1616 except:
1636 except:
1617 warn('Could not open file <%s> for safe execution.' % fname)
1637 warn('Could not open file <%s> for safe execution.' % fname)
1618 return
1638 return
1619
1639
1620 # Find things also in current directory. This is needed to mimic the
1640 # Find things also in current directory. This is needed to mimic the
1621 # behavior of running a script from the system command line, where
1641 # behavior of running a script from the system command line, where
1622 # Python inserts the script's directory into sys.path
1642 # Python inserts the script's directory into sys.path
1623 dname = os.path.dirname(fname)
1643 dname = os.path.dirname(fname)
1624
1644
1625 with prepended_to_syspath(dname):
1645 with prepended_to_syspath(dname):
1626 try:
1646 try:
1627 execfile(fname,*where)
1647 execfile(fname,*where)
1628 except SystemExit, status:
1648 except SystemExit, status:
1629 # If the call was made with 0 or None exit status (sys.exit(0)
1649 # If the call was made with 0 or None exit status (sys.exit(0)
1630 # or sys.exit() ), don't bother showing a traceback, as both of
1650 # or sys.exit() ), don't bother showing a traceback, as both of
1631 # these are considered normal by the OS:
1651 # these are considered normal by the OS:
1632 # > python -c'import sys;sys.exit(0)'; echo $?
1652 # > python -c'import sys;sys.exit(0)'; echo $?
1633 # 0
1653 # 0
1634 # > python -c'import sys;sys.exit()'; echo $?
1654 # > python -c'import sys;sys.exit()'; echo $?
1635 # 0
1655 # 0
1636 # For other exit status, we show the exception unless
1656 # For other exit status, we show the exception unless
1637 # explicitly silenced, but only in short form.
1657 # explicitly silenced, but only in short form.
1638 if status.code not in (0, None) and not kw['exit_ignore']:
1658 if status.code not in (0, None) and not kw['exit_ignore']:
1639 self.showtraceback(exception_only=True)
1659 self.showtraceback(exception_only=True)
1640 except:
1660 except:
1641 self.showtraceback()
1661 self.showtraceback()
1642
1662
1643 def safe_execfile_ipy(self, fname):
1663 def safe_execfile_ipy(self, fname):
1644 """Like safe_execfile, but for .ipy files with IPython syntax.
1664 """Like safe_execfile, but for .ipy files with IPython syntax.
1645
1665
1646 Parameters
1666 Parameters
1647 ----------
1667 ----------
1648 fname : str
1668 fname : str
1649 The name of the file to execute. The filename must have a
1669 The name of the file to execute. The filename must have a
1650 .ipy extension.
1670 .ipy extension.
1651 """
1671 """
1652 fname = os.path.abspath(os.path.expanduser(fname))
1672 fname = os.path.abspath(os.path.expanduser(fname))
1653
1673
1654 # Make sure we have a .py file
1674 # Make sure we have a .py file
1655 if not fname.endswith('.ipy'):
1675 if not fname.endswith('.ipy'):
1656 warn('File must end with .py to be run using execfile: <%s>' % fname)
1676 warn('File must end with .py to be run using execfile: <%s>' % fname)
1657
1677
1658 # Make sure we can open the file
1678 # Make sure we can open the file
1659 try:
1679 try:
1660 with open(fname) as thefile:
1680 with open(fname) as thefile:
1661 pass
1681 pass
1662 except:
1682 except:
1663 warn('Could not open file <%s> for safe execution.' % fname)
1683 warn('Could not open file <%s> for safe execution.' % fname)
1664 return
1684 return
1665
1685
1666 # Find things also in current directory. This is needed to mimic the
1686 # Find things also in current directory. This is needed to mimic the
1667 # behavior of running a script from the system command line, where
1687 # behavior of running a script from the system command line, where
1668 # Python inserts the script's directory into sys.path
1688 # Python inserts the script's directory into sys.path
1669 dname = os.path.dirname(fname)
1689 dname = os.path.dirname(fname)
1670
1690
1671 with prepended_to_syspath(dname):
1691 with prepended_to_syspath(dname):
1672 try:
1692 try:
1673 with open(fname) as thefile:
1693 with open(fname) as thefile:
1674 script = thefile.read()
1694 script = thefile.read()
1675 # self.runlines currently captures all exceptions
1695 # self.runlines currently captures all exceptions
1676 # raise in user code. It would be nice if there were
1696 # raise in user code. It would be nice if there were
1677 # versions of runlines, execfile that did raise, so
1697 # versions of runlines, execfile that did raise, so
1678 # we could catch the errors.
1698 # we could catch the errors.
1679 self.runlines(script, clean=True)
1699 self.runlines(script, clean=True)
1680 except:
1700 except:
1681 self.showtraceback()
1701 self.showtraceback()
1682 warn('Unknown failure executing file: <%s>' % fname)
1702 warn('Unknown failure executing file: <%s>' % fname)
1683
1703
1684 def runlines(self, lines, clean=False):
1704 def runlines(self, lines, clean=False):
1685 """Run a string of one or more lines of source.
1705 """Run a string of one or more lines of source.
1686
1706
1687 This method is capable of running a string containing multiple source
1707 This method is capable of running a string containing multiple source
1688 lines, as if they had been entered at the IPython prompt. Since it
1708 lines, as if they had been entered at the IPython prompt. Since it
1689 exposes IPython's processing machinery, the given strings can contain
1709 exposes IPython's processing machinery, the given strings can contain
1690 magic calls (%magic), special shell access (!cmd), etc.
1710 magic calls (%magic), special shell access (!cmd), etc.
1691 """
1711 """
1692
1712
1693 if isinstance(lines, (list, tuple)):
1713 if isinstance(lines, (list, tuple)):
1694 lines = '\n'.join(lines)
1714 lines = '\n'.join(lines)
1695
1715
1696 if clean:
1716 if clean:
1697 lines = self._cleanup_ipy_script(lines)
1717 lines = self._cleanup_ipy_script(lines)
1698
1718
1699 # We must start with a clean buffer, in case this is run from an
1719 # We must start with a clean buffer, in case this is run from an
1700 # interactive IPython session (via a magic, for example).
1720 # interactive IPython session (via a magic, for example).
1701 self.resetbuffer()
1721 self.resetbuffer()
1702 lines = lines.splitlines()
1722 lines = lines.splitlines()
1703 more = 0
1723 more = 0
1704
1724
1705 with nested(self.builtin_trap, self.display_trap):
1725 with nested(self.builtin_trap, self.display_trap):
1706 for line in lines:
1726 for line in lines:
1707 # skip blank lines so we don't mess up the prompt counter, but do
1727 # skip blank lines so we don't mess up the prompt counter, but do
1708 # NOT skip even a blank line if we are in a code block (more is
1728 # NOT skip even a blank line if we are in a code block (more is
1709 # true)
1729 # true)
1710
1730
1711 if line or more:
1731 if line or more:
1712 # push to raw history, so hist line numbers stay in sync
1732 # push to raw history, so hist line numbers stay in sync
1713 self.input_hist_raw.append("# " + line + "\n")
1733 self.input_hist_raw.append("# " + line + "\n")
1714 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1734 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1715 more = self.push_line(prefiltered)
1735 more = self.push_line(prefiltered)
1716 # IPython's runsource returns None if there was an error
1736 # IPython's runsource returns None if there was an error
1717 # compiling the code. This allows us to stop processing right
1737 # compiling the code. This allows us to stop processing right
1718 # away, so the user gets the error message at the right place.
1738 # away, so the user gets the error message at the right place.
1719 if more is None:
1739 if more is None:
1720 break
1740 break
1721 else:
1741 else:
1722 self.input_hist_raw.append("\n")
1742 self.input_hist_raw.append("\n")
1723 # final newline in case the input didn't have it, so that the code
1743 # final newline in case the input didn't have it, so that the code
1724 # actually does get executed
1744 # actually does get executed
1725 if more:
1745 if more:
1726 self.push_line('\n')
1746 self.push_line('\n')
1727
1747
1728 def runsource(self, source, filename='<input>', symbol='single'):
1748 def runsource(self, source, filename='<input>', symbol='single'):
1729 """Compile and run some source in the interpreter.
1749 """Compile and run some source in the interpreter.
1730
1750
1731 Arguments are as for compile_command().
1751 Arguments are as for compile_command().
1732
1752
1733 One several things can happen:
1753 One several things can happen:
1734
1754
1735 1) The input is incorrect; compile_command() raised an
1755 1) The input is incorrect; compile_command() raised an
1736 exception (SyntaxError or OverflowError). A syntax traceback
1756 exception (SyntaxError or OverflowError). A syntax traceback
1737 will be printed by calling the showsyntaxerror() method.
1757 will be printed by calling the showsyntaxerror() method.
1738
1758
1739 2) The input is incomplete, and more input is required;
1759 2) The input is incomplete, and more input is required;
1740 compile_command() returned None. Nothing happens.
1760 compile_command() returned None. Nothing happens.
1741
1761
1742 3) The input is complete; compile_command() returned a code
1762 3) The input is complete; compile_command() returned a code
1743 object. The code is executed by calling self.runcode() (which
1763 object. The code is executed by calling self.runcode() (which
1744 also handles run-time exceptions, except for SystemExit).
1764 also handles run-time exceptions, except for SystemExit).
1745
1765
1746 The return value is:
1766 The return value is:
1747
1767
1748 - True in case 2
1768 - True in case 2
1749
1769
1750 - False in the other cases, unless an exception is raised, where
1770 - False in the other cases, unless an exception is raised, where
1751 None is returned instead. This can be used by external callers to
1771 None is returned instead. This can be used by external callers to
1752 know whether to continue feeding input or not.
1772 know whether to continue feeding input or not.
1753
1773
1754 The return value can be used to decide whether to use sys.ps1 or
1774 The return value can be used to decide whether to use sys.ps1 or
1755 sys.ps2 to prompt the next line."""
1775 sys.ps2 to prompt the next line."""
1756
1776
1757 # if the source code has leading blanks, add 'if 1:\n' to it
1777 # if the source code has leading blanks, add 'if 1:\n' to it
1758 # this allows execution of indented pasted code. It is tempting
1778 # this allows execution of indented pasted code. It is tempting
1759 # to add '\n' at the end of source to run commands like ' a=1'
1779 # to add '\n' at the end of source to run commands like ' a=1'
1760 # directly, but this fails for more complicated scenarios
1780 # directly, but this fails for more complicated scenarios
1761 source=source.encode(self.stdin_encoding)
1781 source=source.encode(self.stdin_encoding)
1762 if source[:1] in [' ', '\t']:
1782 if source[:1] in [' ', '\t']:
1763 source = 'if 1:\n%s' % source
1783 source = 'if 1:\n%s' % source
1764
1784
1765 try:
1785 try:
1766 code = self.compile(source,filename,symbol)
1786 code = self.compile(source,filename,symbol)
1767 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1787 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1768 # Case 1
1788 # Case 1
1769 self.showsyntaxerror(filename)
1789 self.showsyntaxerror(filename)
1770 return None
1790 return None
1771
1791
1772 if code is None:
1792 if code is None:
1773 # Case 2
1793 # Case 2
1774 return True
1794 return True
1775
1795
1776 # Case 3
1796 # Case 3
1777 # We store the code object so that threaded shells and
1797 # We store the code object so that threaded shells and
1778 # custom exception handlers can access all this info if needed.
1798 # custom exception handlers can access all this info if needed.
1779 # The source corresponding to this can be obtained from the
1799 # The source corresponding to this can be obtained from the
1780 # buffer attribute as '\n'.join(self.buffer).
1800 # buffer attribute as '\n'.join(self.buffer).
1781 self.code_to_run = code
1801 self.code_to_run = code
1782 # now actually execute the code object
1802 # now actually execute the code object
1783 if self.runcode(code) == 0:
1803 if self.runcode(code) == 0:
1784 return False
1804 return False
1785 else:
1805 else:
1786 return None
1806 return None
1787
1807
1788 def runcode(self,code_obj):
1808 def runcode(self,code_obj):
1789 """Execute a code object.
1809 """Execute a code object.
1790
1810
1791 When an exception occurs, self.showtraceback() is called to display a
1811 When an exception occurs, self.showtraceback() is called to display a
1792 traceback.
1812 traceback.
1793
1813
1794 Return value: a flag indicating whether the code to be run completed
1814 Return value: a flag indicating whether the code to be run completed
1795 successfully:
1815 successfully:
1796
1816
1797 - 0: successful execution.
1817 - 0: successful execution.
1798 - 1: an error occurred.
1818 - 1: an error occurred.
1799 """
1819 """
1800
1820
1801 # Set our own excepthook in case the user code tries to call it
1821 # Set our own excepthook in case the user code tries to call it
1802 # directly, so that the IPython crash handler doesn't get triggered
1822 # directly, so that the IPython crash handler doesn't get triggered
1803 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1823 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1804
1824
1805 # we save the original sys.excepthook in the instance, in case config
1825 # we save the original sys.excepthook in the instance, in case config
1806 # code (such as magics) needs access to it.
1826 # code (such as magics) needs access to it.
1807 self.sys_excepthook = old_excepthook
1827 self.sys_excepthook = old_excepthook
1808 outflag = 1 # happens in more places, so it's easier as default
1828 outflag = 1 # happens in more places, so it's easier as default
1809 try:
1829 try:
1810 try:
1830 try:
1811 self.hooks.pre_runcode_hook()
1831 self.hooks.pre_runcode_hook()
1812 exec code_obj in self.user_global_ns, self.user_ns
1832 exec code_obj in self.user_global_ns, self.user_ns
1813 finally:
1833 finally:
1814 # Reset our crash handler in place
1834 # Reset our crash handler in place
1815 sys.excepthook = old_excepthook
1835 sys.excepthook = old_excepthook
1816 except SystemExit:
1836 except SystemExit:
1817 self.resetbuffer()
1837 self.resetbuffer()
1818 self.showtraceback(exception_only=True)
1838 self.showtraceback(exception_only=True)
1819 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1839 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1820 except self.custom_exceptions:
1840 except self.custom_exceptions:
1821 etype,value,tb = sys.exc_info()
1841 etype,value,tb = sys.exc_info()
1822 self.CustomTB(etype,value,tb)
1842 self.CustomTB(etype,value,tb)
1823 except:
1843 except:
1824 self.showtraceback()
1844 self.showtraceback()
1825 else:
1845 else:
1826 outflag = 0
1846 outflag = 0
1827 if softspace(sys.stdout, 0):
1847 if softspace(sys.stdout, 0):
1828 print
1848 print
1829 # Flush out code object which has been run (and source)
1849 # Flush out code object which has been run (and source)
1830 self.code_to_run = None
1850 self.code_to_run = None
1831 return outflag
1851 return outflag
1832
1852
1833 def push_line(self, line):
1853 def push_line(self, line):
1834 """Push a line to the interpreter.
1854 """Push a line to the interpreter.
1835
1855
1836 The line should not have a trailing newline; it may have
1856 The line should not have a trailing newline; it may have
1837 internal newlines. The line is appended to a buffer and the
1857 internal newlines. The line is appended to a buffer and the
1838 interpreter's runsource() method is called with the
1858 interpreter's runsource() method is called with the
1839 concatenated contents of the buffer as source. If this
1859 concatenated contents of the buffer as source. If this
1840 indicates that the command was executed or invalid, the buffer
1860 indicates that the command was executed or invalid, the buffer
1841 is reset; otherwise, the command is incomplete, and the buffer
1861 is reset; otherwise, the command is incomplete, and the buffer
1842 is left as it was after the line was appended. The return
1862 is left as it was after the line was appended. The return
1843 value is 1 if more input is required, 0 if the line was dealt
1863 value is 1 if more input is required, 0 if the line was dealt
1844 with in some way (this is the same as runsource()).
1864 with in some way (this is the same as runsource()).
1845 """
1865 """
1846
1866
1847 # autoindent management should be done here, and not in the
1867 # autoindent management should be done here, and not in the
1848 # interactive loop, since that one is only seen by keyboard input. We
1868 # interactive loop, since that one is only seen by keyboard input. We
1849 # need this done correctly even for code run via runlines (which uses
1869 # need this done correctly even for code run via runlines (which uses
1850 # push).
1870 # push).
1851
1871
1852 #print 'push line: <%s>' % line # dbg
1872 #print 'push line: <%s>' % line # dbg
1853 for subline in line.splitlines():
1873 for subline in line.splitlines():
1854 self._autoindent_update(subline)
1874 self._autoindent_update(subline)
1855 self.buffer.append(line)
1875 self.buffer.append(line)
1856 more = self.runsource('\n'.join(self.buffer), self.filename)
1876 more = self.runsource('\n'.join(self.buffer), self.filename)
1857 if not more:
1877 if not more:
1858 self.resetbuffer()
1878 self.resetbuffer()
1859 return more
1879 return more
1860
1880
1861 def resetbuffer(self):
1881 def resetbuffer(self):
1862 """Reset the input buffer."""
1882 """Reset the input buffer."""
1863 self.buffer[:] = []
1883 self.buffer[:] = []
1864
1884
1865 def _is_secondary_block_start(self, s):
1885 def _is_secondary_block_start(self, s):
1866 if not s.endswith(':'):
1886 if not s.endswith(':'):
1867 return False
1887 return False
1868 if (s.startswith('elif') or
1888 if (s.startswith('elif') or
1869 s.startswith('else') or
1889 s.startswith('else') or
1870 s.startswith('except') or
1890 s.startswith('except') or
1871 s.startswith('finally')):
1891 s.startswith('finally')):
1872 return True
1892 return True
1873
1893
1874 def _cleanup_ipy_script(self, script):
1894 def _cleanup_ipy_script(self, script):
1875 """Make a script safe for self.runlines()
1895 """Make a script safe for self.runlines()
1876
1896
1877 Currently, IPython is lines based, with blocks being detected by
1897 Currently, IPython is lines based, with blocks being detected by
1878 empty lines. This is a problem for block based scripts that may
1898 empty lines. This is a problem for block based scripts that may
1879 not have empty lines after blocks. This script adds those empty
1899 not have empty lines after blocks. This script adds those empty
1880 lines to make scripts safe for running in the current line based
1900 lines to make scripts safe for running in the current line based
1881 IPython.
1901 IPython.
1882 """
1902 """
1883 res = []
1903 res = []
1884 lines = script.splitlines()
1904 lines = script.splitlines()
1885 level = 0
1905 level = 0
1886
1906
1887 for l in lines:
1907 for l in lines:
1888 lstripped = l.lstrip()
1908 lstripped = l.lstrip()
1889 stripped = l.strip()
1909 stripped = l.strip()
1890 if not stripped:
1910 if not stripped:
1891 continue
1911 continue
1892 newlevel = len(l) - len(lstripped)
1912 newlevel = len(l) - len(lstripped)
1893 if level > 0 and newlevel == 0 and \
1913 if level > 0 and newlevel == 0 and \
1894 not self._is_secondary_block_start(stripped):
1914 not self._is_secondary_block_start(stripped):
1895 # add empty line
1915 # add empty line
1896 res.append('')
1916 res.append('')
1897 res.append(l)
1917 res.append(l)
1898 level = newlevel
1918 level = newlevel
1899
1919
1900 return '\n'.join(res) + '\n'
1920 return '\n'.join(res) + '\n'
1901
1921
1902 def _autoindent_update(self,line):
1922 def _autoindent_update(self,line):
1903 """Keep track of the indent level."""
1923 """Keep track of the indent level."""
1904
1924
1905 #debugx('line')
1925 #debugx('line')
1906 #debugx('self.indent_current_nsp')
1926 #debugx('self.indent_current_nsp')
1907 if self.autoindent:
1927 if self.autoindent:
1908 if line:
1928 if line:
1909 inisp = num_ini_spaces(line)
1929 inisp = num_ini_spaces(line)
1910 if inisp < self.indent_current_nsp:
1930 if inisp < self.indent_current_nsp:
1911 self.indent_current_nsp = inisp
1931 self.indent_current_nsp = inisp
1912
1932
1913 if line[-1] == ':':
1933 if line[-1] == ':':
1914 self.indent_current_nsp += 4
1934 self.indent_current_nsp += 4
1915 elif dedent_re.match(line):
1935 elif dedent_re.match(line):
1916 self.indent_current_nsp -= 4
1936 self.indent_current_nsp -= 4
1917 else:
1937 else:
1918 self.indent_current_nsp = 0
1938 self.indent_current_nsp = 0
1919
1939
1920 #-------------------------------------------------------------------------
1940 #-------------------------------------------------------------------------
1921 # Things related to GUI support and pylab
1941 # Things related to GUI support and pylab
1922 #-------------------------------------------------------------------------
1942 #-------------------------------------------------------------------------
1923
1943
1924 def enable_pylab(self, gui=None):
1944 def enable_pylab(self, gui=None):
1925 raise NotImplementedError('Implement enable_pylab in a subclass')
1945 raise NotImplementedError('Implement enable_pylab in a subclass')
1926
1946
1927 #-------------------------------------------------------------------------
1947 #-------------------------------------------------------------------------
1928 # Utilities
1948 # Utilities
1929 #-------------------------------------------------------------------------
1949 #-------------------------------------------------------------------------
1930
1950
1931 def getoutput(self, cmd):
1951 def getoutput(self, cmd):
1932 return getoutput(self.var_expand(cmd,depth=2),
1952 return getoutput(self.var_expand(cmd,depth=2),
1933 header=self.system_header,
1953 header=self.system_header,
1934 verbose=self.system_verbose)
1954 verbose=self.system_verbose)
1935
1955
1936 def getoutputerror(self, cmd):
1956 def getoutputerror(self, cmd):
1937 return getoutputerror(self.var_expand(cmd,depth=2),
1957 return getoutputerror(self.var_expand(cmd,depth=2),
1938 header=self.system_header,
1958 header=self.system_header,
1939 verbose=self.system_verbose)
1959 verbose=self.system_verbose)
1940
1960
1941 def var_expand(self,cmd,depth=0):
1961 def var_expand(self,cmd,depth=0):
1942 """Expand python variables in a string.
1962 """Expand python variables in a string.
1943
1963
1944 The depth argument indicates how many frames above the caller should
1964 The depth argument indicates how many frames above the caller should
1945 be walked to look for the local namespace where to expand variables.
1965 be walked to look for the local namespace where to expand variables.
1946
1966
1947 The global namespace for expansion is always the user's interactive
1967 The global namespace for expansion is always the user's interactive
1948 namespace.
1968 namespace.
1949 """
1969 """
1950
1970
1951 return str(ItplNS(cmd,
1971 return str(ItplNS(cmd,
1952 self.user_ns, # globals
1972 self.user_ns, # globals
1953 # Skip our own frame in searching for locals:
1973 # Skip our own frame in searching for locals:
1954 sys._getframe(depth+1).f_locals # locals
1974 sys._getframe(depth+1).f_locals # locals
1955 ))
1975 ))
1956
1976
1957 def mktempfile(self,data=None):
1977 def mktempfile(self,data=None):
1958 """Make a new tempfile and return its filename.
1978 """Make a new tempfile and return its filename.
1959
1979
1960 This makes a call to tempfile.mktemp, but it registers the created
1980 This makes a call to tempfile.mktemp, but it registers the created
1961 filename internally so ipython cleans it up at exit time.
1981 filename internally so ipython cleans it up at exit time.
1962
1982
1963 Optional inputs:
1983 Optional inputs:
1964
1984
1965 - data(None): if data is given, it gets written out to the temp file
1985 - data(None): if data is given, it gets written out to the temp file
1966 immediately, and the file is closed again."""
1986 immediately, and the file is closed again."""
1967
1987
1968 filename = tempfile.mktemp('.py','ipython_edit_')
1988 filename = tempfile.mktemp('.py','ipython_edit_')
1969 self.tempfiles.append(filename)
1989 self.tempfiles.append(filename)
1970
1990
1971 if data:
1991 if data:
1972 tmp_file = open(filename,'w')
1992 tmp_file = open(filename,'w')
1973 tmp_file.write(data)
1993 tmp_file.write(data)
1974 tmp_file.close()
1994 tmp_file.close()
1975 return filename
1995 return filename
1976
1996
1977 # TODO: This should be removed when Term is refactored.
1997 # TODO: This should be removed when Term is refactored.
1978 def write(self,data):
1998 def write(self,data):
1979 """Write a string to the default output"""
1999 """Write a string to the default output"""
1980 Term.cout.write(data)
2000 Term.cout.write(data)
1981
2001
1982 # TODO: This should be removed when Term is refactored.
2002 # TODO: This should be removed when Term is refactored.
1983 def write_err(self,data):
2003 def write_err(self,data):
1984 """Write a string to the default error output"""
2004 """Write a string to the default error output"""
1985 Term.cerr.write(data)
2005 Term.cerr.write(data)
1986
2006
1987 def ask_yes_no(self,prompt,default=True):
2007 def ask_yes_no(self,prompt,default=True):
1988 if self.quiet:
2008 if self.quiet:
1989 return True
2009 return True
1990 return ask_yes_no(prompt,default)
2010 return ask_yes_no(prompt,default)
1991
2011
1992 #-------------------------------------------------------------------------
2012 #-------------------------------------------------------------------------
1993 # Things related to IPython exiting
2013 # Things related to IPython exiting
1994 #-------------------------------------------------------------------------
2014 #-------------------------------------------------------------------------
1995
2015
1996 def atexit_operations(self):
2016 def atexit_operations(self):
1997 """This will be executed at the time of exit.
2017 """This will be executed at the time of exit.
1998
2018
1999 Saving of persistent data should be performed here.
2019 Saving of persistent data should be performed here.
2000 """
2020 """
2001 self.savehist()
2021 self.savehist()
2002
2022
2003 # Cleanup all tempfiles left around
2023 # Cleanup all tempfiles left around
2004 for tfile in self.tempfiles:
2024 for tfile in self.tempfiles:
2005 try:
2025 try:
2006 os.unlink(tfile)
2026 os.unlink(tfile)
2007 except OSError:
2027 except OSError:
2008 pass
2028 pass
2009
2029
2010 # Clear all user namespaces to release all references cleanly.
2030 # Clear all user namespaces to release all references cleanly.
2011 self.reset()
2031 self.reset()
2012
2032
2013 # Run user hooks
2033 # Run user hooks
2014 self.hooks.shutdown_hook()
2034 self.hooks.shutdown_hook()
2015
2035
2016 def cleanup(self):
2036 def cleanup(self):
2017 self.restore_sys_module_state()
2037 self.restore_sys_module_state()
2018
2038
2019
2039
2020 class InteractiveShellABC(object):
2040 class InteractiveShellABC(object):
2021 """An abstract base class for InteractiveShell."""
2041 """An abstract base class for InteractiveShell."""
2022 __metaclass__ = abc.ABCMeta
2042 __metaclass__ = abc.ABCMeta
2023
2043
2024 InteractiveShellABC.register(InteractiveShell)
2044 InteractiveShellABC.register(InteractiveShell)
@@ -1,541 +1,523 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.inputlist import InputList
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
29 from IPython.lib.pylabtools import pylab_activate
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
34 from IPython.utils.traitlets import Int, Str, CBool
35
35
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Utilities
38 # Utilities
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 def get_default_editor():
42 def get_default_editor():
43 try:
43 try:
44 ed = os.environ['EDITOR']
44 ed = os.environ['EDITOR']
45 except KeyError:
45 except KeyError:
46 if os.name == 'posix':
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
48 else:
49 ed = 'notepad' # same in Windows!
49 ed = 'notepad' # same in Windows!
50 return ed
50 return ed
51
51
52
52
53 # store the builtin raw_input globally, and use this always, in case user code
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
55 raw_input_original = raw_input
56
56
57
57
58 class SeparateStr(Str):
59 """A Str subclass to validate separate_in, separate_out, etc.
60
61 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
62 """
63
64 def validate(self, obj, value):
65 if value == '0': value = ''
66 value = value.replace('\\n','\n')
67 return super(SeparateStr, self).validate(obj, value)
68
69
70 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
71 # Main class
59 # Main class
72 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
73
61
74
62
75 class TerminalInteractiveShell(InteractiveShell):
63 class TerminalInteractiveShell(InteractiveShell):
76
64
77 autoedit_syntax = CBool(False, config=True)
65 autoedit_syntax = CBool(False, config=True)
78 autoindent = CBool(True, config=True)
79 banner = Str('')
66 banner = Str('')
80 banner1 = Str(default_banner, config=True)
67 banner1 = Str(default_banner, config=True)
81 banner2 = Str('', config=True)
68 banner2 = Str('', config=True)
82 confirm_exit = CBool(True, config=True)
69 confirm_exit = CBool(True, config=True)
83 # This display_banner only controls whether or not self.show_banner()
70 # This display_banner only controls whether or not self.show_banner()
84 # is called when mainloop/interact are called. The default is False
71 # is called when mainloop/interact are called. The default is False
85 # because for the terminal based application, the banner behavior
72 # because for the terminal based application, the banner behavior
86 # is controlled by Global.display_banner, which IPythonApp looks at
73 # is controlled by Global.display_banner, which IPythonApp looks at
87 # to determine if *it* should call show_banner() by hand or not.
74 # to determine if *it* should call show_banner() by hand or not.
88 display_banner = CBool(False) # This isn't configurable!
75 display_banner = CBool(False) # This isn't configurable!
89 embedded = CBool(False)
76 embedded = CBool(False)
90 embedded_active = CBool(False)
77 embedded_active = CBool(False)
91 editor = Str(get_default_editor(), config=True)
78 editor = Str(get_default_editor(), config=True)
92 exit_now = CBool(False)
79 exit_now = CBool(False)
93 pager = Str('less', config=True)
80 pager = Str('less', config=True)
94
81
95 screen_length = Int(0, config=True)
82 screen_length = Int(0, config=True)
96
97 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
98 separate_in = SeparateStr('\n', config=True)
99 separate_out = SeparateStr('', config=True)
100 separate_out2 = SeparateStr('', config=True)
101 term_title = CBool(False, config=True)
83 term_title = CBool(False, config=True)
102
84
103 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 def __init__(self, config=None, ipython_dir=None, user_ns=None,
104 user_global_ns=None, custom_exceptions=((),None),
86 user_global_ns=None, custom_exceptions=((),None),
105 usage=None, banner1=None, banner2=None,
87 usage=None, banner1=None, banner2=None,
106 display_banner=None):
88 display_banner=None):
107
89
108 super(TerminalInteractiveShell, self).__init__(
90 super(TerminalInteractiveShell, self).__init__(
109 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
110 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
111 )
93 )
112 self.init_term_title()
94 self.init_term_title()
113 self.init_usage(usage)
95 self.init_usage(usage)
114 self.init_banner(banner1, banner2, display_banner)
96 self.init_banner(banner1, banner2, display_banner)
115
97
116 #-------------------------------------------------------------------------
98 #-------------------------------------------------------------------------
117 # Things related to the terminal
99 # Things related to the terminal
118 #-------------------------------------------------------------------------
100 #-------------------------------------------------------------------------
119
101
120 @property
102 @property
121 def usable_screen_length(self):
103 def usable_screen_length(self):
122 if self.screen_length == 0:
104 if self.screen_length == 0:
123 return 0
105 return 0
124 else:
106 else:
125 num_lines_bot = self.separate_in.count('\n')+1
107 num_lines_bot = self.separate_in.count('\n')+1
126 return self.screen_length - num_lines_bot
108 return self.screen_length - num_lines_bot
127
109
128 def init_term_title(self):
110 def init_term_title(self):
129 # Enable or disable the terminal title.
111 # Enable or disable the terminal title.
130 if self.term_title:
112 if self.term_title:
131 toggle_set_term_title(True)
113 toggle_set_term_title(True)
132 set_term_title('IPython: ' + abbrev_cwd())
114 set_term_title('IPython: ' + abbrev_cwd())
133 else:
115 else:
134 toggle_set_term_title(False)
116 toggle_set_term_title(False)
135
117
136 #-------------------------------------------------------------------------
118 #-------------------------------------------------------------------------
137 # Things related to the banner and usage
119 # Things related to the banner and usage
138 #-------------------------------------------------------------------------
120 #-------------------------------------------------------------------------
139
121
140 def _banner1_changed(self):
122 def _banner1_changed(self):
141 self.compute_banner()
123 self.compute_banner()
142
124
143 def _banner2_changed(self):
125 def _banner2_changed(self):
144 self.compute_banner()
126 self.compute_banner()
145
127
146 def _term_title_changed(self, name, new_value):
128 def _term_title_changed(self, name, new_value):
147 self.init_term_title()
129 self.init_term_title()
148
130
149 def init_banner(self, banner1, banner2, display_banner):
131 def init_banner(self, banner1, banner2, display_banner):
150 if banner1 is not None:
132 if banner1 is not None:
151 self.banner1 = banner1
133 self.banner1 = banner1
152 if banner2 is not None:
134 if banner2 is not None:
153 self.banner2 = banner2
135 self.banner2 = banner2
154 if display_banner is not None:
136 if display_banner is not None:
155 self.display_banner = display_banner
137 self.display_banner = display_banner
156 self.compute_banner()
138 self.compute_banner()
157
139
158 def show_banner(self, banner=None):
140 def show_banner(self, banner=None):
159 if banner is None:
141 if banner is None:
160 banner = self.banner
142 banner = self.banner
161 self.write(banner)
143 self.write(banner)
162
144
163 def compute_banner(self):
145 def compute_banner(self):
164 self.banner = self.banner1 + '\n'
146 self.banner = self.banner1 + '\n'
165 if self.profile:
147 if self.profile:
166 self.banner += '\nIPython profile: %s\n' % self.profile
148 self.banner += '\nIPython profile: %s\n' % self.profile
167 if self.banner2:
149 if self.banner2:
168 self.banner += '\n' + self.banner2 + '\n'
150 self.banner += '\n' + self.banner2 + '\n'
169
151
170 def init_usage(self, usage=None):
152 def init_usage(self, usage=None):
171 if usage is None:
153 if usage is None:
172 self.usage = interactive_usage
154 self.usage = interactive_usage
173 else:
155 else:
174 self.usage = usage
156 self.usage = usage
175
157
176 #-------------------------------------------------------------------------
158 #-------------------------------------------------------------------------
177 # Mainloop and code execution logic
159 # Mainloop and code execution logic
178 #-------------------------------------------------------------------------
160 #-------------------------------------------------------------------------
179
161
180 def mainloop(self, display_banner=None):
162 def mainloop(self, display_banner=None):
181 """Start the mainloop.
163 """Start the mainloop.
182
164
183 If an optional banner argument is given, it will override the
165 If an optional banner argument is given, it will override the
184 internally created default banner.
166 internally created default banner.
185 """
167 """
186
168
187 with nested(self.builtin_trap, self.display_trap):
169 with nested(self.builtin_trap, self.display_trap):
188
170
189 # if you run stuff with -c <cmd>, raw hist is not updated
171 # if you run stuff with -c <cmd>, raw hist is not updated
190 # ensure that it's in sync
172 # ensure that it's in sync
191 if len(self.input_hist) != len (self.input_hist_raw):
173 if len(self.input_hist) != len (self.input_hist_raw):
192 self.input_hist_raw = InputList(self.input_hist)
174 self.input_hist_raw = InputList(self.input_hist)
193
175
194 while 1:
176 while 1:
195 try:
177 try:
196 self.interact(display_banner=display_banner)
178 self.interact(display_banner=display_banner)
197 #self.interact_with_readline()
179 #self.interact_with_readline()
198 # XXX for testing of a readline-decoupled repl loop, call
180 # XXX for testing of a readline-decoupled repl loop, call
199 # interact_with_readline above
181 # interact_with_readline above
200 break
182 break
201 except KeyboardInterrupt:
183 except KeyboardInterrupt:
202 # this should not be necessary, but KeyboardInterrupt
184 # this should not be necessary, but KeyboardInterrupt
203 # handling seems rather unpredictable...
185 # handling seems rather unpredictable...
204 self.write("\nKeyboardInterrupt in interact()\n")
186 self.write("\nKeyboardInterrupt in interact()\n")
205
187
206 def interact(self, display_banner=None):
188 def interact(self, display_banner=None):
207 """Closely emulate the interactive Python console."""
189 """Closely emulate the interactive Python console."""
208
190
209 # batch run -> do not interact
191 # batch run -> do not interact
210 if self.exit_now:
192 if self.exit_now:
211 return
193 return
212
194
213 if display_banner is None:
195 if display_banner is None:
214 display_banner = self.display_banner
196 display_banner = self.display_banner
215 if display_banner:
197 if display_banner:
216 self.show_banner()
198 self.show_banner()
217
199
218 more = 0
200 more = 0
219
201
220 # Mark activity in the builtins
202 # Mark activity in the builtins
221 __builtin__.__dict__['__IPYTHON__active'] += 1
203 __builtin__.__dict__['__IPYTHON__active'] += 1
222
204
223 if self.has_readline:
205 if self.has_readline:
224 self.readline_startup_hook(self.pre_readline)
206 self.readline_startup_hook(self.pre_readline)
225 # exit_now is set by a call to %Exit or %Quit, through the
207 # exit_now is set by a call to %Exit or %Quit, through the
226 # ask_exit callback.
208 # ask_exit callback.
227
209
228 while not self.exit_now:
210 while not self.exit_now:
229 self.hooks.pre_prompt_hook()
211 self.hooks.pre_prompt_hook()
230 if more:
212 if more:
231 try:
213 try:
232 prompt = self.hooks.generate_prompt(True)
214 prompt = self.hooks.generate_prompt(True)
233 except:
215 except:
234 self.showtraceback()
216 self.showtraceback()
235 if self.autoindent:
217 if self.autoindent:
236 self.rl_do_indent = True
218 self.rl_do_indent = True
237
219
238 else:
220 else:
239 try:
221 try:
240 prompt = self.hooks.generate_prompt(False)
222 prompt = self.hooks.generate_prompt(False)
241 except:
223 except:
242 self.showtraceback()
224 self.showtraceback()
243 try:
225 try:
244 line = self.raw_input(prompt, more)
226 line = self.raw_input(prompt, more)
245 if self.exit_now:
227 if self.exit_now:
246 # quick exit on sys.std[in|out] close
228 # quick exit on sys.std[in|out] close
247 break
229 break
248 if self.autoindent:
230 if self.autoindent:
249 self.rl_do_indent = False
231 self.rl_do_indent = False
250
232
251 except KeyboardInterrupt:
233 except KeyboardInterrupt:
252 #double-guard against keyboardinterrupts during kbdint handling
234 #double-guard against keyboardinterrupts during kbdint handling
253 try:
235 try:
254 self.write('\nKeyboardInterrupt\n')
236 self.write('\nKeyboardInterrupt\n')
255 self.resetbuffer()
237 self.resetbuffer()
256 # keep cache in sync with the prompt counter:
238 # keep cache in sync with the prompt counter:
257 self.outputcache.prompt_count -= 1
239 self.outputcache.prompt_count -= 1
258
240
259 if self.autoindent:
241 if self.autoindent:
260 self.indent_current_nsp = 0
242 self.indent_current_nsp = 0
261 more = 0
243 more = 0
262 except KeyboardInterrupt:
244 except KeyboardInterrupt:
263 pass
245 pass
264 except EOFError:
246 except EOFError:
265 if self.autoindent:
247 if self.autoindent:
266 self.rl_do_indent = False
248 self.rl_do_indent = False
267 if self.has_readline:
249 if self.has_readline:
268 self.readline_startup_hook(None)
250 self.readline_startup_hook(None)
269 self.write('\n')
251 self.write('\n')
270 self.exit()
252 self.exit()
271 except bdb.BdbQuit:
253 except bdb.BdbQuit:
272 warn('The Python debugger has exited with a BdbQuit exception.\n'
254 warn('The Python debugger has exited with a BdbQuit exception.\n'
273 'Because of how pdb handles the stack, it is impossible\n'
255 'Because of how pdb handles the stack, it is impossible\n'
274 'for IPython to properly format this particular exception.\n'
256 'for IPython to properly format this particular exception.\n'
275 'IPython will resume normal operation.')
257 'IPython will resume normal operation.')
276 except:
258 except:
277 # exceptions here are VERY RARE, but they can be triggered
259 # exceptions here are VERY RARE, but they can be triggered
278 # asynchronously by signal handlers, for example.
260 # asynchronously by signal handlers, for example.
279 self.showtraceback()
261 self.showtraceback()
280 else:
262 else:
281 more = self.push_line(line)
263 more = self.push_line(line)
282 if (self.SyntaxTB.last_syntax_error and
264 if (self.SyntaxTB.last_syntax_error and
283 self.autoedit_syntax):
265 self.autoedit_syntax):
284 self.edit_syntax_error()
266 self.edit_syntax_error()
285
267
286 # We are off again...
268 # We are off again...
287 __builtin__.__dict__['__IPYTHON__active'] -= 1
269 __builtin__.__dict__['__IPYTHON__active'] -= 1
288
270
289 # Turn off the exit flag, so the mainloop can be restarted if desired
271 # Turn off the exit flag, so the mainloop can be restarted if desired
290 self.exit_now = False
272 self.exit_now = False
291
273
292 def raw_input(self,prompt='',continue_prompt=False):
274 def raw_input(self,prompt='',continue_prompt=False):
293 """Write a prompt and read a line.
275 """Write a prompt and read a line.
294
276
295 The returned line does not include the trailing newline.
277 The returned line does not include the trailing newline.
296 When the user enters the EOF key sequence, EOFError is raised.
278 When the user enters the EOF key sequence, EOFError is raised.
297
279
298 Optional inputs:
280 Optional inputs:
299
281
300 - prompt(''): a string to be printed to prompt the user.
282 - prompt(''): a string to be printed to prompt the user.
301
283
302 - continue_prompt(False): whether this line is the first one or a
284 - continue_prompt(False): whether this line is the first one or a
303 continuation in a sequence of inputs.
285 continuation in a sequence of inputs.
304 """
286 """
305 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
287 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
306
288
307 # Code run by the user may have modified the readline completer state.
289 # Code run by the user may have modified the readline completer state.
308 # We must ensure that our completer is back in place.
290 # We must ensure that our completer is back in place.
309
291
310 if self.has_readline:
292 if self.has_readline:
311 self.set_completer()
293 self.set_completer()
312
294
313 try:
295 try:
314 line = raw_input_original(prompt).decode(self.stdin_encoding)
296 line = raw_input_original(prompt).decode(self.stdin_encoding)
315 except ValueError:
297 except ValueError:
316 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
298 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
317 " or sys.stdout.close()!\nExiting IPython!")
299 " or sys.stdout.close()!\nExiting IPython!")
318 self.ask_exit()
300 self.ask_exit()
319 return ""
301 return ""
320
302
321 # Try to be reasonably smart about not re-indenting pasted input more
303 # Try to be reasonably smart about not re-indenting pasted input more
322 # than necessary. We do this by trimming out the auto-indent initial
304 # than necessary. We do this by trimming out the auto-indent initial
323 # spaces, if the user's actual input started itself with whitespace.
305 # spaces, if the user's actual input started itself with whitespace.
324 #debugx('self.buffer[-1]')
306 #debugx('self.buffer[-1]')
325
307
326 if self.autoindent:
308 if self.autoindent:
327 if num_ini_spaces(line) > self.indent_current_nsp:
309 if num_ini_spaces(line) > self.indent_current_nsp:
328 line = line[self.indent_current_nsp:]
310 line = line[self.indent_current_nsp:]
329 self.indent_current_nsp = 0
311 self.indent_current_nsp = 0
330
312
331 # store the unfiltered input before the user has any chance to modify
313 # store the unfiltered input before the user has any chance to modify
332 # it.
314 # it.
333 if line.strip():
315 if line.strip():
334 if continue_prompt:
316 if continue_prompt:
335 self.input_hist_raw[-1] += '%s\n' % line
317 self.input_hist_raw[-1] += '%s\n' % line
336 if self.has_readline and self.readline_use:
318 if self.has_readline and self.readline_use:
337 try:
319 try:
338 histlen = self.readline.get_current_history_length()
320 histlen = self.readline.get_current_history_length()
339 if histlen > 1:
321 if histlen > 1:
340 newhist = self.input_hist_raw[-1].rstrip()
322 newhist = self.input_hist_raw[-1].rstrip()
341 self.readline.remove_history_item(histlen-1)
323 self.readline.remove_history_item(histlen-1)
342 self.readline.replace_history_item(histlen-2,
324 self.readline.replace_history_item(histlen-2,
343 newhist.encode(self.stdin_encoding))
325 newhist.encode(self.stdin_encoding))
344 except AttributeError:
326 except AttributeError:
345 pass # re{move,place}_history_item are new in 2.4.
327 pass # re{move,place}_history_item are new in 2.4.
346 else:
328 else:
347 self.input_hist_raw.append('%s\n' % line)
329 self.input_hist_raw.append('%s\n' % line)
348 # only entries starting at first column go to shadow history
330 # only entries starting at first column go to shadow history
349 if line.lstrip() == line:
331 if line.lstrip() == line:
350 self.shadowhist.add(line.strip())
332 self.shadowhist.add(line.strip())
351 elif not continue_prompt:
333 elif not continue_prompt:
352 self.input_hist_raw.append('\n')
334 self.input_hist_raw.append('\n')
353 try:
335 try:
354 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
336 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
355 except:
337 except:
356 # blanket except, in case a user-defined prefilter crashes, so it
338 # blanket except, in case a user-defined prefilter crashes, so it
357 # can't take all of ipython with it.
339 # can't take all of ipython with it.
358 self.showtraceback()
340 self.showtraceback()
359 return ''
341 return ''
360 else:
342 else:
361 return lineout
343 return lineout
362
344
363 # TODO: The following three methods are an early attempt to refactor
345 # TODO: The following three methods are an early attempt to refactor
364 # the main code execution logic. We don't use them, but they may be
346 # the main code execution logic. We don't use them, but they may be
365 # helpful when we refactor the code execution logic further.
347 # helpful when we refactor the code execution logic further.
366 # def interact_prompt(self):
348 # def interact_prompt(self):
367 # """ Print the prompt (in read-eval-print loop)
349 # """ Print the prompt (in read-eval-print loop)
368 #
350 #
369 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
351 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
370 # used in standard IPython flow.
352 # used in standard IPython flow.
371 # """
353 # """
372 # if self.more:
354 # if self.more:
373 # try:
355 # try:
374 # prompt = self.hooks.generate_prompt(True)
356 # prompt = self.hooks.generate_prompt(True)
375 # except:
357 # except:
376 # self.showtraceback()
358 # self.showtraceback()
377 # if self.autoindent:
359 # if self.autoindent:
378 # self.rl_do_indent = True
360 # self.rl_do_indent = True
379 #
361 #
380 # else:
362 # else:
381 # try:
363 # try:
382 # prompt = self.hooks.generate_prompt(False)
364 # prompt = self.hooks.generate_prompt(False)
383 # except:
365 # except:
384 # self.showtraceback()
366 # self.showtraceback()
385 # self.write(prompt)
367 # self.write(prompt)
386 #
368 #
387 # def interact_handle_input(self,line):
369 # def interact_handle_input(self,line):
388 # """ Handle the input line (in read-eval-print loop)
370 # """ Handle the input line (in read-eval-print loop)
389 #
371 #
390 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
391 # used in standard IPython flow.
373 # used in standard IPython flow.
392 # """
374 # """
393 # if line.lstrip() == line:
375 # if line.lstrip() == line:
394 # self.shadowhist.add(line.strip())
376 # self.shadowhist.add(line.strip())
395 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
377 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
396 #
378 #
397 # if line.strip():
379 # if line.strip():
398 # if self.more:
380 # if self.more:
399 # self.input_hist_raw[-1] += '%s\n' % line
381 # self.input_hist_raw[-1] += '%s\n' % line
400 # else:
382 # else:
401 # self.input_hist_raw.append('%s\n' % line)
383 # self.input_hist_raw.append('%s\n' % line)
402 #
384 #
403 #
385 #
404 # self.more = self.push_line(lineout)
386 # self.more = self.push_line(lineout)
405 # if (self.SyntaxTB.last_syntax_error and
387 # if (self.SyntaxTB.last_syntax_error and
406 # self.autoedit_syntax):
388 # self.autoedit_syntax):
407 # self.edit_syntax_error()
389 # self.edit_syntax_error()
408 #
390 #
409 # def interact_with_readline(self):
391 # def interact_with_readline(self):
410 # """ Demo of using interact_handle_input, interact_prompt
392 # """ Demo of using interact_handle_input, interact_prompt
411 #
393 #
412 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
394 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
413 # it should work like this.
395 # it should work like this.
414 # """
396 # """
415 # self.readline_startup_hook(self.pre_readline)
397 # self.readline_startup_hook(self.pre_readline)
416 # while not self.exit_now:
398 # while not self.exit_now:
417 # self.interact_prompt()
399 # self.interact_prompt()
418 # if self.more:
400 # if self.more:
419 # self.rl_do_indent = True
401 # self.rl_do_indent = True
420 # else:
402 # else:
421 # self.rl_do_indent = False
403 # self.rl_do_indent = False
422 # line = raw_input_original().decode(self.stdin_encoding)
404 # line = raw_input_original().decode(self.stdin_encoding)
423 # self.interact_handle_input(line)
405 # self.interact_handle_input(line)
424
406
425 #-------------------------------------------------------------------------
407 #-------------------------------------------------------------------------
426 # Methods to support auto-editing of SyntaxErrors.
408 # Methods to support auto-editing of SyntaxErrors.
427 #-------------------------------------------------------------------------
409 #-------------------------------------------------------------------------
428
410
429 def edit_syntax_error(self):
411 def edit_syntax_error(self):
430 """The bottom half of the syntax error handler called in the main loop.
412 """The bottom half of the syntax error handler called in the main loop.
431
413
432 Loop until syntax error is fixed or user cancels.
414 Loop until syntax error is fixed or user cancels.
433 """
415 """
434
416
435 while self.SyntaxTB.last_syntax_error:
417 while self.SyntaxTB.last_syntax_error:
436 # copy and clear last_syntax_error
418 # copy and clear last_syntax_error
437 err = self.SyntaxTB.clear_err_state()
419 err = self.SyntaxTB.clear_err_state()
438 if not self._should_recompile(err):
420 if not self._should_recompile(err):
439 return
421 return
440 try:
422 try:
441 # may set last_syntax_error again if a SyntaxError is raised
423 # may set last_syntax_error again if a SyntaxError is raised
442 self.safe_execfile(err.filename,self.user_ns)
424 self.safe_execfile(err.filename,self.user_ns)
443 except:
425 except:
444 self.showtraceback()
426 self.showtraceback()
445 else:
427 else:
446 try:
428 try:
447 f = file(err.filename)
429 f = file(err.filename)
448 try:
430 try:
449 # This should be inside a display_trap block and I
431 # This should be inside a display_trap block and I
450 # think it is.
432 # think it is.
451 sys.displayhook(f.read())
433 sys.displayhook(f.read())
452 finally:
434 finally:
453 f.close()
435 f.close()
454 except:
436 except:
455 self.showtraceback()
437 self.showtraceback()
456
438
457 def _should_recompile(self,e):
439 def _should_recompile(self,e):
458 """Utility routine for edit_syntax_error"""
440 """Utility routine for edit_syntax_error"""
459
441
460 if e.filename in ('<ipython console>','<input>','<string>',
442 if e.filename in ('<ipython console>','<input>','<string>',
461 '<console>','<BackgroundJob compilation>',
443 '<console>','<BackgroundJob compilation>',
462 None):
444 None):
463
445
464 return False
446 return False
465 try:
447 try:
466 if (self.autoedit_syntax and
448 if (self.autoedit_syntax and
467 not self.ask_yes_no('Return to editor to correct syntax error? '
449 not self.ask_yes_no('Return to editor to correct syntax error? '
468 '[Y/n] ','y')):
450 '[Y/n] ','y')):
469 return False
451 return False
470 except EOFError:
452 except EOFError:
471 return False
453 return False
472
454
473 def int0(x):
455 def int0(x):
474 try:
456 try:
475 return int(x)
457 return int(x)
476 except TypeError:
458 except TypeError:
477 return 0
459 return 0
478 # always pass integer line and offset values to editor hook
460 # always pass integer line and offset values to editor hook
479 try:
461 try:
480 self.hooks.fix_error_editor(e.filename,
462 self.hooks.fix_error_editor(e.filename,
481 int0(e.lineno),int0(e.offset),e.msg)
463 int0(e.lineno),int0(e.offset),e.msg)
482 except TryNext:
464 except TryNext:
483 warn('Could not open editor')
465 warn('Could not open editor')
484 return False
466 return False
485 return True
467 return True
486
468
487 #-------------------------------------------------------------------------
469 #-------------------------------------------------------------------------
488 # Things related to GUI support and pylab
470 # Things related to GUI support and pylab
489 #-------------------------------------------------------------------------
471 #-------------------------------------------------------------------------
490
472
491 def enable_pylab(self, gui=None):
473 def enable_pylab(self, gui=None):
492 """Activate pylab support at runtime.
474 """Activate pylab support at runtime.
493
475
494 This turns on support for matplotlib, preloads into the interactive
476 This turns on support for matplotlib, preloads into the interactive
495 namespace all of numpy and pylab, and configures IPython to correcdtly
477 namespace all of numpy and pylab, and configures IPython to correcdtly
496 interact with the GUI event loop. The GUI backend to be used can be
478 interact with the GUI event loop. The GUI backend to be used can be
497 optionally selected with the optional :param:`gui` argument.
479 optionally selected with the optional :param:`gui` argument.
498
480
499 Parameters
481 Parameters
500 ----------
482 ----------
501 gui : optional, string
483 gui : optional, string
502
484
503 If given, dictates the choice of matplotlib GUI backend to use
485 If given, dictates the choice of matplotlib GUI backend to use
504 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
486 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
505 'gtk'), otherwise we use the default chosen by matplotlib (as
487 'gtk'), otherwise we use the default chosen by matplotlib (as
506 dictated by the matplotlib build-time options plus the user's
488 dictated by the matplotlib build-time options plus the user's
507 matplotlibrc configuration file).
489 matplotlibrc configuration file).
508 """
490 """
509 # We want to prevent the loading of pylab to pollute the user's
491 # We want to prevent the loading of pylab to pollute the user's
510 # namespace as shown by the %who* magics, so we execute the activation
492 # namespace as shown by the %who* magics, so we execute the activation
511 # code in an empty namespace, and we update *both* user_ns and
493 # code in an empty namespace, and we update *both* user_ns and
512 # user_ns_hidden with this information.
494 # user_ns_hidden with this information.
513 ns = {}
495 ns = {}
514 gui = pylab_activate(ns, gui)
496 gui = pylab_activate(ns, gui)
515 self.user_ns.update(ns)
497 self.user_ns.update(ns)
516 self.user_ns_hidden.update(ns)
498 self.user_ns_hidden.update(ns)
517 # Now we must activate the gui pylab wants to use, and fix %run to take
499 # Now we must activate the gui pylab wants to use, and fix %run to take
518 # plot updates into account
500 # plot updates into account
519 enable_gui(gui)
501 enable_gui(gui)
520 self.magic_run = self._pylab_magic_run
502 self.magic_run = self._pylab_magic_run
521
503
522 #-------------------------------------------------------------------------
504 #-------------------------------------------------------------------------
523 # Things related to exiting
505 # Things related to exiting
524 #-------------------------------------------------------------------------
506 #-------------------------------------------------------------------------
525
507
526 def ask_exit(self):
508 def ask_exit(self):
527 """ Ask the shell to exit. Can be overiden and used as a callback. """
509 """ Ask the shell to exit. Can be overiden and used as a callback. """
528 self.exit_now = True
510 self.exit_now = True
529
511
530 def exit(self):
512 def exit(self):
531 """Handle interactive exit.
513 """Handle interactive exit.
532
514
533 This method calls the ask_exit callback."""
515 This method calls the ask_exit callback."""
534 if self.confirm_exit:
516 if self.confirm_exit:
535 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
517 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
536 self.ask_exit()
518 self.ask_exit()
537 else:
519 else:
538 self.ask_exit()
520 self.ask_exit()
539
521
540
522
541 InteractiveShellABC.register(TerminalInteractiveShell)
523 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,665 +1,665 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 """
12 """
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2010 The IPython Development Team
15 # Copyright (C) 2008-2010 The IPython Development Team
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 from __future__ import absolute_import
25 from __future__ import absolute_import
26
26
27 import logging
27 import logging
28 import os
28 import os
29 import sys
29 import sys
30
30
31 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.crashhandler import CrashHandler
32 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 from IPython.config.loader import (
35 from IPython.config.loader import (
36 Config,
36 Config,
37 PyFileConfigLoader
37 PyFileConfigLoader
38 )
38 )
39 from IPython.lib import inputhook
39 from IPython.lib import inputhook
40 from IPython.utils.path import filefind, get_ipython_dir
40 from IPython.utils.path import filefind, get_ipython_dir
41 from IPython.core import usage
41 from IPython.core import usage
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Globals, utilities and helpers
44 # Globals, utilities and helpers
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 #: The default config file name for this application.
47 #: The default config file name for this application.
48 default_config_file_name = u'ipython_config.py'
48 default_config_file_name = u'ipython_config.py'
49
49
50
50
51 class IPAppConfigLoader(BaseAppConfigLoader):
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
52
53 def _add_arguments(self):
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
55 paa = self.parser.add_argument
56 paa('-p',
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
57 '--profile', dest='Global.profile', type=unicode,
58 help=
58 help=
59 """The string name of the ipython profile to be used. Assume that your
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
66 metavar='Global.profile')
67 paa('--config-file',
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
68 dest='Global.config_file', type=unicode,
69 help=
69 help=
70 """Set the config file name to override default. Normally IPython
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
74 loaded at all).""",
75 metavar='Global.config_file')
75 metavar='Global.config_file')
76 paa('--autocall',
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
77 dest='InteractiveShell.autocall', type=int,
78 help=
78 help=
79 """Make IPython automatically call any callable object even if you
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
87 paa('--autoindent',
88 action='store_true', dest='TerminalInteractiveShell.autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
90 paa('--no-autoindent',
91 action='store_false', dest='TerminalInteractiveShell.autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
92 help='Turn off autoindenting.')
93 paa('--automagic',
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
97 IPython prompt for more information.""")
98 paa('--no-automagic',
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
101 paa('--autoedit-syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
115 help=
116 """Set the size of the output cache. The default is 1000, you can
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
123 paa('--classic',
124 action='store_true', dest='Global.classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
132 help=
133 """IPython can display information about objects via a set of func-
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
141 inter- actively for testing.""")
142 paa('--no-color-info',
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
145 paa('--confirm-exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 help=
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
151 paa('--no-confirm-exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
164 by default [which means that you have both normal reload() and
165 dreload()].""")
165 dreload()].""")
166 paa('--no-deep-reload',
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
169 paa('--editor',
170 type=str, dest='TerminalInteractiveShell.editor',
170 type=str, dest='TerminalInteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='TerminalInteractiveShell.editor')
172 metavar='TerminalInteractiveShell.editor')
173 paa('--log','-l',
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
190 paa('--pprint',
191 action='store_true', dest='InteractiveShell.pprint',
191 action='store_true', dest='InteractiveShell.pprint',
192 help="Enable auto pretty printing of results.")
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
193 paa('--no-pprint',
194 action='store_false', dest='InteractiveShell.pprint',
194 action='store_false', dest='InteractiveShell.pprint',
195 help="Disable auto auto pretty printing of results.")
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
221 paa('--quick',
222 action='store_true', dest='Global.quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
223 help="Enable quick startup with no config files.")
224 paa('--readline',
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
230 paa('--screen-length','-sl',
231 type=int, dest='TerminalInteractiveShell.screen_length',
231 type=int, dest='TerminalInteractiveShell.screen_length',
232 help=
232 help=
233 """Number of lines of your screen, used to control printing of very
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
241 default.""",
242 metavar='TerminalInteractiveShell.screen_length')
242 metavar='TerminalInteractiveShell.screen_length')
243 paa('--separate-in','-si',
243 paa('--separate-in','-si',
244 type=str, dest='TerminalInteractiveShell.separate_in',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='TerminalInteractiveShell.separate_in')
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
247 paa('--separate-out','-so',
248 type=str, dest='TerminalInteractiveShell.separate_out',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='TerminalInteractiveShell.separate_out')
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
251 paa('--separate-out2','-so2',
252 type=str, dest='TerminalInteractiveShell.separate_out2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='TerminalInteractiveShell.separate_out2')
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
258 paa('--term-title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
261 paa('--no-term-title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
276 it more than once).
277 """,
277 """,
278 metavar='InteractiveShell.xmode')
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
282 metavar='Global.extra_extension')
283 paa('-c',
283 paa('-c',
284 type=str, dest='Global.code_to_run',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
286 metavar='Global.code_to_run')
287 paa('-i',
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
288 action='store_true', dest='Global.force_interact',
289 help=
289 help=
290 "If running code from the command line, become interactive afterwards.")
290 "If running code from the command line, become interactive afterwards.")
291
291
292 # Options to start with GUI control enabled from the beginning
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
293 paa('--gui',
294 type=str, dest='Global.gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
307 action='store_true', dest='Global.wthread',
308 help=
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
311 action='store_true', dest='Global.q4thread',
312 help=
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
316 action='store_true', dest='Global.gthread',
317 help=
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319
319
320
320
321 #-----------------------------------------------------------------------------
321 #-----------------------------------------------------------------------------
322 # Crash handler for this application
322 # Crash handler for this application
323 #-----------------------------------------------------------------------------
323 #-----------------------------------------------------------------------------
324
324
325
325
326 _message_template = """\
326 _message_template = """\
327 Oops, $self.app_name crashed. We do our best to make it stable, but...
327 Oops, $self.app_name crashed. We do our best to make it stable, but...
328
328
329 A crash report was automatically generated with the following information:
329 A crash report was automatically generated with the following information:
330 - A verbatim copy of the crash traceback.
330 - A verbatim copy of the crash traceback.
331 - A copy of your input history during this session.
331 - A copy of your input history during this session.
332 - Data on your current $self.app_name configuration.
332 - Data on your current $self.app_name configuration.
333
333
334 It was left in the file named:
334 It was left in the file named:
335 \t'$self.crash_report_fname'
335 \t'$self.crash_report_fname'
336 If you can email this file to the developers, the information in it will help
336 If you can email this file to the developers, the information in it will help
337 them in understanding and correcting the problem.
337 them in understanding and correcting the problem.
338
338
339 You can mail it to: $self.contact_name at $self.contact_email
339 You can mail it to: $self.contact_name at $self.contact_email
340 with the subject '$self.app_name Crash Report'.
340 with the subject '$self.app_name Crash Report'.
341
341
342 If you want to do it now, the following command will work (under Unix):
342 If you want to do it now, the following command will work (under Unix):
343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
344
344
345 To ensure accurate tracking of this issue, please file a report about it at:
345 To ensure accurate tracking of this issue, please file a report about it at:
346 $self.bug_tracker
346 $self.bug_tracker
347 """
347 """
348
348
349 class IPAppCrashHandler(CrashHandler):
349 class IPAppCrashHandler(CrashHandler):
350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
351
351
352 message_template = _message_template
352 message_template = _message_template
353
353
354 def __init__(self, app):
354 def __init__(self, app):
355 contact_name = release.authors['Fernando'][0]
355 contact_name = release.authors['Fernando'][0]
356 contact_email = release.authors['Fernando'][1]
356 contact_email = release.authors['Fernando'][1]
357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
358 super(IPAppCrashHandler,self).__init__(
358 super(IPAppCrashHandler,self).__init__(
359 app, contact_name, contact_email, bug_tracker
359 app, contact_name, contact_email, bug_tracker
360 )
360 )
361
361
362 def make_report(self,traceback):
362 def make_report(self,traceback):
363 """Return a string containing a crash report."""
363 """Return a string containing a crash report."""
364
364
365 sec_sep = self.section_sep
365 sec_sep = self.section_sep
366 # Start with parent report
366 # Start with parent report
367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
368 # Add interactive-specific info we may have
368 # Add interactive-specific info we may have
369 rpt_add = report.append
369 rpt_add = report.append
370 try:
370 try:
371 rpt_add(sec_sep+"History of session input:")
371 rpt_add(sec_sep+"History of session input:")
372 for line in self.app.shell.user_ns['_ih']:
372 for line in self.app.shell.user_ns['_ih']:
373 rpt_add(line)
373 rpt_add(line)
374 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 rpt_add('\n*** Last line of input (may not be in above history):\n')
375 rpt_add(self.app.shell._last_input_line+'\n')
375 rpt_add(self.app.shell._last_input_line+'\n')
376 except:
376 except:
377 pass
377 pass
378
378
379 return ''.join(report)
379 return ''.join(report)
380
380
381
381
382 #-----------------------------------------------------------------------------
382 #-----------------------------------------------------------------------------
383 # Main classes and functions
383 # Main classes and functions
384 #-----------------------------------------------------------------------------
384 #-----------------------------------------------------------------------------
385
385
386 class IPythonApp(Application):
386 class IPythonApp(Application):
387 name = u'ipython'
387 name = u'ipython'
388 #: argparse formats better the 'usage' than the 'description' field
388 #: argparse formats better the 'usage' than the 'description' field
389 description = None
389 description = None
390 usage = usage.cl_usage
390 usage = usage.cl_usage
391 command_line_loader = IPAppConfigLoader
391 command_line_loader = IPAppConfigLoader
392 default_config_file_name = default_config_file_name
392 default_config_file_name = default_config_file_name
393 crash_handler_class = IPAppCrashHandler
393 crash_handler_class = IPAppCrashHandler
394
394
395 def create_default_config(self):
395 def create_default_config(self):
396 super(IPythonApp, self).create_default_config()
396 super(IPythonApp, self).create_default_config()
397 # Eliminate multiple lookups
397 # Eliminate multiple lookups
398 Global = self.default_config.Global
398 Global = self.default_config.Global
399
399
400 # Set all default values
400 # Set all default values
401 Global.display_banner = True
401 Global.display_banner = True
402
402
403 # If the -c flag is given or a file is given to run at the cmd line
403 # If the -c flag is given or a file is given to run at the cmd line
404 # like "ipython foo.py", normally we exit without starting the main
404 # like "ipython foo.py", normally we exit without starting the main
405 # loop. The force_interact config variable allows a user to override
405 # loop. The force_interact config variable allows a user to override
406 # this and interact. It is also set by the -i cmd line flag, just
406 # this and interact. It is also set by the -i cmd line flag, just
407 # like Python.
407 # like Python.
408 Global.force_interact = False
408 Global.force_interact = False
409
409
410 # By default always interact by starting the IPython mainloop.
410 # By default always interact by starting the IPython mainloop.
411 Global.interact = True
411 Global.interact = True
412
412
413 # No GUI integration by default
413 # No GUI integration by default
414 Global.gui = False
414 Global.gui = False
415 # Pylab off by default
415 # Pylab off by default
416 Global.pylab = False
416 Global.pylab = False
417
417
418 # Deprecated versions of gui support that used threading, we support
418 # Deprecated versions of gui support that used threading, we support
419 # them just for bacwards compatibility as an alternate spelling for
419 # them just for bacwards compatibility as an alternate spelling for
420 # '--gui X'
420 # '--gui X'
421 Global.qthread = False
421 Global.qthread = False
422 Global.q4thread = False
422 Global.q4thread = False
423 Global.wthread = False
423 Global.wthread = False
424 Global.gthread = False
424 Global.gthread = False
425
425
426 def load_file_config(self):
426 def load_file_config(self):
427 if hasattr(self.command_line_config.Global, 'quick'):
427 if hasattr(self.command_line_config.Global, 'quick'):
428 if self.command_line_config.Global.quick:
428 if self.command_line_config.Global.quick:
429 self.file_config = Config()
429 self.file_config = Config()
430 return
430 return
431 super(IPythonApp, self).load_file_config()
431 super(IPythonApp, self).load_file_config()
432
432
433 def post_load_file_config(self):
433 def post_load_file_config(self):
434 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 if hasattr(self.command_line_config.Global, 'extra_extension'):
435 if not hasattr(self.file_config.Global, 'extensions'):
435 if not hasattr(self.file_config.Global, 'extensions'):
436 self.file_config.Global.extensions = []
436 self.file_config.Global.extensions = []
437 self.file_config.Global.extensions.append(
437 self.file_config.Global.extensions.append(
438 self.command_line_config.Global.extra_extension)
438 self.command_line_config.Global.extra_extension)
439 del self.command_line_config.Global.extra_extension
439 del self.command_line_config.Global.extra_extension
440
440
441 def pre_construct(self):
441 def pre_construct(self):
442 config = self.master_config
442 config = self.master_config
443
443
444 if hasattr(config.Global, 'classic'):
444 if hasattr(config.Global, 'classic'):
445 if config.Global.classic:
445 if config.Global.classic:
446 config.InteractiveShell.cache_size = 0
446 config.InteractiveShell.cache_size = 0
447 config.InteractiveShell.pprint = 0
447 config.InteractiveShell.pprint = 0
448 config.InteractiveShell.prompt_in1 = '>>> '
448 config.InteractiveShell.prompt_in1 = '>>> '
449 config.InteractiveShell.prompt_in2 = '... '
449 config.InteractiveShell.prompt_in2 = '... '
450 config.InteractiveShell.prompt_out = ''
450 config.InteractiveShell.prompt_out = ''
451 config.TerminalInteractiveShell.separate_in = \
451 config.InteractiveShell.separate_in = \
452 config.TerminalInteractiveShell.separate_out = \
452 config.InteractiveShell.separate_out = \
453 config.TerminalInteractiveShell.separate_out2 = ''
453 config.InteractiveShell.separate_out2 = ''
454 config.InteractiveShell.colors = 'NoColor'
454 config.InteractiveShell.colors = 'NoColor'
455 config.InteractiveShell.xmode = 'Plain'
455 config.InteractiveShell.xmode = 'Plain'
456
456
457 if hasattr(config.Global, 'nosep'):
457 if hasattr(config.Global, 'nosep'):
458 if config.Global.nosep:
458 if config.Global.nosep:
459 config.TerminalInteractiveShell.separate_in = \
459 config.InteractiveShell.separate_in = \
460 config.TerminalInteractiveShell.separate_out = \
460 config.InteractiveShell.separate_out = \
461 config.TerminalInteractiveShell.separate_out2 = ''
461 config.InteractiveShell.separate_out2 = ''
462
462
463 # if there is code of files to run from the cmd line, don't interact
463 # if there is code of files to run from the cmd line, don't interact
464 # unless the -i flag (Global.force_interact) is true.
464 # unless the -i flag (Global.force_interact) is true.
465 code_to_run = config.Global.get('code_to_run','')
465 code_to_run = config.Global.get('code_to_run','')
466 file_to_run = False
466 file_to_run = False
467 if self.extra_args and self.extra_args[0]:
467 if self.extra_args and self.extra_args[0]:
468 file_to_run = True
468 file_to_run = True
469 if file_to_run or code_to_run:
469 if file_to_run or code_to_run:
470 if not config.Global.force_interact:
470 if not config.Global.force_interact:
471 config.Global.interact = False
471 config.Global.interact = False
472
472
473 def construct(self):
473 def construct(self):
474 # I am a little hesitant to put these into InteractiveShell itself.
474 # I am a little hesitant to put these into InteractiveShell itself.
475 # But that might be the place for them
475 # But that might be the place for them
476 sys.path.insert(0, '')
476 sys.path.insert(0, '')
477
477
478 # Create an InteractiveShell instance.
478 # Create an InteractiveShell instance.
479 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
479 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
480
480
481 def post_construct(self):
481 def post_construct(self):
482 """Do actions after construct, but before starting the app."""
482 """Do actions after construct, but before starting the app."""
483 config = self.master_config
483 config = self.master_config
484
484
485 # shell.display_banner should always be False for the terminal
485 # shell.display_banner should always be False for the terminal
486 # based app, because we call shell.show_banner() by hand below
486 # based app, because we call shell.show_banner() by hand below
487 # so the banner shows *before* all extension loading stuff.
487 # so the banner shows *before* all extension loading stuff.
488 self.shell.display_banner = False
488 self.shell.display_banner = False
489 if config.Global.display_banner and \
489 if config.Global.display_banner and \
490 config.Global.interact:
490 config.Global.interact:
491 self.shell.show_banner()
491 self.shell.show_banner()
492
492
493 # Make sure there is a space below the banner.
493 # Make sure there is a space below the banner.
494 if self.log_level <= logging.INFO: print
494 if self.log_level <= logging.INFO: print
495
495
496 # Now a variety of things that happen after the banner is printed.
496 # Now a variety of things that happen after the banner is printed.
497 self._enable_gui_pylab()
497 self._enable_gui_pylab()
498 self._load_extensions()
498 self._load_extensions()
499 self._run_exec_lines()
499 self._run_exec_lines()
500 self._run_exec_files()
500 self._run_exec_files()
501 self._run_cmd_line_code()
501 self._run_cmd_line_code()
502
502
503 def _enable_gui_pylab(self):
503 def _enable_gui_pylab(self):
504 """Enable GUI event loop integration, taking pylab into account."""
504 """Enable GUI event loop integration, taking pylab into account."""
505 Global = self.master_config.Global
505 Global = self.master_config.Global
506
506
507 # Select which gui to use
507 # Select which gui to use
508 if Global.gui:
508 if Global.gui:
509 gui = Global.gui
509 gui = Global.gui
510 # The following are deprecated, but there's likely to be a lot of use
510 # The following are deprecated, but there's likely to be a lot of use
511 # of this form out there, so we might as well support it for now. But
511 # of this form out there, so we might as well support it for now. But
512 # the --gui option above takes precedence.
512 # the --gui option above takes precedence.
513 elif Global.wthread:
513 elif Global.wthread:
514 gui = inputhook.GUI_WX
514 gui = inputhook.GUI_WX
515 elif Global.qthread:
515 elif Global.qthread:
516 gui = inputhook.GUI_QT
516 gui = inputhook.GUI_QT
517 elif Global.gthread:
517 elif Global.gthread:
518 gui = inputhook.GUI_GTK
518 gui = inputhook.GUI_GTK
519 else:
519 else:
520 gui = None
520 gui = None
521
521
522 # Using --pylab will also require gui activation, though which toolkit
522 # Using --pylab will also require gui activation, though which toolkit
523 # to use may be chosen automatically based on mpl configuration.
523 # to use may be chosen automatically based on mpl configuration.
524 if Global.pylab:
524 if Global.pylab:
525 activate = self.shell.enable_pylab
525 activate = self.shell.enable_pylab
526 if Global.pylab == 'auto':
526 if Global.pylab == 'auto':
527 gui = None
527 gui = None
528 else:
528 else:
529 gui = Global.pylab
529 gui = Global.pylab
530 else:
530 else:
531 # Enable only GUI integration, no pylab
531 # Enable only GUI integration, no pylab
532 activate = inputhook.enable_gui
532 activate = inputhook.enable_gui
533
533
534 if gui or Global.pylab:
534 if gui or Global.pylab:
535 try:
535 try:
536 self.log.info("Enabling GUI event loop integration, "
536 self.log.info("Enabling GUI event loop integration, "
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
538 activate(gui)
538 activate(gui)
539 except:
539 except:
540 self.log.warn("Error in enabling GUI event loop integration:")
540 self.log.warn("Error in enabling GUI event loop integration:")
541 self.shell.showtraceback()
541 self.shell.showtraceback()
542
542
543 def _load_extensions(self):
543 def _load_extensions(self):
544 """Load all IPython extensions in Global.extensions.
544 """Load all IPython extensions in Global.extensions.
545
545
546 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 This uses the :meth:`ExtensionManager.load_extensions` to load all
547 the extensions listed in ``self.master_config.Global.extensions``.
547 the extensions listed in ``self.master_config.Global.extensions``.
548 """
548 """
549 try:
549 try:
550 if hasattr(self.master_config.Global, 'extensions'):
550 if hasattr(self.master_config.Global, 'extensions'):
551 self.log.debug("Loading IPython extensions...")
551 self.log.debug("Loading IPython extensions...")
552 extensions = self.master_config.Global.extensions
552 extensions = self.master_config.Global.extensions
553 for ext in extensions:
553 for ext in extensions:
554 try:
554 try:
555 self.log.info("Loading IPython extension: %s" % ext)
555 self.log.info("Loading IPython extension: %s" % ext)
556 self.shell.extension_manager.load_extension(ext)
556 self.shell.extension_manager.load_extension(ext)
557 except:
557 except:
558 self.log.warn("Error in loading extension: %s" % ext)
558 self.log.warn("Error in loading extension: %s" % ext)
559 self.shell.showtraceback()
559 self.shell.showtraceback()
560 except:
560 except:
561 self.log.warn("Unknown error in loading extensions:")
561 self.log.warn("Unknown error in loading extensions:")
562 self.shell.showtraceback()
562 self.shell.showtraceback()
563
563
564 def _run_exec_lines(self):
564 def _run_exec_lines(self):
565 """Run lines of code in Global.exec_lines in the user's namespace."""
565 """Run lines of code in Global.exec_lines in the user's namespace."""
566 try:
566 try:
567 if hasattr(self.master_config.Global, 'exec_lines'):
567 if hasattr(self.master_config.Global, 'exec_lines'):
568 self.log.debug("Running code from Global.exec_lines...")
568 self.log.debug("Running code from Global.exec_lines...")
569 exec_lines = self.master_config.Global.exec_lines
569 exec_lines = self.master_config.Global.exec_lines
570 for line in exec_lines:
570 for line in exec_lines:
571 try:
571 try:
572 self.log.info("Running code in user namespace: %s" %
572 self.log.info("Running code in user namespace: %s" %
573 line)
573 line)
574 self.shell.runlines(line)
574 self.shell.runlines(line)
575 except:
575 except:
576 self.log.warn("Error in executing line in user "
576 self.log.warn("Error in executing line in user "
577 "namespace: %s" % line)
577 "namespace: %s" % line)
578 self.shell.showtraceback()
578 self.shell.showtraceback()
579 except:
579 except:
580 self.log.warn("Unknown error in handling Global.exec_lines:")
580 self.log.warn("Unknown error in handling Global.exec_lines:")
581 self.shell.showtraceback()
581 self.shell.showtraceback()
582
582
583 def _exec_file(self, fname):
583 def _exec_file(self, fname):
584 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 full_filename = filefind(fname, [u'.', self.ipython_dir])
585 if os.path.isfile(full_filename):
585 if os.path.isfile(full_filename):
586 if full_filename.endswith(u'.py'):
586 if full_filename.endswith(u'.py'):
587 self.log.info("Running file in user namespace: %s" %
587 self.log.info("Running file in user namespace: %s" %
588 full_filename)
588 full_filename)
589 # Ensure that __file__ is always defined to match Python behavior
589 # Ensure that __file__ is always defined to match Python behavior
590 self.shell.user_ns['__file__'] = fname
590 self.shell.user_ns['__file__'] = fname
591 try:
591 try:
592 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 self.shell.safe_execfile(full_filename, self.shell.user_ns)
593 finally:
593 finally:
594 del self.shell.user_ns['__file__']
594 del self.shell.user_ns['__file__']
595 elif full_filename.endswith('.ipy'):
595 elif full_filename.endswith('.ipy'):
596 self.log.info("Running file in user namespace: %s" %
596 self.log.info("Running file in user namespace: %s" %
597 full_filename)
597 full_filename)
598 self.shell.safe_execfile_ipy(full_filename)
598 self.shell.safe_execfile_ipy(full_filename)
599 else:
599 else:
600 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 self.log.warn("File does not have a .py or .ipy extension: <%s>"
601 % full_filename)
601 % full_filename)
602 def _run_exec_files(self):
602 def _run_exec_files(self):
603 try:
603 try:
604 if hasattr(self.master_config.Global, 'exec_files'):
604 if hasattr(self.master_config.Global, 'exec_files'):
605 self.log.debug("Running files in Global.exec_files...")
605 self.log.debug("Running files in Global.exec_files...")
606 exec_files = self.master_config.Global.exec_files
606 exec_files = self.master_config.Global.exec_files
607 for fname in exec_files:
607 for fname in exec_files:
608 self._exec_file(fname)
608 self._exec_file(fname)
609 except:
609 except:
610 self.log.warn("Unknown error in handling Global.exec_files:")
610 self.log.warn("Unknown error in handling Global.exec_files:")
611 self.shell.showtraceback()
611 self.shell.showtraceback()
612
612
613 def _run_cmd_line_code(self):
613 def _run_cmd_line_code(self):
614 if hasattr(self.master_config.Global, 'code_to_run'):
614 if hasattr(self.master_config.Global, 'code_to_run'):
615 line = self.master_config.Global.code_to_run
615 line = self.master_config.Global.code_to_run
616 try:
616 try:
617 self.log.info("Running code given at command line (-c): %s" %
617 self.log.info("Running code given at command line (-c): %s" %
618 line)
618 line)
619 self.shell.runlines(line)
619 self.shell.runlines(line)
620 except:
620 except:
621 self.log.warn("Error in executing line in user namespace: %s" %
621 self.log.warn("Error in executing line in user namespace: %s" %
622 line)
622 line)
623 self.shell.showtraceback()
623 self.shell.showtraceback()
624 return
624 return
625 # Like Python itself, ignore the second if the first of these is present
625 # Like Python itself, ignore the second if the first of these is present
626 try:
626 try:
627 fname = self.extra_args[0]
627 fname = self.extra_args[0]
628 except:
628 except:
629 pass
629 pass
630 else:
630 else:
631 try:
631 try:
632 self._exec_file(fname)
632 self._exec_file(fname)
633 except:
633 except:
634 self.log.warn("Error in executing file in user namespace: %s" %
634 self.log.warn("Error in executing file in user namespace: %s" %
635 fname)
635 fname)
636 self.shell.showtraceback()
636 self.shell.showtraceback()
637
637
638 def start_app(self):
638 def start_app(self):
639 if self.master_config.Global.interact:
639 if self.master_config.Global.interact:
640 self.log.debug("Starting IPython's mainloop...")
640 self.log.debug("Starting IPython's mainloop...")
641 self.shell.mainloop()
641 self.shell.mainloop()
642 else:
642 else:
643 self.log.debug("IPython not interactive, start_app is no-op...")
643 self.log.debug("IPython not interactive, start_app is no-op...")
644
644
645
645
646 def load_default_config(ipython_dir=None):
646 def load_default_config(ipython_dir=None):
647 """Load the default config file from the default ipython_dir.
647 """Load the default config file from the default ipython_dir.
648
648
649 This is useful for embedded shells.
649 This is useful for embedded shells.
650 """
650 """
651 if ipython_dir is None:
651 if ipython_dir is None:
652 ipython_dir = get_ipython_dir()
652 ipython_dir = get_ipython_dir()
653 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
653 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
654 config = cl.load_config()
654 config = cl.load_config()
655 return config
655 return config
656
656
657
657
658 def launch_new_instance():
658 def launch_new_instance():
659 """Create and run a full blown IPython instance"""
659 """Create and run a full blown IPython instance"""
660 app = IPythonApp()
660 app = IPythonApp()
661 app.start()
661 app.start()
662
662
663
663
664 if __name__ == '__main__':
664 if __name__ == '__main__':
665 launch_new_instance()
665 launch_new_instance()
@@ -1,364 +1,364 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 # Standard library imports.
17 # Standard library imports.
18 import __builtin__
18 import __builtin__
19 from code import CommandCompiler
19 from code import CommandCompiler
20 import os
20 import os
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24
24
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
30 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
31 from IPython.external.argparse import ArgumentParser
31 from IPython.external.argparse import ArgumentParser
32 from IPython.utils.traitlets import Instance
32 from IPython.utils.traitlets import Instance
33 from IPython.zmq.session import Session, Message
33 from IPython.zmq.session import Session, Message
34 from completer import KernelCompleter
34 from completer import KernelCompleter
35 from iostream import OutStream
35 from iostream import OutStream
36 from displayhook import DisplayHook
36 from displayhook import DisplayHook
37 from exitpoller import ExitPollerUnix, ExitPollerWindows
37 from exitpoller import ExitPollerUnix, ExitPollerWindows
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Main kernel class
40 # Main kernel class
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 class Kernel(Configurable):
43 class Kernel(Configurable):
44
44
45 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
45 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
46 session = Instance('IPython.zmq.session.Session')
46 session = Instance('IPython.zmq.session.Session')
47 reply_socket = Instance('zmq.Socket')
47 reply_socket = Instance('zmq.Socket')
48 pub_socket = Instance('zmq.Socket')
48 pub_socket = Instance('zmq.Socket')
49 req_socket = Instance('zmq.Socket')
49 req_socket = Instance('zmq.Socket')
50
50
51 def __init__(self, **kwargs):
51 def __init__(self, **kwargs):
52 super(Kernel, self).__init__(**kwargs)
52 super(Kernel, self).__init__(**kwargs)
53 self.shell = InteractiveShell.instance()
53 self.shell = InteractiveShell.instance()
54
54
55 # Build dict of handlers for message types
55 # Build dict of handlers for message types
56 msg_types = [ 'execute_request', 'complete_request',
56 msg_types = [ 'execute_request', 'complete_request',
57 'object_info_request' ]
57 'object_info_request' ]
58 self.handlers = {}
58 self.handlers = {}
59 for msg_type in msg_types:
59 for msg_type in msg_types:
60 self.handlers[msg_type] = getattr(self, msg_type)
60 self.handlers[msg_type] = getattr(self, msg_type)
61
61
62 def abort_queue(self):
62 def abort_queue(self):
63 while True:
63 while True:
64 try:
64 try:
65 ident = self.reply_socket.recv(zmq.NOBLOCK)
65 ident = self.reply_socket.recv(zmq.NOBLOCK)
66 except zmq.ZMQError, e:
66 except zmq.ZMQError, e:
67 if e.errno == zmq.EAGAIN:
67 if e.errno == zmq.EAGAIN:
68 break
68 break
69 else:
69 else:
70 assert self.reply_socket.rcvmore(), "Unexpected missing message part."
70 assert self.reply_socket.rcvmore(), "Unexpected missing message part."
71 msg = self.reply_socket.recv_json()
71 msg = self.reply_socket.recv_json()
72 print>>sys.__stdout__, "Aborting:"
72 print>>sys.__stdout__, "Aborting:"
73 print>>sys.__stdout__, Message(msg)
73 print>>sys.__stdout__, Message(msg)
74 msg_type = msg['msg_type']
74 msg_type = msg['msg_type']
75 reply_type = msg_type.split('_')[0] + '_reply'
75 reply_type = msg_type.split('_')[0] + '_reply'
76 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
76 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
77 print>>sys.__stdout__, Message(reply_msg)
77 print>>sys.__stdout__, Message(reply_msg)
78 self.reply_socket.send(ident,zmq.SNDMORE)
78 self.reply_socket.send(ident,zmq.SNDMORE)
79 self.reply_socket.send_json(reply_msg)
79 self.reply_socket.send_json(reply_msg)
80 # We need to wait a bit for requests to come in. This can probably
80 # We need to wait a bit for requests to come in. This can probably
81 # be set shorter for true asynchronous clients.
81 # be set shorter for true asynchronous clients.
82 time.sleep(0.1)
82 time.sleep(0.1)
83
83
84 def execute_request(self, ident, parent):
84 def execute_request(self, ident, parent):
85 try:
85 try:
86 code = parent[u'content'][u'code']
86 code = parent[u'content'][u'code']
87 except:
87 except:
88 print>>sys.__stderr__, "Got bad msg: "
88 print>>sys.__stderr__, "Got bad msg: "
89 print>>sys.__stderr__, Message(parent)
89 print>>sys.__stderr__, Message(parent)
90 return
90 return
91 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
91 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
92 self.pub_socket.send_json(pyin_msg)
92 self.pub_socket.send_json(pyin_msg)
93
93
94 try:
94 try:
95 # Replace raw_input. Note that is not sufficient to replace
95 # Replace raw_input. Note that is not sufficient to replace
96 # raw_input in the user namespace.
96 # raw_input in the user namespace.
97 raw_input = lambda prompt='': self.raw_input(prompt, ident, parent)
97 raw_input = lambda prompt='': self.raw_input(prompt, ident, parent)
98 __builtin__.raw_input = raw_input
98 __builtin__.raw_input = raw_input
99
99
100 # Configure the display hook.
100 # Configure the display hook.
101 sys.displayhook.set_parent(parent)
101 sys.displayhook.set_parent(parent)
102
102
103 self.shell.runlines(code)
103 self.shell.runlines(code)
104 # exec comp_code in self.user_ns, self.user_ns
104 # exec comp_code in self.user_ns, self.user_ns
105 except:
105 except:
106 etype, evalue, tb = sys.exc_info()
106 etype, evalue, tb = sys.exc_info()
107 tb = traceback.format_exception(etype, evalue, tb)
107 tb = traceback.format_exception(etype, evalue, tb)
108 exc_content = {
108 exc_content = {
109 u'status' : u'error',
109 u'status' : u'error',
110 u'traceback' : tb,
110 u'traceback' : tb,
111 u'ename' : unicode(etype.__name__),
111 u'ename' : unicode(etype.__name__),
112 u'evalue' : unicode(evalue)
112 u'evalue' : unicode(evalue)
113 }
113 }
114 exc_msg = self.session.msg(u'pyerr', exc_content, parent)
114 exc_msg = self.session.msg(u'pyerr', exc_content, parent)
115 self.pub_socket.send_json(exc_msg)
115 self.pub_socket.send_json(exc_msg)
116 reply_content = exc_content
116 reply_content = exc_content
117 else:
117 else:
118 reply_content = {'status' : 'ok'}
118 reply_content = {'status' : 'ok'}
119
119
120 # Flush output before sending the reply.
120 # Flush output before sending the reply.
121 sys.stderr.flush()
121 sys.stderr.flush()
122 sys.stdout.flush()
122 sys.stdout.flush()
123
123
124 # Send the reply.
124 # Send the reply.
125 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
125 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
126 print>>sys.__stdout__, Message(reply_msg)
126 print>>sys.__stdout__, Message(reply_msg)
127 self.reply_socket.send(ident, zmq.SNDMORE)
127 self.reply_socket.send(ident, zmq.SNDMORE)
128 self.reply_socket.send_json(reply_msg)
128 self.reply_socket.send_json(reply_msg)
129 if reply_msg['content']['status'] == u'error':
129 if reply_msg['content']['status'] == u'error':
130 self.abort_queue()
130 self.abort_queue()
131
131
132 def raw_input(self, prompt, ident, parent):
132 def raw_input(self, prompt, ident, parent):
133 # Flush output before making the request.
133 # Flush output before making the request.
134 sys.stderr.flush()
134 sys.stderr.flush()
135 sys.stdout.flush()
135 sys.stdout.flush()
136
136
137 # Send the input request.
137 # Send the input request.
138 content = dict(prompt=prompt)
138 content = dict(prompt=prompt)
139 msg = self.session.msg(u'input_request', content, parent)
139 msg = self.session.msg(u'input_request', content, parent)
140 self.req_socket.send_json(msg)
140 self.req_socket.send_json(msg)
141
141
142 # Await a response.
142 # Await a response.
143 reply = self.req_socket.recv_json()
143 reply = self.req_socket.recv_json()
144 try:
144 try:
145 value = reply['content']['value']
145 value = reply['content']['value']
146 except:
146 except:
147 print>>sys.__stderr__, "Got bad raw_input reply: "
147 print>>sys.__stderr__, "Got bad raw_input reply: "
148 print>>sys.__stderr__, Message(parent)
148 print>>sys.__stderr__, Message(parent)
149 value = ''
149 value = ''
150 return value
150 return value
151
151
152 def complete_request(self, ident, parent):
152 def complete_request(self, ident, parent):
153 matches = {'matches' : self.complete(parent),
153 matches = {'matches' : self.complete(parent),
154 'status' : 'ok'}
154 'status' : 'ok'}
155 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
155 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
156 matches, parent, ident)
156 matches, parent, ident)
157 print >> sys.__stdout__, completion_msg
157 print >> sys.__stdout__, completion_msg
158
158
159 def complete(self, msg):
159 def complete(self, msg):
160 return self.shell.complete(msg.content.line)
160 return self.shell.complete(msg.content.line)
161
161
162 def object_info_request(self, ident, parent):
162 def object_info_request(self, ident, parent):
163 context = parent['content']['oname'].split('.')
163 context = parent['content']['oname'].split('.')
164 object_info = self.object_info(context)
164 object_info = self.object_info(context)
165 msg = self.session.send(self.reply_socket, 'object_info_reply',
165 msg = self.session.send(self.reply_socket, 'object_info_reply',
166 object_info, parent, ident)
166 object_info, parent, ident)
167 print >> sys.__stdout__, msg
167 print >> sys.__stdout__, msg
168
168
169 def object_info(self, context):
169 def object_info(self, context):
170 symbol, leftover = self.symbol_from_context(context)
170 symbol, leftover = self.symbol_from_context(context)
171 if symbol is not None and not leftover:
171 if symbol is not None and not leftover:
172 doc = getattr(symbol, '__doc__', '')
172 doc = getattr(symbol, '__doc__', '')
173 else:
173 else:
174 doc = ''
174 doc = ''
175 object_info = dict(docstring = doc)
175 object_info = dict(docstring = doc)
176 return object_info
176 return object_info
177
177
178 def symbol_from_context(self, context):
178 def symbol_from_context(self, context):
179 if not context:
179 if not context:
180 return None, context
180 return None, context
181
181
182 base_symbol_string = context[0]
182 base_symbol_string = context[0]
183 symbol = self.shell.user_ns.get(base_symbol_string, None)
183 symbol = self.shell.user_ns.get(base_symbol_string, None)
184 if symbol is None:
184 if symbol is None:
185 symbol = __builtin__.__dict__.get(base_symbol_string, None)
185 symbol = __builtin__.__dict__.get(base_symbol_string, None)
186 if symbol is None:
186 if symbol is None:
187 return None, context
187 return None, context
188
188
189 context = context[1:]
189 context = context[1:]
190 for i, name in enumerate(context):
190 for i, name in enumerate(context):
191 new_symbol = getattr(symbol, name, None)
191 new_symbol = getattr(symbol, name, None)
192 if new_symbol is None:
192 if new_symbol is None:
193 return symbol, context[i:]
193 return symbol, context[i:]
194 else:
194 else:
195 symbol = new_symbol
195 symbol = new_symbol
196
196
197 return symbol, []
197 return symbol, []
198
198
199 def start(self):
199 def start(self):
200 while True:
200 while True:
201 ident = self.reply_socket.recv()
201 ident = self.reply_socket.recv()
202 assert self.reply_socket.rcvmore(), "Missing message part."
202 assert self.reply_socket.rcvmore(), "Missing message part."
203 msg = self.reply_socket.recv_json()
203 msg = self.reply_socket.recv_json()
204 omsg = Message(msg)
204 omsg = Message(msg)
205 print>>sys.__stdout__
205 print>>sys.__stdout__
206 print>>sys.__stdout__, omsg
206 print>>sys.__stdout__, omsg
207 handler = self.handlers.get(omsg.msg_type, None)
207 handler = self.handlers.get(omsg.msg_type, None)
208 if handler is None:
208 if handler is None:
209 print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg
209 print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg
210 else:
210 else:
211 handler(ident, omsg)
211 handler(ident, omsg)
212
212
213 #-----------------------------------------------------------------------------
213 #-----------------------------------------------------------------------------
214 # Kernel main and launch functions
214 # Kernel main and launch functions
215 #-----------------------------------------------------------------------------
215 #-----------------------------------------------------------------------------
216
216
217 def bind_port(socket, ip, port):
217 def bind_port(socket, ip, port):
218 """ Binds the specified ZMQ socket. If the port is less than zero, a random
218 """ Binds the specified ZMQ socket. If the port is less than zero, a random
219 port is chosen. Returns the port that was bound.
219 port is chosen. Returns the port that was bound.
220 """
220 """
221 connection = 'tcp://%s' % ip
221 connection = 'tcp://%s' % ip
222 if port <= 0:
222 if port <= 0:
223 port = socket.bind_to_random_port(connection)
223 port = socket.bind_to_random_port(connection)
224 else:
224 else:
225 connection += ':%i' % port
225 connection += ':%i' % port
226 socket.bind(connection)
226 socket.bind(connection)
227 return port
227 return port
228
228
229
229
230 def main():
230 def main():
231 """ Main entry point for launching a kernel.
231 """ Main entry point for launching a kernel.
232 """
232 """
233 # Parse command line arguments.
233 # Parse command line arguments.
234 parser = ArgumentParser()
234 parser = ArgumentParser()
235 parser.add_argument('--ip', type=str, default='127.0.0.1',
235 parser.add_argument('--ip', type=str, default='127.0.0.1',
236 help='set the kernel\'s IP address [default: local]')
236 help='set the kernel\'s IP address [default: local]')
237 parser.add_argument('--xrep', type=int, metavar='PORT', default=0,
237 parser.add_argument('--xrep', type=int, metavar='PORT', default=0,
238 help='set the XREP channel port [default: random]')
238 help='set the XREP channel port [default: random]')
239 parser.add_argument('--pub', type=int, metavar='PORT', default=0,
239 parser.add_argument('--pub', type=int, metavar='PORT', default=0,
240 help='set the PUB channel port [default: random]')
240 help='set the PUB channel port [default: random]')
241 parser.add_argument('--req', type=int, metavar='PORT', default=0,
241 parser.add_argument('--req', type=int, metavar='PORT', default=0,
242 help='set the REQ channel port [default: random]')
242 help='set the REQ channel port [default: random]')
243 if sys.platform == 'win32':
243 if sys.platform == 'win32':
244 parser.add_argument('--parent', type=int, metavar='HANDLE',
244 parser.add_argument('--parent', type=int, metavar='HANDLE',
245 default=0, help='kill this process if the process '
245 default=0, help='kill this process if the process '
246 'with HANDLE dies')
246 'with HANDLE dies')
247 else:
247 else:
248 parser.add_argument('--parent', action='store_true',
248 parser.add_argument('--parent', action='store_true',
249 help='kill this process if its parent dies')
249 help='kill this process if its parent dies')
250 namespace = parser.parse_args()
250 namespace = parser.parse_args()
251
251
252 # Create a context, a session, and the kernel sockets.
252 # Create a context, a session, and the kernel sockets.
253 print >>sys.__stdout__, "Starting the kernel..."
253 print >>sys.__stdout__, "Starting the kernel..."
254 context = zmq.Context()
254 context = zmq.Context()
255 session = Session(username=u'kernel')
255 session = Session(username=u'kernel')
256
256
257 reply_socket = context.socket(zmq.XREP)
257 reply_socket = context.socket(zmq.XREP)
258 xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep)
258 xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep)
259 print >>sys.__stdout__, "XREP Channel on port", xrep_port
259 print >>sys.__stdout__, "XREP Channel on port", xrep_port
260
260
261 pub_socket = context.socket(zmq.PUB)
261 pub_socket = context.socket(zmq.PUB)
262 pub_port = bind_port(pub_socket, namespace.ip, namespace.pub)
262 pub_port = bind_port(pub_socket, namespace.ip, namespace.pub)
263 print >>sys.__stdout__, "PUB Channel on port", pub_port
263 print >>sys.__stdout__, "PUB Channel on port", pub_port
264
264
265 req_socket = context.socket(zmq.XREQ)
265 req_socket = context.socket(zmq.XREQ)
266 req_port = bind_port(req_socket, namespace.ip, namespace.req)
266 req_port = bind_port(req_socket, namespace.ip, namespace.req)
267 print >>sys.__stdout__, "REQ Channel on port", req_port
267 print >>sys.__stdout__, "REQ Channel on port", req_port
268
268
269 # Redirect input streams and set a display hook.
269 # Redirect input streams and set a display hook.
270 sys.stdout = OutStream(session, pub_socket, u'stdout')
270 # sys.stdout = OutStream(session, pub_socket, u'stdout')
271 sys.stderr = OutStream(session, pub_socket, u'stderr')
271 # sys.stderr = OutStream(session, pub_socket, u'stderr')
272 sys.displayhook = DisplayHook(session, pub_socket)
272 sys.displayhook = DisplayHook(session, pub_socket)
273
273
274 # Create the kernel.
274 # Create the kernel.
275 kernel = Kernel(
275 kernel = Kernel(
276 session=session, reply_socket=reply_socket,
276 session=session, reply_socket=reply_socket,
277 pub_socket=pub_socket, req_socket=req_socket
277 pub_socket=pub_socket, req_socket=req_socket
278 )
278 )
279
279
280 # Configure this kernel/process to die on parent termination, if necessary.
280 # Configure this kernel/process to die on parent termination, if necessary.
281 if namespace.parent:
281 if namespace.parent:
282 if sys.platform == 'win32':
282 if sys.platform == 'win32':
283 poller = ExitPollerWindows(namespace.parent)
283 poller = ExitPollerWindows(namespace.parent)
284 else:
284 else:
285 poller = ExitPollerUnix()
285 poller = ExitPollerUnix()
286 poller.start()
286 poller.start()
287
287
288 # Start the kernel mainloop.
288 # Start the kernel mainloop.
289 kernel.start()
289 kernel.start()
290
290
291
291
292 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False):
292 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False):
293 """ Launches a localhost kernel, binding to the specified ports.
293 """ Launches a localhost kernel, binding to the specified ports.
294
294
295 Parameters
295 Parameters
296 ----------
296 ----------
297 xrep_port : int, optional
297 xrep_port : int, optional
298 The port to use for XREP channel.
298 The port to use for XREP channel.
299
299
300 pub_port : int, optional
300 pub_port : int, optional
301 The port to use for the SUB channel.
301 The port to use for the SUB channel.
302
302
303 req_port : int, optional
303 req_port : int, optional
304 The port to use for the REQ (raw input) channel.
304 The port to use for the REQ (raw input) channel.
305
305
306 independent : bool, optional (default False)
306 independent : bool, optional (default False)
307 If set, the kernel process is guaranteed to survive if this process
307 If set, the kernel process is guaranteed to survive if this process
308 dies. If not set, an effort is made to ensure that the kernel is killed
308 dies. If not set, an effort is made to ensure that the kernel is killed
309 when this process dies. Note that in this case it is still good practice
309 when this process dies. Note that in this case it is still good practice
310 to kill kernels manually before exiting.
310 to kill kernels manually before exiting.
311
311
312 Returns
312 Returns
313 -------
313 -------
314 A tuple of form:
314 A tuple of form:
315 (kernel_process, xrep_port, pub_port, req_port)
315 (kernel_process, xrep_port, pub_port, req_port)
316 where kernel_process is a Popen object and the ports are integers.
316 where kernel_process is a Popen object and the ports are integers.
317 """
317 """
318 import socket
318 import socket
319 from subprocess import Popen
319 from subprocess import Popen
320
320
321 # Find open ports as necessary.
321 # Find open ports as necessary.
322 ports = []
322 ports = []
323 ports_needed = int(xrep_port <= 0) + int(pub_port <= 0) + int(req_port <= 0)
323 ports_needed = int(xrep_port <= 0) + int(pub_port <= 0) + int(req_port <= 0)
324 for i in xrange(ports_needed):
324 for i in xrange(ports_needed):
325 sock = socket.socket()
325 sock = socket.socket()
326 sock.bind(('', 0))
326 sock.bind(('', 0))
327 ports.append(sock)
327 ports.append(sock)
328 for i, sock in enumerate(ports):
328 for i, sock in enumerate(ports):
329 port = sock.getsockname()[1]
329 port = sock.getsockname()[1]
330 sock.close()
330 sock.close()
331 ports[i] = port
331 ports[i] = port
332 if xrep_port <= 0:
332 if xrep_port <= 0:
333 xrep_port = ports.pop(0)
333 xrep_port = ports.pop(0)
334 if pub_port <= 0:
334 if pub_port <= 0:
335 pub_port = ports.pop(0)
335 pub_port = ports.pop(0)
336 if req_port <= 0:
336 if req_port <= 0:
337 req_port = ports.pop(0)
337 req_port = ports.pop(0)
338
338
339 # Spawn a kernel.
339 # Spawn a kernel.
340 command = 'from IPython.zmq.ipkernel import main; main()'
340 command = 'from IPython.zmq.ipkernel import main; main()'
341 arguments = [ sys.executable, '-c', command, '--xrep', str(xrep_port),
341 arguments = [ sys.executable, '-c', command, '--xrep', str(xrep_port),
342 '--pub', str(pub_port), '--req', str(req_port) ]
342 '--pub', str(pub_port), '--req', str(req_port) ]
343 if independent:
343 if independent:
344 if sys.platform == 'win32':
344 if sys.platform == 'win32':
345 proc = Popen(['start', '/b'] + arguments, shell=True)
345 proc = Popen(['start', '/b'] + arguments, shell=True)
346 else:
346 else:
347 proc = Popen(arguments, preexec_fn=lambda: os.setsid())
347 proc = Popen(arguments, preexec_fn=lambda: os.setsid())
348 else:
348 else:
349 if sys.platform == 'win32':
349 if sys.platform == 'win32':
350 from _subprocess import DuplicateHandle, GetCurrentProcess, \
350 from _subprocess import DuplicateHandle, GetCurrentProcess, \
351 DUPLICATE_SAME_ACCESS
351 DUPLICATE_SAME_ACCESS
352 pid = GetCurrentProcess()
352 pid = GetCurrentProcess()
353 handle = DuplicateHandle(pid, pid, pid, 0,
353 handle = DuplicateHandle(pid, pid, pid, 0,
354 True, # Inheritable by new processes.
354 True, # Inheritable by new processes.
355 DUPLICATE_SAME_ACCESS)
355 DUPLICATE_SAME_ACCESS)
356 proc = Popen(arguments + ['--parent', str(int(handle))])
356 proc = Popen(arguments + ['--parent', str(int(handle))])
357 else:
357 else:
358 proc = Popen(arguments + ['--parent'])
358 proc = Popen(arguments + ['--parent'])
359
359
360 return proc, xrep_port, pub_port, req_port
360 return proc, xrep_port, pub_port, req_port
361
361
362
362
363 if __name__ == '__main__':
363 if __name__ == '__main__':
364 main()
364 main()
General Comments 0
You need to be logged in to leave comments. Login now