|
@@
-1,2390
+1,2403
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 __future__
|
|
21
|
import __future__
|
|
22
|
import abc
|
|
22
|
import abc
|
|
23
|
import atexit
|
|
23
|
import atexit
|
|
24
|
import codeop
|
|
24
|
import codeop
|
|
25
|
import exceptions
|
|
25
|
import exceptions
|
|
26
|
import new
|
|
26
|
import new
|
|
27
|
import os
|
|
27
|
import os
|
|
28
|
import re
|
|
28
|
import re
|
|
29
|
import string
|
|
29
|
import string
|
|
30
|
import sys
|
|
30
|
import sys
|
|
31
|
import tempfile
|
|
31
|
import tempfile
|
|
32
|
from contextlib import nested
|
|
32
|
from contextlib import nested
|
|
33
|
|
|
33
|
|
|
34
|
from IPython.config.configurable import Configurable
|
|
34
|
from IPython.config.configurable import Configurable
|
|
35
|
from IPython.core import debugger, oinspect
|
|
35
|
from IPython.core import debugger, oinspect
|
|
36
|
from IPython.core import history as ipcorehist
|
|
36
|
from IPython.core import history as ipcorehist
|
|
37
|
from IPython.core import page
|
|
37
|
from IPython.core import page
|
|
38
|
from IPython.core import prefilter
|
|
38
|
from IPython.core import prefilter
|
|
39
|
from IPython.core import shadowns
|
|
39
|
from IPython.core import shadowns
|
|
40
|
from IPython.core import ultratb
|
|
40
|
from IPython.core import ultratb
|
|
41
|
from IPython.core.alias import AliasManager
|
|
41
|
from IPython.core.alias import AliasManager
|
|
42
|
from IPython.core.builtin_trap import BuiltinTrap
|
|
42
|
from IPython.core.builtin_trap import BuiltinTrap
|
|
43
|
from IPython.core.display_trap import DisplayTrap
|
|
43
|
from IPython.core.display_trap import DisplayTrap
|
|
44
|
from IPython.core.displayhook import DisplayHook
|
|
44
|
from IPython.core.displayhook import DisplayHook
|
|
45
|
from IPython.core.error import TryNext, UsageError
|
|
45
|
from IPython.core.error import TryNext, UsageError
|
|
46
|
from IPython.core.extensions import ExtensionManager
|
|
46
|
from IPython.core.extensions import ExtensionManager
|
|
47
|
from IPython.core.fakemodule import FakeModule, init_fakemod_dict
|
|
47
|
from IPython.core.fakemodule import FakeModule, init_fakemod_dict
|
|
48
|
from IPython.core.inputlist import InputList
|
|
48
|
from IPython.core.inputlist import InputList
|
|
49
|
from IPython.core.logger import Logger
|
|
49
|
from IPython.core.logger import Logger
|
|
50
|
from IPython.core.magic import Magic
|
|
50
|
from IPython.core.magic import Magic
|
|
51
|
from IPython.core.payload import PayloadManager
|
|
51
|
from IPython.core.payload import PayloadManager
|
|
52
|
from IPython.core.plugin import PluginManager
|
|
52
|
from IPython.core.plugin import PluginManager
|
|
53
|
from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
|
|
53
|
from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
|
|
54
|
from IPython.external.Itpl import ItplNS
|
|
54
|
from IPython.external.Itpl import ItplNS
|
|
55
|
from IPython.utils import PyColorize
|
|
55
|
from IPython.utils import PyColorize
|
|
56
|
from IPython.utils import io
|
|
56
|
from IPython.utils import io
|
|
57
|
from IPython.utils import pickleshare
|
|
57
|
from IPython.utils import pickleshare
|
|
58
|
from IPython.utils.doctestreload import doctest_reload
|
|
58
|
from IPython.utils.doctestreload import doctest_reload
|
|
59
|
from IPython.utils.io import ask_yes_no, rprint
|
|
59
|
from IPython.utils.io import ask_yes_no, rprint
|
|
60
|
from IPython.utils.ipstruct import Struct
|
|
60
|
from IPython.utils.ipstruct import Struct
|
|
61
|
from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
|
|
61
|
from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
|
|
62
|
from IPython.utils.process import system, getoutput
|
|
62
|
from IPython.utils.process import system, getoutput
|
|
63
|
from IPython.utils.strdispatch import StrDispatch
|
|
63
|
from IPython.utils.strdispatch import StrDispatch
|
|
64
|
from IPython.utils.syspathcontext import prepended_to_syspath
|
|
64
|
from IPython.utils.syspathcontext import prepended_to_syspath
|
|
65
|
from IPython.utils.text import num_ini_spaces, format_screen
|
|
65
|
from IPython.utils.text import num_ini_spaces, format_screen
|
|
66
|
from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
|
|
66
|
from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
|
|
67
|
List, Unicode, Instance, Type)
|
|
67
|
List, Unicode, Instance, Type)
|
|
68
|
from IPython.utils.warn import warn, error, fatal
|
|
68
|
from IPython.utils.warn import warn, error, fatal
|
|
69
|
import IPython.core.hooks
|
|
69
|
import IPython.core.hooks
|
|
70
|
|
|
70
|
|
|
71
|
#-----------------------------------------------------------------------------
|
|
71
|
#-----------------------------------------------------------------------------
|
|
72
|
# Globals
|
|
72
|
# Globals
|
|
73
|
#-----------------------------------------------------------------------------
|
|
73
|
#-----------------------------------------------------------------------------
|
|
74
|
|
|
74
|
|
|
75
|
# compiled regexps for autoindent management
|
|
75
|
# compiled regexps for autoindent management
|
|
76
|
dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
|
|
76
|
dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
|
|
77
|
|
|
77
|
|
|
78
|
#-----------------------------------------------------------------------------
|
|
78
|
#-----------------------------------------------------------------------------
|
|
79
|
# Utilities
|
|
79
|
# Utilities
|
|
80
|
#-----------------------------------------------------------------------------
|
|
80
|
#-----------------------------------------------------------------------------
|
|
81
|
|
|
81
|
|
|
82
|
# store the builtin raw_input globally, and use this always, in case user code
|
|
82
|
# store the builtin raw_input globally, and use this always, in case user code
|
|
83
|
# overwrites it (like wx.py.PyShell does)
|
|
83
|
# overwrites it (like wx.py.PyShell does)
|
|
84
|
raw_input_original = raw_input
|
|
84
|
raw_input_original = raw_input
|
|
85
|
|
|
85
|
|
|
86
|
def softspace(file, newvalue):
|
|
86
|
def softspace(file, newvalue):
|
|
87
|
"""Copied from code.py, to remove the dependency"""
|
|
87
|
"""Copied from code.py, to remove the dependency"""
|
|
88
|
|
|
88
|
|
|
89
|
oldvalue = 0
|
|
89
|
oldvalue = 0
|
|
90
|
try:
|
|
90
|
try:
|
|
91
|
oldvalue = file.softspace
|
|
91
|
oldvalue = file.softspace
|
|
92
|
except AttributeError:
|
|
92
|
except AttributeError:
|
|
93
|
pass
|
|
93
|
pass
|
|
94
|
try:
|
|
94
|
try:
|
|
95
|
file.softspace = newvalue
|
|
95
|
file.softspace = newvalue
|
|
96
|
except (AttributeError, TypeError):
|
|
96
|
except (AttributeError, TypeError):
|
|
97
|
# "attribute-less object" or "read-only attributes"
|
|
97
|
# "attribute-less object" or "read-only attributes"
|
|
98
|
pass
|
|
98
|
pass
|
|
99
|
return oldvalue
|
|
99
|
return oldvalue
|
|
100
|
|
|
100
|
|
|
101
|
|
|
101
|
|
|
102
|
def no_op(*a, **kw): pass
|
|
102
|
def no_op(*a, **kw): pass
|
|
103
|
|
|
103
|
|
|
104
|
class SpaceInInput(exceptions.Exception): pass
|
|
104
|
class SpaceInInput(exceptions.Exception): pass
|
|
105
|
|
|
105
|
|
|
106
|
class Bunch: pass
|
|
106
|
class Bunch: pass
|
|
107
|
|
|
107
|
|
|
108
|
|
|
108
|
|
|
109
|
def get_default_colors():
|
|
109
|
def get_default_colors():
|
|
110
|
if sys.platform=='darwin':
|
|
110
|
if sys.platform=='darwin':
|
|
111
|
return "LightBG"
|
|
111
|
return "LightBG"
|
|
112
|
elif os.name=='nt':
|
|
112
|
elif os.name=='nt':
|
|
113
|
return 'Linux'
|
|
113
|
return 'Linux'
|
|
114
|
else:
|
|
114
|
else:
|
|
115
|
return 'Linux'
|
|
115
|
return 'Linux'
|
|
116
|
|
|
116
|
|
|
117
|
|
|
117
|
|
|
118
|
class SeparateStr(Str):
|
|
118
|
class SeparateStr(Str):
|
|
119
|
"""A Str subclass to validate separate_in, separate_out, etc.
|
|
119
|
"""A Str subclass to validate separate_in, separate_out, etc.
|
|
120
|
|
|
120
|
|
|
121
|
This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
|
|
121
|
This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
|
|
122
|
"""
|
|
122
|
"""
|
|
123
|
|
|
123
|
|
|
124
|
def validate(self, obj, value):
|
|
124
|
def validate(self, obj, value):
|
|
125
|
if value == '0': value = ''
|
|
125
|
if value == '0': value = ''
|
|
126
|
value = value.replace('\\n','\n')
|
|
126
|
value = value.replace('\\n','\n')
|
|
127
|
return super(SeparateStr, self).validate(obj, value)
|
|
127
|
return super(SeparateStr, self).validate(obj, value)
|
|
128
|
|
|
128
|
|
|
129
|
class MultipleInstanceError(Exception):
|
|
129
|
class MultipleInstanceError(Exception):
|
|
130
|
pass
|
|
130
|
pass
|
|
131
|
|
|
131
|
|
|
132
|
|
|
132
|
|
|
133
|
#-----------------------------------------------------------------------------
|
|
133
|
#-----------------------------------------------------------------------------
|
|
134
|
# Main IPython class
|
|
134
|
# Main IPython class
|
|
135
|
#-----------------------------------------------------------------------------
|
|
135
|
#-----------------------------------------------------------------------------
|
|
136
|
|
|
136
|
|
|
137
|
|
|
137
|
|
|
138
|
class InteractiveShell(Configurable, Magic):
|
|
138
|
class InteractiveShell(Configurable, Magic):
|
|
139
|
"""An enhanced, interactive shell for Python."""
|
|
139
|
"""An enhanced, interactive shell for Python."""
|
|
140
|
|
|
140
|
|
|
141
|
_instance = None
|
|
141
|
_instance = None
|
|
142
|
autocall = Enum((0,1,2), default_value=1, config=True)
|
|
142
|
autocall = Enum((0,1,2), default_value=1, config=True)
|
|
143
|
# TODO: remove all autoindent logic and put into frontends.
|
|
143
|
# TODO: remove all autoindent logic and put into frontends.
|
|
144
|
# We can't do this yet because even runlines uses the autoindent.
|
|
144
|
# We can't do this yet because even runlines uses the autoindent.
|
|
145
|
autoindent = CBool(True, config=True)
|
|
145
|
autoindent = CBool(True, config=True)
|
|
146
|
automagic = CBool(True, config=True)
|
|
146
|
automagic = CBool(True, config=True)
|
|
147
|
cache_size = Int(1000, config=True)
|
|
147
|
cache_size = Int(1000, config=True)
|
|
148
|
color_info = CBool(True, config=True)
|
|
148
|
color_info = CBool(True, config=True)
|
|
149
|
colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
|
|
149
|
colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
|
|
150
|
default_value=get_default_colors(), config=True)
|
|
150
|
default_value=get_default_colors(), config=True)
|
|
151
|
debug = CBool(False, config=True)
|
|
151
|
debug = CBool(False, config=True)
|
|
152
|
deep_reload = CBool(False, config=True)
|
|
152
|
deep_reload = CBool(False, config=True)
|
|
153
|
displayhook_class = Type(DisplayHook)
|
|
153
|
displayhook_class = Type(DisplayHook)
|
|
154
|
exit_now = CBool(False)
|
|
154
|
exit_now = CBool(False)
|
|
155
|
filename = Str("<ipython console>")
|
|
155
|
filename = Str("<ipython console>")
|
|
156
|
ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
|
|
156
|
ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
|
|
157
|
logstart = CBool(False, config=True)
|
|
157
|
logstart = CBool(False, config=True)
|
|
158
|
logfile = Str('', config=True)
|
|
158
|
logfile = Str('', config=True)
|
|
159
|
logappend = Str('', config=True)
|
|
159
|
logappend = Str('', config=True)
|
|
160
|
object_info_string_level = Enum((0,1,2), default_value=0,
|
|
160
|
object_info_string_level = Enum((0,1,2), default_value=0,
|
|
161
|
config=True)
|
|
161
|
config=True)
|
|
162
|
pdb = CBool(False, config=True)
|
|
162
|
pdb = CBool(False, config=True)
|
|
163
|
pprint = CBool(True, config=True)
|
|
163
|
pprint = CBool(True, config=True)
|
|
164
|
profile = Str('', config=True)
|
|
164
|
profile = Str('', config=True)
|
|
165
|
prompt_in1 = Str('In [\\#]: ', config=True)
|
|
165
|
prompt_in1 = Str('In [\\#]: ', config=True)
|
|
166
|
prompt_in2 = Str(' .\\D.: ', config=True)
|
|
166
|
prompt_in2 = Str(' .\\D.: ', config=True)
|
|
167
|
prompt_out = Str('Out[\\#]: ', config=True)
|
|
167
|
prompt_out = Str('Out[\\#]: ', config=True)
|
|
168
|
prompts_pad_left = CBool(True, config=True)
|
|
168
|
prompts_pad_left = CBool(True, config=True)
|
|
169
|
quiet = CBool(False, config=True)
|
|
169
|
quiet = CBool(False, config=True)
|
|
170
|
|
|
170
|
|
|
171
|
# The readline stuff will eventually be moved to the terminal subclass
|
|
171
|
# The readline stuff will eventually be moved to the terminal subclass
|
|
172
|
# but for now, we can't do that as readline is welded in everywhere.
|
|
172
|
# but for now, we can't do that as readline is welded in everywhere.
|
|
173
|
readline_use = CBool(True, config=True)
|
|
173
|
readline_use = CBool(True, config=True)
|
|
174
|
readline_merge_completions = CBool(True, config=True)
|
|
174
|
readline_merge_completions = CBool(True, config=True)
|
|
175
|
readline_omit__names = Enum((0,1,2), default_value=0, config=True)
|
|
175
|
readline_omit__names = Enum((0,1,2), default_value=0, config=True)
|
|
176
|
readline_remove_delims = Str('-/~', config=True)
|
|
176
|
readline_remove_delims = Str('-/~', config=True)
|
|
177
|
readline_parse_and_bind = List([
|
|
177
|
readline_parse_and_bind = List([
|
|
178
|
'tab: complete',
|
|
178
|
'tab: complete',
|
|
179
|
'"\C-l": clear-screen',
|
|
179
|
'"\C-l": clear-screen',
|
|
180
|
'set show-all-if-ambiguous on',
|
|
180
|
'set show-all-if-ambiguous on',
|
|
181
|
'"\C-o": tab-insert',
|
|
181
|
'"\C-o": tab-insert',
|
|
182
|
'"\M-i": " "',
|
|
182
|
'"\M-i": " "',
|
|
183
|
'"\M-o": "\d\d\d\d"',
|
|
183
|
'"\M-o": "\d\d\d\d"',
|
|
184
|
'"\M-I": "\d\d\d\d"',
|
|
184
|
'"\M-I": "\d\d\d\d"',
|
|
185
|
'"\C-r": reverse-search-history',
|
|
185
|
'"\C-r": reverse-search-history',
|
|
186
|
'"\C-s": forward-search-history',
|
|
186
|
'"\C-s": forward-search-history',
|
|
187
|
'"\C-p": history-search-backward',
|
|
187
|
'"\C-p": history-search-backward',
|
|
188
|
'"\C-n": history-search-forward',
|
|
188
|
'"\C-n": history-search-forward',
|
|
189
|
'"\e[A": history-search-backward',
|
|
189
|
'"\e[A": history-search-backward',
|
|
190
|
'"\e[B": history-search-forward',
|
|
190
|
'"\e[B": history-search-forward',
|
|
191
|
'"\C-k": kill-line',
|
|
191
|
'"\C-k": kill-line',
|
|
192
|
'"\C-u": unix-line-discard',
|
|
192
|
'"\C-u": unix-line-discard',
|
|
193
|
], allow_none=False, config=True)
|
|
193
|
], allow_none=False, config=True)
|
|
194
|
|
|
194
|
|
|
195
|
# TODO: this part of prompt management should be moved to the frontends.
|
|
195
|
# TODO: this part of prompt management should be moved to the frontends.
|
|
196
|
# Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
|
|
196
|
# Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
|
|
197
|
separate_in = SeparateStr('\n', config=True)
|
|
197
|
separate_in = SeparateStr('\n', config=True)
|
|
198
|
separate_out = SeparateStr('', config=True)
|
|
198
|
separate_out = SeparateStr('', config=True)
|
|
199
|
separate_out2 = SeparateStr('', config=True)
|
|
199
|
separate_out2 = SeparateStr('', config=True)
|
|
200
|
wildcards_case_sensitive = CBool(True, config=True)
|
|
200
|
wildcards_case_sensitive = CBool(True, config=True)
|
|
201
|
xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
|
|
201
|
xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
|
|
202
|
default_value='Context', config=True)
|
|
202
|
default_value='Context', config=True)
|
|
203
|
|
|
203
|
|
|
204
|
# Subcomponents of InteractiveShell
|
|
204
|
# Subcomponents of InteractiveShell
|
|
205
|
alias_manager = Instance('IPython.core.alias.AliasManager')
|
|
205
|
alias_manager = Instance('IPython.core.alias.AliasManager')
|
|
206
|
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
|
|
206
|
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
|
|
207
|
builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
|
|
207
|
builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
|
|
208
|
display_trap = Instance('IPython.core.display_trap.DisplayTrap')
|
|
208
|
display_trap = Instance('IPython.core.display_trap.DisplayTrap')
|
|
209
|
extension_manager = Instance('IPython.core.extensions.ExtensionManager')
|
|
209
|
extension_manager = Instance('IPython.core.extensions.ExtensionManager')
|
|
210
|
plugin_manager = Instance('IPython.core.plugin.PluginManager')
|
|
210
|
plugin_manager = Instance('IPython.core.plugin.PluginManager')
|
|
211
|
payload_manager = Instance('IPython.core.payload.PayloadManager')
|
|
211
|
payload_manager = Instance('IPython.core.payload.PayloadManager')
|
|
212
|
|
|
212
|
|
|
213
|
def __init__(self, config=None, ipython_dir=None,
|
|
213
|
def __init__(self, config=None, ipython_dir=None,
|
|
214
|
user_ns=None, user_global_ns=None,
|
|
214
|
user_ns=None, user_global_ns=None,
|
|
215
|
custom_exceptions=((),None)):
|
|
215
|
custom_exceptions=((),None)):
|
|
216
|
|
|
216
|
|
|
217
|
# This is where traits with a config_key argument are updated
|
|
217
|
# This is where traits with a config_key argument are updated
|
|
218
|
# from the values on config.
|
|
218
|
# from the values on config.
|
|
219
|
super(InteractiveShell, self).__init__(config=config)
|
|
219
|
super(InteractiveShell, self).__init__(config=config)
|
|
220
|
|
|
220
|
|
|
221
|
# These are relatively independent and stateless
|
|
221
|
# These are relatively independent and stateless
|
|
222
|
self.init_ipython_dir(ipython_dir)
|
|
222
|
self.init_ipython_dir(ipython_dir)
|
|
223
|
self.init_instance_attrs()
|
|
223
|
self.init_instance_attrs()
|
|
224
|
|
|
224
|
|
|
225
|
# Create namespaces (user_ns, user_global_ns, etc.)
|
|
225
|
# Create namespaces (user_ns, user_global_ns, etc.)
|
|
226
|
self.init_create_namespaces(user_ns, user_global_ns)
|
|
226
|
self.init_create_namespaces(user_ns, user_global_ns)
|
|
227
|
# This has to be done after init_create_namespaces because it uses
|
|
227
|
# This has to be done after init_create_namespaces because it uses
|
|
228
|
# something in self.user_ns, but before init_sys_modules, which
|
|
228
|
# something in self.user_ns, but before init_sys_modules, which
|
|
229
|
# is the first thing to modify sys.
|
|
229
|
# is the first thing to modify sys.
|
|
230
|
# TODO: When we override sys.stdout and sys.stderr before this class
|
|
230
|
# TODO: When we override sys.stdout and sys.stderr before this class
|
|
231
|
# is created, we are saving the overridden ones here. Not sure if this
|
|
231
|
# is created, we are saving the overridden ones here. Not sure if this
|
|
232
|
# is what we want to do.
|
|
232
|
# is what we want to do.
|
|
233
|
self.save_sys_module_state()
|
|
233
|
self.save_sys_module_state()
|
|
234
|
self.init_sys_modules()
|
|
234
|
self.init_sys_modules()
|
|
235
|
|
|
235
|
|
|
236
|
self.init_history()
|
|
236
|
self.init_history()
|
|
237
|
self.init_encoding()
|
|
237
|
self.init_encoding()
|
|
238
|
self.init_prefilter()
|
|
238
|
self.init_prefilter()
|
|
239
|
|
|
239
|
|
|
240
|
Magic.__init__(self, self)
|
|
240
|
Magic.__init__(self, self)
|
|
241
|
|
|
241
|
|
|
242
|
self.init_syntax_highlighting()
|
|
242
|
self.init_syntax_highlighting()
|
|
243
|
self.init_hooks()
|
|
243
|
self.init_hooks()
|
|
244
|
self.init_pushd_popd_magic()
|
|
244
|
self.init_pushd_popd_magic()
|
|
245
|
# self.init_traceback_handlers use to be here, but we moved it below
|
|
245
|
# self.init_traceback_handlers use to be here, but we moved it below
|
|
246
|
# because it and init_io have to come after init_readline.
|
|
246
|
# because it and init_io have to come after init_readline.
|
|
247
|
self.init_user_ns()
|
|
247
|
self.init_user_ns()
|
|
248
|
self.init_logger()
|
|
248
|
self.init_logger()
|
|
249
|
self.init_alias()
|
|
249
|
self.init_alias()
|
|
250
|
self.init_builtins()
|
|
250
|
self.init_builtins()
|
|
251
|
|
|
251
|
|
|
252
|
# pre_config_initialization
|
|
252
|
# pre_config_initialization
|
|
253
|
self.init_shadow_hist()
|
|
253
|
self.init_shadow_hist()
|
|
254
|
|
|
254
|
|
|
255
|
# The next section should contain averything that was in ipmaker.
|
|
255
|
# The next section should contain averything that was in ipmaker.
|
|
256
|
self.init_logstart()
|
|
256
|
self.init_logstart()
|
|
257
|
|
|
257
|
|
|
258
|
# The following was in post_config_initialization
|
|
258
|
# The following was in post_config_initialization
|
|
259
|
self.init_inspector()
|
|
259
|
self.init_inspector()
|
|
260
|
# init_readline() must come before init_io(), because init_io uses
|
|
260
|
# init_readline() must come before init_io(), because init_io uses
|
|
261
|
# readline related things.
|
|
261
|
# readline related things.
|
|
262
|
self.init_readline()
|
|
262
|
self.init_readline()
|
|
263
|
# init_completer must come after init_readline, because it needs to
|
|
263
|
# init_completer must come after init_readline, because it needs to
|
|
264
|
# know whether readline is present or not system-wide to configure the
|
|
264
|
# know whether readline is present or not system-wide to configure the
|
|
265
|
# completers, since the completion machinery can now operate
|
|
265
|
# completers, since the completion machinery can now operate
|
|
266
|
# independently of readline (e.g. over the network)
|
|
266
|
# independently of readline (e.g. over the network)
|
|
267
|
self.init_completer()
|
|
267
|
self.init_completer()
|
|
268
|
# TODO: init_io() needs to happen before init_traceback handlers
|
|
268
|
# TODO: init_io() needs to happen before init_traceback handlers
|
|
269
|
# because the traceback handlers hardcode the stdout/stderr streams.
|
|
269
|
# because the traceback handlers hardcode the stdout/stderr streams.
|
|
270
|
# This logic in in debugger.Pdb and should eventually be changed.
|
|
270
|
# This logic in in debugger.Pdb and should eventually be changed.
|
|
271
|
self.init_io()
|
|
271
|
self.init_io()
|
|
272
|
self.init_traceback_handlers(custom_exceptions)
|
|
272
|
self.init_traceback_handlers(custom_exceptions)
|
|
273
|
self.init_prompts()
|
|
273
|
self.init_prompts()
|
|
274
|
self.init_displayhook()
|
|
274
|
self.init_displayhook()
|
|
275
|
self.init_reload_doctest()
|
|
275
|
self.init_reload_doctest()
|
|
276
|
self.init_magics()
|
|
276
|
self.init_magics()
|
|
277
|
self.init_pdb()
|
|
277
|
self.init_pdb()
|
|
278
|
self.init_extension_manager()
|
|
278
|
self.init_extension_manager()
|
|
279
|
self.init_plugin_manager()
|
|
279
|
self.init_plugin_manager()
|
|
280
|
self.init_payload()
|
|
280
|
self.init_payload()
|
|
281
|
self.hooks.late_startup_hook()
|
|
281
|
self.hooks.late_startup_hook()
|
|
282
|
atexit.register(self.atexit_operations)
|
|
282
|
atexit.register(self.atexit_operations)
|
|
283
|
|
|
283
|
|
|
284
|
@classmethod
|
|
284
|
@classmethod
|
|
285
|
def instance(cls, *args, **kwargs):
|
|
285
|
def instance(cls, *args, **kwargs):
|
|
286
|
"""Returns a global InteractiveShell instance."""
|
|
286
|
"""Returns a global InteractiveShell instance."""
|
|
287
|
if cls._instance is None:
|
|
287
|
if cls._instance is None:
|
|
288
|
inst = cls(*args, **kwargs)
|
|
288
|
inst = cls(*args, **kwargs)
|
|
289
|
# Now make sure that the instance will also be returned by
|
|
289
|
# Now make sure that the instance will also be returned by
|
|
290
|
# the subclasses instance attribute.
|
|
290
|
# the subclasses instance attribute.
|
|
291
|
for subclass in cls.mro():
|
|
291
|
for subclass in cls.mro():
|
|
292
|
if issubclass(cls, subclass) and \
|
|
292
|
if issubclass(cls, subclass) and \
|
|
293
|
issubclass(subclass, InteractiveShell):
|
|
293
|
issubclass(subclass, InteractiveShell):
|
|
294
|
subclass._instance = inst
|
|
294
|
subclass._instance = inst
|
|
295
|
else:
|
|
295
|
else:
|
|
296
|
break
|
|
296
|
break
|
|
297
|
if isinstance(cls._instance, cls):
|
|
297
|
if isinstance(cls._instance, cls):
|
|
298
|
return cls._instance
|
|
298
|
return cls._instance
|
|
299
|
else:
|
|
299
|
else:
|
|
300
|
raise MultipleInstanceError(
|
|
300
|
raise MultipleInstanceError(
|
|
301
|
'Multiple incompatible subclass instances of '
|
|
301
|
'Multiple incompatible subclass instances of '
|
|
302
|
'InteractiveShell are being created.'
|
|
302
|
'InteractiveShell are being created.'
|
|
303
|
)
|
|
303
|
)
|
|
304
|
|
|
304
|
|
|
305
|
@classmethod
|
|
305
|
@classmethod
|
|
306
|
def initialized(cls):
|
|
306
|
def initialized(cls):
|
|
307
|
return hasattr(cls, "_instance")
|
|
307
|
return hasattr(cls, "_instance")
|
|
308
|
|
|
308
|
|
|
309
|
def get_ipython(self):
|
|
309
|
def get_ipython(self):
|
|
310
|
"""Return the currently running IPython instance."""
|
|
310
|
"""Return the currently running IPython instance."""
|
|
311
|
return self
|
|
311
|
return self
|
|
312
|
|
|
312
|
|
|
313
|
#-------------------------------------------------------------------------
|
|
313
|
#-------------------------------------------------------------------------
|
|
314
|
# Trait changed handlers
|
|
314
|
# Trait changed handlers
|
|
315
|
#-------------------------------------------------------------------------
|
|
315
|
#-------------------------------------------------------------------------
|
|
316
|
|
|
316
|
|
|
317
|
def _ipython_dir_changed(self, name, new):
|
|
317
|
def _ipython_dir_changed(self, name, new):
|
|
318
|
if not os.path.isdir(new):
|
|
318
|
if not os.path.isdir(new):
|
|
319
|
os.makedirs(new, mode = 0777)
|
|
319
|
os.makedirs(new, mode = 0777)
|
|
320
|
|
|
320
|
|
|
321
|
def set_autoindent(self,value=None):
|
|
321
|
def set_autoindent(self,value=None):
|
|
322
|
"""Set the autoindent flag, checking for readline support.
|
|
322
|
"""Set the autoindent flag, checking for readline support.
|
|
323
|
|
|
323
|
|
|
324
|
If called with no arguments, it acts as a toggle."""
|
|
324
|
If called with no arguments, it acts as a toggle."""
|
|
325
|
|
|
325
|
|
|
326
|
if not self.has_readline:
|
|
326
|
if not self.has_readline:
|
|
327
|
if os.name == 'posix':
|
|
327
|
if os.name == 'posix':
|
|
328
|
warn("The auto-indent feature requires the readline library")
|
|
328
|
warn("The auto-indent feature requires the readline library")
|
|
329
|
self.autoindent = 0
|
|
329
|
self.autoindent = 0
|
|
330
|
return
|
|
330
|
return
|
|
331
|
if value is None:
|
|
331
|
if value is None:
|
|
332
|
self.autoindent = not self.autoindent
|
|
332
|
self.autoindent = not self.autoindent
|
|
333
|
else:
|
|
333
|
else:
|
|
334
|
self.autoindent = value
|
|
334
|
self.autoindent = value
|
|
335
|
|
|
335
|
|
|
336
|
#-------------------------------------------------------------------------
|
|
336
|
#-------------------------------------------------------------------------
|
|
337
|
# init_* methods called by __init__
|
|
337
|
# init_* methods called by __init__
|
|
338
|
#-------------------------------------------------------------------------
|
|
338
|
#-------------------------------------------------------------------------
|
|
339
|
|
|
339
|
|
|
340
|
def init_ipython_dir(self, ipython_dir):
|
|
340
|
def init_ipython_dir(self, ipython_dir):
|
|
341
|
if ipython_dir is not None:
|
|
341
|
if ipython_dir is not None:
|
|
342
|
self.ipython_dir = ipython_dir
|
|
342
|
self.ipython_dir = ipython_dir
|
|
343
|
self.config.Global.ipython_dir = self.ipython_dir
|
|
343
|
self.config.Global.ipython_dir = self.ipython_dir
|
|
344
|
return
|
|
344
|
return
|
|
345
|
|
|
345
|
|
|
346
|
if hasattr(self.config.Global, 'ipython_dir'):
|
|
346
|
if hasattr(self.config.Global, 'ipython_dir'):
|
|
347
|
self.ipython_dir = self.config.Global.ipython_dir
|
|
347
|
self.ipython_dir = self.config.Global.ipython_dir
|
|
348
|
else:
|
|
348
|
else:
|
|
349
|
self.ipython_dir = get_ipython_dir()
|
|
349
|
self.ipython_dir = get_ipython_dir()
|
|
350
|
|
|
350
|
|
|
351
|
# All children can just read this
|
|
351
|
# All children can just read this
|
|
352
|
self.config.Global.ipython_dir = self.ipython_dir
|
|
352
|
self.config.Global.ipython_dir = self.ipython_dir
|
|
353
|
|
|
353
|
|
|
354
|
def init_instance_attrs(self):
|
|
354
|
def init_instance_attrs(self):
|
|
355
|
self.more = False
|
|
355
|
self.more = False
|
|
356
|
|
|
356
|
|
|
357
|
# command compiler
|
|
357
|
# command compiler
|
|
358
|
self.compile = codeop.CommandCompiler()
|
|
358
|
self.compile = codeop.CommandCompiler()
|
|
359
|
|
|
359
|
|
|
360
|
# User input buffer
|
|
360
|
# User input buffer
|
|
361
|
self.buffer = []
|
|
361
|
self.buffer = []
|
|
362
|
|
|
362
|
|
|
363
|
# Make an empty namespace, which extension writers can rely on both
|
|
363
|
# Make an empty namespace, which extension writers can rely on both
|
|
364
|
# existing and NEVER being used by ipython itself. This gives them a
|
|
364
|
# existing and NEVER being used by ipython itself. This gives them a
|
|
365
|
# convenient location for storing additional information and state
|
|
365
|
# convenient location for storing additional information and state
|
|
366
|
# their extensions may require, without fear of collisions with other
|
|
366
|
# their extensions may require, without fear of collisions with other
|
|
367
|
# ipython names that may develop later.
|
|
367
|
# ipython names that may develop later.
|
|
368
|
self.meta = Struct()
|
|
368
|
self.meta = Struct()
|
|
369
|
|
|
369
|
|
|
370
|
# Object variable to store code object waiting execution. This is
|
|
370
|
# Object variable to store code object waiting execution. This is
|
|
371
|
# used mainly by the multithreaded shells, but it can come in handy in
|
|
371
|
# used mainly by the multithreaded shells, but it can come in handy in
|
|
372
|
# other situations. No need to use a Queue here, since it's a single
|
|
372
|
# other situations. No need to use a Queue here, since it's a single
|
|
373
|
# item which gets cleared once run.
|
|
373
|
# item which gets cleared once run.
|
|
374
|
self.code_to_run = None
|
|
374
|
self.code_to_run = None
|
|
375
|
|
|
375
|
|
|
376
|
# Temporary files used for various purposes. Deleted at exit.
|
|
376
|
# Temporary files used for various purposes. Deleted at exit.
|
|
377
|
self.tempfiles = []
|
|
377
|
self.tempfiles = []
|
|
378
|
|
|
378
|
|
|
379
|
# Keep track of readline usage (later set by init_readline)
|
|
379
|
# Keep track of readline usage (later set by init_readline)
|
|
380
|
self.has_readline = False
|
|
380
|
self.has_readline = False
|
|
381
|
|
|
381
|
|
|
382
|
# keep track of where we started running (mainly for crash post-mortem)
|
|
382
|
# keep track of where we started running (mainly for crash post-mortem)
|
|
383
|
# This is not being used anywhere currently.
|
|
383
|
# This is not being used anywhere currently.
|
|
384
|
self.starting_dir = os.getcwd()
|
|
384
|
self.starting_dir = os.getcwd()
|
|
385
|
|
|
385
|
|
|
386
|
# Indentation management
|
|
386
|
# Indentation management
|
|
387
|
self.indent_current_nsp = 0
|
|
387
|
self.indent_current_nsp = 0
|
|
388
|
|
|
388
|
|
|
389
|
def init_encoding(self):
|
|
389
|
def init_encoding(self):
|
|
390
|
# Get system encoding at startup time. Certain terminals (like Emacs
|
|
390
|
# Get system encoding at startup time. Certain terminals (like Emacs
|
|
391
|
# under Win32 have it set to None, and we need to have a known valid
|
|
391
|
# under Win32 have it set to None, and we need to have a known valid
|
|
392
|
# encoding to use in the raw_input() method
|
|
392
|
# encoding to use in the raw_input() method
|
|
393
|
try:
|
|
393
|
try:
|
|
394
|
self.stdin_encoding = sys.stdin.encoding or 'ascii'
|
|
394
|
self.stdin_encoding = sys.stdin.encoding or 'ascii'
|
|
395
|
except AttributeError:
|
|
395
|
except AttributeError:
|
|
396
|
self.stdin_encoding = 'ascii'
|
|
396
|
self.stdin_encoding = 'ascii'
|
|
397
|
|
|
397
|
|
|
398
|
def init_syntax_highlighting(self):
|
|
398
|
def init_syntax_highlighting(self):
|
|
399
|
# Python source parser/formatter for syntax highlighting
|
|
399
|
# Python source parser/formatter for syntax highlighting
|
|
400
|
pyformat = PyColorize.Parser().format
|
|
400
|
pyformat = PyColorize.Parser().format
|
|
401
|
self.pycolorize = lambda src: pyformat(src,'str',self.colors)
|
|
401
|
self.pycolorize = lambda src: pyformat(src,'str',self.colors)
|
|
402
|
|
|
402
|
|
|
403
|
def init_pushd_popd_magic(self):
|
|
403
|
def init_pushd_popd_magic(self):
|
|
404
|
# for pushd/popd management
|
|
404
|
# for pushd/popd management
|
|
405
|
try:
|
|
405
|
try:
|
|
406
|
self.home_dir = get_home_dir()
|
|
406
|
self.home_dir = get_home_dir()
|
|
407
|
except HomeDirError, msg:
|
|
407
|
except HomeDirError, msg:
|
|
408
|
fatal(msg)
|
|
408
|
fatal(msg)
|
|
409
|
|
|
409
|
|
|
410
|
self.dir_stack = []
|
|
410
|
self.dir_stack = []
|
|
411
|
|
|
411
|
|
|
412
|
def init_logger(self):
|
|
412
|
def init_logger(self):
|
|
413
|
self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
|
|
413
|
self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
|
|
414
|
# local shortcut, this is used a LOT
|
|
414
|
# local shortcut, this is used a LOT
|
|
415
|
self.log = self.logger.log
|
|
415
|
self.log = self.logger.log
|
|
416
|
|
|
416
|
|
|
417
|
def init_logstart(self):
|
|
417
|
def init_logstart(self):
|
|
418
|
if self.logappend:
|
|
418
|
if self.logappend:
|
|
419
|
self.magic_logstart(self.logappend + ' append')
|
|
419
|
self.magic_logstart(self.logappend + ' append')
|
|
420
|
elif self.logfile:
|
|
420
|
elif self.logfile:
|
|
421
|
self.magic_logstart(self.logfile)
|
|
421
|
self.magic_logstart(self.logfile)
|
|
422
|
elif self.logstart:
|
|
422
|
elif self.logstart:
|
|
423
|
self.magic_logstart()
|
|
423
|
self.magic_logstart()
|
|
424
|
|
|
424
|
|
|
425
|
def init_builtins(self):
|
|
425
|
def init_builtins(self):
|
|
426
|
self.builtin_trap = BuiltinTrap(shell=self)
|
|
426
|
self.builtin_trap = BuiltinTrap(shell=self)
|
|
427
|
|
|
427
|
|
|
428
|
def init_inspector(self):
|
|
428
|
def init_inspector(self):
|
|
429
|
# Object inspector
|
|
429
|
# Object inspector
|
|
430
|
self.inspector = oinspect.Inspector(oinspect.InspectColors,
|
|
430
|
self.inspector = oinspect.Inspector(oinspect.InspectColors,
|
|
431
|
PyColorize.ANSICodeColors,
|
|
431
|
PyColorize.ANSICodeColors,
|
|
432
|
'NoColor',
|
|
432
|
'NoColor',
|
|
433
|
self.object_info_string_level)
|
|
433
|
self.object_info_string_level)
|
|
434
|
|
|
434
|
|
|
435
|
def init_io(self):
|
|
435
|
def init_io(self):
|
|
436
|
import IPython.utils.io
|
|
436
|
import IPython.utils.io
|
|
437
|
if sys.platform == 'win32' and self.has_readline:
|
|
437
|
if sys.platform == 'win32' and self.has_readline:
|
|
438
|
Term = io.IOTerm(
|
|
438
|
Term = io.IOTerm(
|
|
439
|
cout=self.readline._outputfile,cerr=self.readline._outputfile
|
|
439
|
cout=self.readline._outputfile,cerr=self.readline._outputfile
|
|
440
|
)
|
|
440
|
)
|
|
441
|
else:
|
|
441
|
else:
|
|
442
|
Term = io.IOTerm()
|
|
442
|
Term = io.IOTerm()
|
|
443
|
io.Term = Term
|
|
443
|
io.Term = Term
|
|
444
|
|
|
444
|
|
|
445
|
def init_prompts(self):
|
|
445
|
def init_prompts(self):
|
|
446
|
# TODO: This is a pass for now because the prompts are managed inside
|
|
446
|
# TODO: This is a pass for now because the prompts are managed inside
|
|
447
|
# the DisplayHook. Once there is a separate prompt manager, this
|
|
447
|
# the DisplayHook. Once there is a separate prompt manager, this
|
|
448
|
# will initialize that object and all prompt related information.
|
|
448
|
# will initialize that object and all prompt related information.
|
|
449
|
pass
|
|
449
|
pass
|
|
450
|
|
|
450
|
|
|
451
|
def init_displayhook(self):
|
|
451
|
def init_displayhook(self):
|
|
452
|
# Initialize displayhook, set in/out prompts and printing system
|
|
452
|
# Initialize displayhook, set in/out prompts and printing system
|
|
453
|
self.displayhook = self.displayhook_class(
|
|
453
|
self.displayhook = self.displayhook_class(
|
|
454
|
shell=self,
|
|
454
|
shell=self,
|
|
455
|
cache_size=self.cache_size,
|
|
455
|
cache_size=self.cache_size,
|
|
456
|
input_sep = self.separate_in,
|
|
456
|
input_sep = self.separate_in,
|
|
457
|
output_sep = self.separate_out,
|
|
457
|
output_sep = self.separate_out,
|
|
458
|
output_sep2 = self.separate_out2,
|
|
458
|
output_sep2 = self.separate_out2,
|
|
459
|
ps1 = self.prompt_in1,
|
|
459
|
ps1 = self.prompt_in1,
|
|
460
|
ps2 = self.prompt_in2,
|
|
460
|
ps2 = self.prompt_in2,
|
|
461
|
ps_out = self.prompt_out,
|
|
461
|
ps_out = self.prompt_out,
|
|
462
|
pad_left = self.prompts_pad_left
|
|
462
|
pad_left = self.prompts_pad_left
|
|
463
|
)
|
|
463
|
)
|
|
464
|
# This is a context manager that installs/revmoes the displayhook at
|
|
464
|
# This is a context manager that installs/revmoes the displayhook at
|
|
465
|
# the appropriate time.
|
|
465
|
# the appropriate time.
|
|
466
|
self.display_trap = DisplayTrap(hook=self.displayhook)
|
|
466
|
self.display_trap = DisplayTrap(hook=self.displayhook)
|
|
467
|
|
|
467
|
|
|
468
|
def init_reload_doctest(self):
|
|
468
|
def init_reload_doctest(self):
|
|
469
|
# Do a proper resetting of doctest, including the necessary displayhook
|
|
469
|
# Do a proper resetting of doctest, including the necessary displayhook
|
|
470
|
# monkeypatching
|
|
470
|
# monkeypatching
|
|
471
|
try:
|
|
471
|
try:
|
|
472
|
doctest_reload()
|
|
472
|
doctest_reload()
|
|
473
|
except ImportError:
|
|
473
|
except ImportError:
|
|
474
|
warn("doctest module does not exist.")
|
|
474
|
warn("doctest module does not exist.")
|
|
475
|
|
|
475
|
|
|
476
|
#-------------------------------------------------------------------------
|
|
476
|
#-------------------------------------------------------------------------
|
|
477
|
# Things related to injections into the sys module
|
|
477
|
# Things related to injections into the sys module
|
|
478
|
#-------------------------------------------------------------------------
|
|
478
|
#-------------------------------------------------------------------------
|
|
479
|
|
|
479
|
|
|
480
|
def save_sys_module_state(self):
|
|
480
|
def save_sys_module_state(self):
|
|
481
|
"""Save the state of hooks in the sys module.
|
|
481
|
"""Save the state of hooks in the sys module.
|
|
482
|
|
|
482
|
|
|
483
|
This has to be called after self.user_ns is created.
|
|
483
|
This has to be called after self.user_ns is created.
|
|
484
|
"""
|
|
484
|
"""
|
|
485
|
self._orig_sys_module_state = {}
|
|
485
|
self._orig_sys_module_state = {}
|
|
486
|
self._orig_sys_module_state['stdin'] = sys.stdin
|
|
486
|
self._orig_sys_module_state['stdin'] = sys.stdin
|
|
487
|
self._orig_sys_module_state['stdout'] = sys.stdout
|
|
487
|
self._orig_sys_module_state['stdout'] = sys.stdout
|
|
488
|
self._orig_sys_module_state['stderr'] = sys.stderr
|
|
488
|
self._orig_sys_module_state['stderr'] = sys.stderr
|
|
489
|
self._orig_sys_module_state['excepthook'] = sys.excepthook
|
|
489
|
self._orig_sys_module_state['excepthook'] = sys.excepthook
|
|
490
|
try:
|
|
490
|
try:
|
|
491
|
self._orig_sys_modules_main_name = self.user_ns['__name__']
|
|
491
|
self._orig_sys_modules_main_name = self.user_ns['__name__']
|
|
492
|
except KeyError:
|
|
492
|
except KeyError:
|
|
493
|
pass
|
|
493
|
pass
|
|
494
|
|
|
494
|
|
|
495
|
def restore_sys_module_state(self):
|
|
495
|
def restore_sys_module_state(self):
|
|
496
|
"""Restore the state of the sys module."""
|
|
496
|
"""Restore the state of the sys module."""
|
|
497
|
try:
|
|
497
|
try:
|
|
498
|
for k, v in self._orig_sys_module_state.items():
|
|
498
|
for k, v in self._orig_sys_module_state.items():
|
|
499
|
setattr(sys, k, v)
|
|
499
|
setattr(sys, k, v)
|
|
500
|
except AttributeError:
|
|
500
|
except AttributeError:
|
|
501
|
pass
|
|
501
|
pass
|
|
502
|
# Reset what what done in self.init_sys_modules
|
|
502
|
# Reset what what done in self.init_sys_modules
|
|
503
|
try:
|
|
503
|
try:
|
|
504
|
sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
|
|
504
|
sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
|
|
505
|
except (AttributeError, KeyError):
|
|
505
|
except (AttributeError, KeyError):
|
|
506
|
pass
|
|
506
|
pass
|
|
507
|
|
|
507
|
|
|
508
|
#-------------------------------------------------------------------------
|
|
508
|
#-------------------------------------------------------------------------
|
|
509
|
# Things related to hooks
|
|
509
|
# Things related to hooks
|
|
510
|
#-------------------------------------------------------------------------
|
|
510
|
#-------------------------------------------------------------------------
|
|
511
|
|
|
511
|
|
|
512
|
def init_hooks(self):
|
|
512
|
def init_hooks(self):
|
|
513
|
# hooks holds pointers used for user-side customizations
|
|
513
|
# hooks holds pointers used for user-side customizations
|
|
514
|
self.hooks = Struct()
|
|
514
|
self.hooks = Struct()
|
|
515
|
|
|
515
|
|
|
516
|
self.strdispatchers = {}
|
|
516
|
self.strdispatchers = {}
|
|
517
|
|
|
517
|
|
|
518
|
# Set all default hooks, defined in the IPython.hooks module.
|
|
518
|
# Set all default hooks, defined in the IPython.hooks module.
|
|
519
|
hooks = IPython.core.hooks
|
|
519
|
hooks = IPython.core.hooks
|
|
520
|
for hook_name in hooks.__all__:
|
|
520
|
for hook_name in hooks.__all__:
|
|
521
|
# default hooks have priority 100, i.e. low; user hooks should have
|
|
521
|
# default hooks have priority 100, i.e. low; user hooks should have
|
|
522
|
# 0-100 priority
|
|
522
|
# 0-100 priority
|
|
523
|
self.set_hook(hook_name,getattr(hooks,hook_name), 100)
|
|
523
|
self.set_hook(hook_name,getattr(hooks,hook_name), 100)
|
|
524
|
|
|
524
|
|
|
525
|
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
|
|
525
|
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
|
|
526
|
"""set_hook(name,hook) -> sets an internal IPython hook.
|
|
526
|
"""set_hook(name,hook) -> sets an internal IPython hook.
|
|
527
|
|
|
527
|
|
|
528
|
IPython exposes some of its internal API as user-modifiable hooks. By
|
|
528
|
IPython exposes some of its internal API as user-modifiable hooks. By
|
|
529
|
adding your function to one of these hooks, you can modify IPython's
|
|
529
|
adding your function to one of these hooks, you can modify IPython's
|
|
530
|
behavior to call at runtime your own routines."""
|
|
530
|
behavior to call at runtime your own routines."""
|
|
531
|
|
|
531
|
|
|
532
|
# At some point in the future, this should validate the hook before it
|
|
532
|
# At some point in the future, this should validate the hook before it
|
|
533
|
# accepts it. Probably at least check that the hook takes the number
|
|
533
|
# accepts it. Probably at least check that the hook takes the number
|
|
534
|
# of args it's supposed to.
|
|
534
|
# of args it's supposed to.
|
|
535
|
|
|
535
|
|
|
536
|
f = new.instancemethod(hook,self,self.__class__)
|
|
536
|
f = new.instancemethod(hook,self,self.__class__)
|
|
537
|
|
|
537
|
|
|
538
|
# check if the hook is for strdispatcher first
|
|
538
|
# check if the hook is for strdispatcher first
|
|
539
|
if str_key is not None:
|
|
539
|
if str_key is not None:
|
|
540
|
sdp = self.strdispatchers.get(name, StrDispatch())
|
|
540
|
sdp = self.strdispatchers.get(name, StrDispatch())
|
|
541
|
sdp.add_s(str_key, f, priority )
|
|
541
|
sdp.add_s(str_key, f, priority )
|
|
542
|
self.strdispatchers[name] = sdp
|
|
542
|
self.strdispatchers[name] = sdp
|
|
543
|
return
|
|
543
|
return
|
|
544
|
if re_key is not None:
|
|
544
|
if re_key is not None:
|
|
545
|
sdp = self.strdispatchers.get(name, StrDispatch())
|
|
545
|
sdp = self.strdispatchers.get(name, StrDispatch())
|
|
546
|
sdp.add_re(re.compile(re_key), f, priority )
|
|
546
|
sdp.add_re(re.compile(re_key), f, priority )
|
|
547
|
self.strdispatchers[name] = sdp
|
|
547
|
self.strdispatchers[name] = sdp
|
|
548
|
return
|
|
548
|
return
|
|
549
|
|
|
549
|
|
|
550
|
dp = getattr(self.hooks, name, None)
|
|
550
|
dp = getattr(self.hooks, name, None)
|
|
551
|
if name not in IPython.core.hooks.__all__:
|
|
551
|
if name not in IPython.core.hooks.__all__:
|
|
552
|
print "Warning! Hook '%s' is not one of %s" % \
|
|
552
|
print "Warning! Hook '%s' is not one of %s" % \
|
|
553
|
(name, IPython.core.hooks.__all__ )
|
|
553
|
(name, IPython.core.hooks.__all__ )
|
|
554
|
if not dp:
|
|
554
|
if not dp:
|
|
555
|
dp = IPython.core.hooks.CommandChainDispatcher()
|
|
555
|
dp = IPython.core.hooks.CommandChainDispatcher()
|
|
556
|
|
|
556
|
|
|
557
|
try:
|
|
557
|
try:
|
|
558
|
dp.add(f,priority)
|
|
558
|
dp.add(f,priority)
|
|
559
|
except AttributeError:
|
|
559
|
except AttributeError:
|
|
560
|
# it was not commandchain, plain old func - replace
|
|
560
|
# it was not commandchain, plain old func - replace
|
|
561
|
dp = f
|
|
561
|
dp = f
|
|
562
|
|
|
562
|
|
|
563
|
setattr(self.hooks,name, dp)
|
|
563
|
setattr(self.hooks,name, dp)
|
|
564
|
|
|
564
|
|
|
565
|
#-------------------------------------------------------------------------
|
|
565
|
#-------------------------------------------------------------------------
|
|
566
|
# Things related to the "main" module
|
|
566
|
# Things related to the "main" module
|
|
567
|
#-------------------------------------------------------------------------
|
|
567
|
#-------------------------------------------------------------------------
|
|
568
|
|
|
568
|
|
|
569
|
def new_main_mod(self,ns=None):
|
|
569
|
def new_main_mod(self,ns=None):
|
|
570
|
"""Return a new 'main' module object for user code execution.
|
|
570
|
"""Return a new 'main' module object for user code execution.
|
|
571
|
"""
|
|
571
|
"""
|
|
572
|
main_mod = self._user_main_module
|
|
572
|
main_mod = self._user_main_module
|
|
573
|
init_fakemod_dict(main_mod,ns)
|
|
573
|
init_fakemod_dict(main_mod,ns)
|
|
574
|
return main_mod
|
|
574
|
return main_mod
|
|
575
|
|
|
575
|
|
|
576
|
def cache_main_mod(self,ns,fname):
|
|
576
|
def cache_main_mod(self,ns,fname):
|
|
577
|
"""Cache a main module's namespace.
|
|
577
|
"""Cache a main module's namespace.
|
|
578
|
|
|
578
|
|
|
579
|
When scripts are executed via %run, we must keep a reference to the
|
|
579
|
When scripts are executed via %run, we must keep a reference to the
|
|
580
|
namespace of their __main__ module (a FakeModule instance) around so
|
|
580
|
namespace of their __main__ module (a FakeModule instance) around so
|
|
581
|
that Python doesn't clear it, rendering objects defined therein
|
|
581
|
that Python doesn't clear it, rendering objects defined therein
|
|
582
|
useless.
|
|
582
|
useless.
|
|
583
|
|
|
583
|
|
|
584
|
This method keeps said reference in a private dict, keyed by the
|
|
584
|
This method keeps said reference in a private dict, keyed by the
|
|
585
|
absolute path of the module object (which corresponds to the script
|
|
585
|
absolute path of the module object (which corresponds to the script
|
|
586
|
path). This way, for multiple executions of the same script we only
|
|
586
|
path). This way, for multiple executions of the same script we only
|
|
587
|
keep one copy of the namespace (the last one), thus preventing memory
|
|
587
|
keep one copy of the namespace (the last one), thus preventing memory
|
|
588
|
leaks from old references while allowing the objects from the last
|
|
588
|
leaks from old references while allowing the objects from the last
|
|
589
|
execution to be accessible.
|
|
589
|
execution to be accessible.
|
|
590
|
|
|
590
|
|
|
591
|
Note: we can not allow the actual FakeModule instances to be deleted,
|
|
591
|
Note: we can not allow the actual FakeModule instances to be deleted,
|
|
592
|
because of how Python tears down modules (it hard-sets all their
|
|
592
|
because of how Python tears down modules (it hard-sets all their
|
|
593
|
references to None without regard for reference counts). This method
|
|
593
|
references to None without regard for reference counts). This method
|
|
594
|
must therefore make a *copy* of the given namespace, to allow the
|
|
594
|
must therefore make a *copy* of the given namespace, to allow the
|
|
595
|
original module's __dict__ to be cleared and reused.
|
|
595
|
original module's __dict__ to be cleared and reused.
|
|
596
|
|
|
596
|
|
|
597
|
|
|
597
|
|
|
598
|
Parameters
|
|
598
|
Parameters
|
|
599
|
----------
|
|
599
|
----------
|
|
600
|
ns : a namespace (a dict, typically)
|
|
600
|
ns : a namespace (a dict, typically)
|
|
601
|
|
|
601
|
|
|
602
|
fname : str
|
|
602
|
fname : str
|
|
603
|
Filename associated with the namespace.
|
|
603
|
Filename associated with the namespace.
|
|
604
|
|
|
604
|
|
|
605
|
Examples
|
|
605
|
Examples
|
|
606
|
--------
|
|
606
|
--------
|
|
607
|
|
|
607
|
|
|
608
|
In [10]: import IPython
|
|
608
|
In [10]: import IPython
|
|
609
|
|
|
609
|
|
|
610
|
In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
|
|
610
|
In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
|
|
611
|
|
|
611
|
|
|
612
|
In [12]: IPython.__file__ in _ip._main_ns_cache
|
|
612
|
In [12]: IPython.__file__ in _ip._main_ns_cache
|
|
613
|
Out[12]: True
|
|
613
|
Out[12]: True
|
|
614
|
"""
|
|
614
|
"""
|
|
615
|
self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
|
|
615
|
self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
|
|
616
|
|
|
616
|
|
|
617
|
def clear_main_mod_cache(self):
|
|
617
|
def clear_main_mod_cache(self):
|
|
618
|
"""Clear the cache of main modules.
|
|
618
|
"""Clear the cache of main modules.
|
|
619
|
|
|
619
|
|
|
620
|
Mainly for use by utilities like %reset.
|
|
620
|
Mainly for use by utilities like %reset.
|
|
621
|
|
|
621
|
|
|
622
|
Examples
|
|
622
|
Examples
|
|
623
|
--------
|
|
623
|
--------
|
|
624
|
|
|
624
|
|
|
625
|
In [15]: import IPython
|
|
625
|
In [15]: import IPython
|
|
626
|
|
|
626
|
|
|
627
|
In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
|
|
627
|
In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
|
|
628
|
|
|
628
|
|
|
629
|
In [17]: len(_ip._main_ns_cache) > 0
|
|
629
|
In [17]: len(_ip._main_ns_cache) > 0
|
|
630
|
Out[17]: True
|
|
630
|
Out[17]: True
|
|
631
|
|
|
631
|
|
|
632
|
In [18]: _ip.clear_main_mod_cache()
|
|
632
|
In [18]: _ip.clear_main_mod_cache()
|
|
633
|
|
|
633
|
|
|
634
|
In [19]: len(_ip._main_ns_cache) == 0
|
|
634
|
In [19]: len(_ip._main_ns_cache) == 0
|
|
635
|
Out[19]: True
|
|
635
|
Out[19]: True
|
|
636
|
"""
|
|
636
|
"""
|
|
637
|
self._main_ns_cache.clear()
|
|
637
|
self._main_ns_cache.clear()
|
|
638
|
|
|
638
|
|
|
639
|
#-------------------------------------------------------------------------
|
|
639
|
#-------------------------------------------------------------------------
|
|
640
|
# Things related to debugging
|
|
640
|
# Things related to debugging
|
|
641
|
#-------------------------------------------------------------------------
|
|
641
|
#-------------------------------------------------------------------------
|
|
642
|
|
|
642
|
|
|
643
|
def init_pdb(self):
|
|
643
|
def init_pdb(self):
|
|
644
|
# Set calling of pdb on exceptions
|
|
644
|
# Set calling of pdb on exceptions
|
|
645
|
# self.call_pdb is a property
|
|
645
|
# self.call_pdb is a property
|
|
646
|
self.call_pdb = self.pdb
|
|
646
|
self.call_pdb = self.pdb
|
|
647
|
|
|
647
|
|
|
648
|
def _get_call_pdb(self):
|
|
648
|
def _get_call_pdb(self):
|
|
649
|
return self._call_pdb
|
|
649
|
return self._call_pdb
|
|
650
|
|
|
650
|
|
|
651
|
def _set_call_pdb(self,val):
|
|
651
|
def _set_call_pdb(self,val):
|
|
652
|
|
|
652
|
|
|
653
|
if val not in (0,1,False,True):
|
|
653
|
if val not in (0,1,False,True):
|
|
654
|
raise ValueError,'new call_pdb value must be boolean'
|
|
654
|
raise ValueError,'new call_pdb value must be boolean'
|
|
655
|
|
|
655
|
|
|
656
|
# store value in instance
|
|
656
|
# store value in instance
|
|
657
|
self._call_pdb = val
|
|
657
|
self._call_pdb = val
|
|
658
|
|
|
658
|
|
|
659
|
# notify the actual exception handlers
|
|
659
|
# notify the actual exception handlers
|
|
660
|
self.InteractiveTB.call_pdb = val
|
|
660
|
self.InteractiveTB.call_pdb = val
|
|
661
|
|
|
661
|
|
|
662
|
call_pdb = property(_get_call_pdb,_set_call_pdb,None,
|
|
662
|
call_pdb = property(_get_call_pdb,_set_call_pdb,None,
|
|
663
|
'Control auto-activation of pdb at exceptions')
|
|
663
|
'Control auto-activation of pdb at exceptions')
|
|
664
|
|
|
664
|
|
|
665
|
def debugger(self,force=False):
|
|
665
|
def debugger(self,force=False):
|
|
666
|
"""Call the pydb/pdb debugger.
|
|
666
|
"""Call the pydb/pdb debugger.
|
|
667
|
|
|
667
|
|
|
668
|
Keywords:
|
|
668
|
Keywords:
|
|
669
|
|
|
669
|
|
|
670
|
- force(False): by default, this routine checks the instance call_pdb
|
|
670
|
- force(False): by default, this routine checks the instance call_pdb
|
|
671
|
flag and does not actually invoke the debugger if the flag is false.
|
|
671
|
flag and does not actually invoke the debugger if the flag is false.
|
|
672
|
The 'force' option forces the debugger to activate even if the flag
|
|
672
|
The 'force' option forces the debugger to activate even if the flag
|
|
673
|
is false.
|
|
673
|
is false.
|
|
674
|
"""
|
|
674
|
"""
|
|
675
|
|
|
675
|
|
|
676
|
if not (force or self.call_pdb):
|
|
676
|
if not (force or self.call_pdb):
|
|
677
|
return
|
|
677
|
return
|
|
678
|
|
|
678
|
|
|
679
|
if not hasattr(sys,'last_traceback'):
|
|
679
|
if not hasattr(sys,'last_traceback'):
|
|
680
|
error('No traceback has been produced, nothing to debug.')
|
|
680
|
error('No traceback has been produced, nothing to debug.')
|
|
681
|
return
|
|
681
|
return
|
|
682
|
|
|
682
|
|
|
683
|
# use pydb if available
|
|
683
|
# use pydb if available
|
|
684
|
if debugger.has_pydb:
|
|
684
|
if debugger.has_pydb:
|
|
685
|
from pydb import pm
|
|
685
|
from pydb import pm
|
|
686
|
else:
|
|
686
|
else:
|
|
687
|
# fallback to our internal debugger
|
|
687
|
# fallback to our internal debugger
|
|
688
|
pm = lambda : self.InteractiveTB.debugger(force=True)
|
|
688
|
pm = lambda : self.InteractiveTB.debugger(force=True)
|
|
689
|
self.history_saving_wrapper(pm)()
|
|
689
|
self.history_saving_wrapper(pm)()
|
|
690
|
|
|
690
|
|
|
691
|
#-------------------------------------------------------------------------
|
|
691
|
#-------------------------------------------------------------------------
|
|
692
|
# Things related to IPython's various namespaces
|
|
692
|
# Things related to IPython's various namespaces
|
|
693
|
#-------------------------------------------------------------------------
|
|
693
|
#-------------------------------------------------------------------------
|
|
694
|
|
|
694
|
|
|
695
|
def init_create_namespaces(self, user_ns=None, user_global_ns=None):
|
|
695
|
def init_create_namespaces(self, user_ns=None, user_global_ns=None):
|
|
696
|
# Create the namespace where the user will operate. user_ns is
|
|
696
|
# Create the namespace where the user will operate. user_ns is
|
|
697
|
# normally the only one used, and it is passed to the exec calls as
|
|
697
|
# normally the only one used, and it is passed to the exec calls as
|
|
698
|
# the locals argument. But we do carry a user_global_ns namespace
|
|
698
|
# the locals argument. But we do carry a user_global_ns namespace
|
|
699
|
# given as the exec 'globals' argument, This is useful in embedding
|
|
699
|
# given as the exec 'globals' argument, This is useful in embedding
|
|
700
|
# situations where the ipython shell opens in a context where the
|
|
700
|
# situations where the ipython shell opens in a context where the
|
|
701
|
# distinction between locals and globals is meaningful. For
|
|
701
|
# distinction between locals and globals is meaningful. For
|
|
702
|
# non-embedded contexts, it is just the same object as the user_ns dict.
|
|
702
|
# non-embedded contexts, it is just the same object as the user_ns dict.
|
|
703
|
|
|
703
|
|
|
704
|
# FIXME. For some strange reason, __builtins__ is showing up at user
|
|
704
|
# FIXME. For some strange reason, __builtins__ is showing up at user
|
|
705
|
# level as a dict instead of a module. This is a manual fix, but I
|
|
705
|
# level as a dict instead of a module. This is a manual fix, but I
|
|
706
|
# should really track down where the problem is coming from. Alex
|
|
706
|
# should really track down where the problem is coming from. Alex
|
|
707
|
# Schmolck reported this problem first.
|
|
707
|
# Schmolck reported this problem first.
|
|
708
|
|
|
708
|
|
|
709
|
# A useful post by Alex Martelli on this topic:
|
|
709
|
# A useful post by Alex Martelli on this topic:
|
|
710
|
# Re: inconsistent value from __builtins__
|
|
710
|
# Re: inconsistent value from __builtins__
|
|
711
|
# Von: Alex Martelli <aleaxit@yahoo.com>
|
|
711
|
# Von: Alex Martelli <aleaxit@yahoo.com>
|
|
712
|
# Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
|
|
712
|
# Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
|
|
713
|
# Gruppen: comp.lang.python
|
|
713
|
# Gruppen: comp.lang.python
|
|
714
|
|
|
714
|
|
|
715
|
# Michael Hohn <hohn@hooknose.lbl.gov> wrote:
|
|
715
|
# Michael Hohn <hohn@hooknose.lbl.gov> wrote:
|
|
716
|
# > >>> print type(builtin_check.get_global_binding('__builtins__'))
|
|
716
|
# > >>> print type(builtin_check.get_global_binding('__builtins__'))
|
|
717
|
# > <type 'dict'>
|
|
717
|
# > <type 'dict'>
|
|
718
|
# > >>> print type(__builtins__)
|
|
718
|
# > >>> print type(__builtins__)
|
|
719
|
# > <type 'module'>
|
|
719
|
# > <type 'module'>
|
|
720
|
# > Is this difference in return value intentional?
|
|
720
|
# > Is this difference in return value intentional?
|
|
721
|
|
|
721
|
|
|
722
|
# Well, it's documented that '__builtins__' can be either a dictionary
|
|
722
|
# Well, it's documented that '__builtins__' can be either a dictionary
|
|
723
|
# or a module, and it's been that way for a long time. Whether it's
|
|
723
|
# or a module, and it's been that way for a long time. Whether it's
|
|
724
|
# intentional (or sensible), I don't know. In any case, the idea is
|
|
724
|
# intentional (or sensible), I don't know. In any case, the idea is
|
|
725
|
# that if you need to access the built-in namespace directly, you
|
|
725
|
# that if you need to access the built-in namespace directly, you
|
|
726
|
# should start with "import __builtin__" (note, no 's') which will
|
|
726
|
# should start with "import __builtin__" (note, no 's') which will
|
|
727
|
# definitely give you a module. Yeah, it's somewhat confusing:-(.
|
|
727
|
# definitely give you a module. Yeah, it's somewhat confusing:-(.
|
|
728
|
|
|
728
|
|
|
729
|
# These routines return properly built dicts as needed by the rest of
|
|
729
|
# These routines return properly built dicts as needed by the rest of
|
|
730
|
# the code, and can also be used by extension writers to generate
|
|
730
|
# the code, and can also be used by extension writers to generate
|
|
731
|
# properly initialized namespaces.
|
|
731
|
# properly initialized namespaces.
|
|
732
|
user_ns, user_global_ns = self.make_user_namespaces(user_ns,
|
|
732
|
user_ns, user_global_ns = self.make_user_namespaces(user_ns,
|
|
733
|
user_global_ns)
|
|
733
|
user_global_ns)
|
|
734
|
|
|
734
|
|
|
735
|
# Assign namespaces
|
|
735
|
# Assign namespaces
|
|
736
|
# This is the namespace where all normal user variables live
|
|
736
|
# This is the namespace where all normal user variables live
|
|
737
|
self.user_ns = user_ns
|
|
737
|
self.user_ns = user_ns
|
|
738
|
self.user_global_ns = user_global_ns
|
|
738
|
self.user_global_ns = user_global_ns
|
|
739
|
|
|
739
|
|
|
740
|
# An auxiliary namespace that checks what parts of the user_ns were
|
|
740
|
# An auxiliary namespace that checks what parts of the user_ns were
|
|
741
|
# loaded at startup, so we can list later only variables defined in
|
|
741
|
# loaded at startup, so we can list later only variables defined in
|
|
742
|
# actual interactive use. Since it is always a subset of user_ns, it
|
|
742
|
# actual interactive use. Since it is always a subset of user_ns, it
|
|
743
|
# doesn't need to be separately tracked in the ns_table.
|
|
743
|
# doesn't need to be separately tracked in the ns_table.
|
|
744
|
self.user_ns_hidden = {}
|
|
744
|
self.user_ns_hidden = {}
|
|
745
|
|
|
745
|
|
|
746
|
# A namespace to keep track of internal data structures to prevent
|
|
746
|
# A namespace to keep track of internal data structures to prevent
|
|
747
|
# them from cluttering user-visible stuff. Will be updated later
|
|
747
|
# them from cluttering user-visible stuff. Will be updated later
|
|
748
|
self.internal_ns = {}
|
|
748
|
self.internal_ns = {}
|
|
749
|
|
|
749
|
|
|
750
|
# Now that FakeModule produces a real module, we've run into a nasty
|
|
750
|
# Now that FakeModule produces a real module, we've run into a nasty
|
|
751
|
# problem: after script execution (via %run), the module where the user
|
|
751
|
# problem: after script execution (via %run), the module where the user
|
|
752
|
# code ran is deleted. Now that this object is a true module (needed
|
|
752
|
# code ran is deleted. Now that this object is a true module (needed
|
|
753
|
# so docetst and other tools work correctly), the Python module
|
|
753
|
# so docetst and other tools work correctly), the Python module
|
|
754
|
# teardown mechanism runs over it, and sets to None every variable
|
|
754
|
# teardown mechanism runs over it, and sets to None every variable
|
|
755
|
# present in that module. Top-level references to objects from the
|
|
755
|
# present in that module. Top-level references to objects from the
|
|
756
|
# script survive, because the user_ns is updated with them. However,
|
|
756
|
# script survive, because the user_ns is updated with them. However,
|
|
757
|
# calling functions defined in the script that use other things from
|
|
757
|
# calling functions defined in the script that use other things from
|
|
758
|
# the script will fail, because the function's closure had references
|
|
758
|
# the script will fail, because the function's closure had references
|
|
759
|
# to the original objects, which are now all None. So we must protect
|
|
759
|
# to the original objects, which are now all None. So we must protect
|
|
760
|
# these modules from deletion by keeping a cache.
|
|
760
|
# these modules from deletion by keeping a cache.
|
|
761
|
#
|
|
761
|
#
|
|
762
|
# To avoid keeping stale modules around (we only need the one from the
|
|
762
|
# To avoid keeping stale modules around (we only need the one from the
|
|
763
|
# last run), we use a dict keyed with the full path to the script, so
|
|
763
|
# last run), we use a dict keyed with the full path to the script, so
|
|
764
|
# only the last version of the module is held in the cache. Note,
|
|
764
|
# only the last version of the module is held in the cache. Note,
|
|
765
|
# however, that we must cache the module *namespace contents* (their
|
|
765
|
# however, that we must cache the module *namespace contents* (their
|
|
766
|
# __dict__). Because if we try to cache the actual modules, old ones
|
|
766
|
# __dict__). Because if we try to cache the actual modules, old ones
|
|
767
|
# (uncached) could be destroyed while still holding references (such as
|
|
767
|
# (uncached) could be destroyed while still holding references (such as
|
|
768
|
# those held by GUI objects that tend to be long-lived)>
|
|
768
|
# those held by GUI objects that tend to be long-lived)>
|
|
769
|
#
|
|
769
|
#
|
|
770
|
# The %reset command will flush this cache. See the cache_main_mod()
|
|
770
|
# The %reset command will flush this cache. See the cache_main_mod()
|
|
771
|
# and clear_main_mod_cache() methods for details on use.
|
|
771
|
# and clear_main_mod_cache() methods for details on use.
|
|
772
|
|
|
772
|
|
|
773
|
# This is the cache used for 'main' namespaces
|
|
773
|
# This is the cache used for 'main' namespaces
|
|
774
|
self._main_ns_cache = {}
|
|
774
|
self._main_ns_cache = {}
|
|
775
|
# And this is the single instance of FakeModule whose __dict__ we keep
|
|
775
|
# And this is the single instance of FakeModule whose __dict__ we keep
|
|
776
|
# copying and clearing for reuse on each %run
|
|
776
|
# copying and clearing for reuse on each %run
|
|
777
|
self._user_main_module = FakeModule()
|
|
777
|
self._user_main_module = FakeModule()
|
|
778
|
|
|
778
|
|
|
779
|
# A table holding all the namespaces IPython deals with, so that
|
|
779
|
# A table holding all the namespaces IPython deals with, so that
|
|
780
|
# introspection facilities can search easily.
|
|
780
|
# introspection facilities can search easily.
|
|
781
|
self.ns_table = {'user':user_ns,
|
|
781
|
self.ns_table = {'user':user_ns,
|
|
782
|
'user_global':user_global_ns,
|
|
782
|
'user_global':user_global_ns,
|
|
783
|
'internal':self.internal_ns,
|
|
783
|
'internal':self.internal_ns,
|
|
784
|
'builtin':__builtin__.__dict__
|
|
784
|
'builtin':__builtin__.__dict__
|
|
785
|
}
|
|
785
|
}
|
|
786
|
|
|
786
|
|
|
787
|
# Similarly, track all namespaces where references can be held and that
|
|
787
|
# Similarly, track all namespaces where references can be held and that
|
|
788
|
# we can safely clear (so it can NOT include builtin). This one can be
|
|
788
|
# we can safely clear (so it can NOT include builtin). This one can be
|
|
789
|
# a simple list.
|
|
789
|
# a simple list.
|
|
790
|
self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
|
|
790
|
self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
|
|
791
|
self.internal_ns, self._main_ns_cache ]
|
|
791
|
self.internal_ns, self._main_ns_cache ]
|
|
792
|
|
|
792
|
|
|
793
|
def make_user_namespaces(self, user_ns=None, user_global_ns=None):
|
|
793
|
def make_user_namespaces(self, user_ns=None, user_global_ns=None):
|
|
794
|
"""Return a valid local and global user interactive namespaces.
|
|
794
|
"""Return a valid local and global user interactive namespaces.
|
|
795
|
|
|
795
|
|
|
796
|
This builds a dict with the minimal information needed to operate as a
|
|
796
|
This builds a dict with the minimal information needed to operate as a
|
|
797
|
valid IPython user namespace, which you can pass to the various
|
|
797
|
valid IPython user namespace, which you can pass to the various
|
|
798
|
embedding classes in ipython. The default implementation returns the
|
|
798
|
embedding classes in ipython. The default implementation returns the
|
|
799
|
same dict for both the locals and the globals to allow functions to
|
|
799
|
same dict for both the locals and the globals to allow functions to
|
|
800
|
refer to variables in the namespace. Customized implementations can
|
|
800
|
refer to variables in the namespace. Customized implementations can
|
|
801
|
return different dicts. The locals dictionary can actually be anything
|
|
801
|
return different dicts. The locals dictionary can actually be anything
|
|
802
|
following the basic mapping protocol of a dict, but the globals dict
|
|
802
|
following the basic mapping protocol of a dict, but the globals dict
|
|
803
|
must be a true dict, not even a subclass. It is recommended that any
|
|
803
|
must be a true dict, not even a subclass. It is recommended that any
|
|
804
|
custom object for the locals namespace synchronize with the globals
|
|
804
|
custom object for the locals namespace synchronize with the globals
|
|
805
|
dict somehow.
|
|
805
|
dict somehow.
|
|
806
|
|
|
806
|
|
|
807
|
Raises TypeError if the provided globals namespace is not a true dict.
|
|
807
|
Raises TypeError if the provided globals namespace is not a true dict.
|
|
808
|
|
|
808
|
|
|
809
|
Parameters
|
|
809
|
Parameters
|
|
810
|
----------
|
|
810
|
----------
|
|
811
|
user_ns : dict-like, optional
|
|
811
|
user_ns : dict-like, optional
|
|
812
|
The current user namespace. The items in this namespace should
|
|
812
|
The current user namespace. The items in this namespace should
|
|
813
|
be included in the output. If None, an appropriate blank
|
|
813
|
be included in the output. If None, an appropriate blank
|
|
814
|
namespace should be created.
|
|
814
|
namespace should be created.
|
|
815
|
user_global_ns : dict, optional
|
|
815
|
user_global_ns : dict, optional
|
|
816
|
The current user global namespace. The items in this namespace
|
|
816
|
The current user global namespace. The items in this namespace
|
|
817
|
should be included in the output. If None, an appropriate
|
|
817
|
should be included in the output. If None, an appropriate
|
|
818
|
blank namespace should be created.
|
|
818
|
blank namespace should be created.
|
|
819
|
|
|
819
|
|
|
820
|
Returns
|
|
820
|
Returns
|
|
821
|
-------
|
|
821
|
-------
|
|
822
|
A pair of dictionary-like object to be used as the local namespace
|
|
822
|
A pair of dictionary-like object to be used as the local namespace
|
|
823
|
of the interpreter and a dict to be used as the global namespace.
|
|
823
|
of the interpreter and a dict to be used as the global namespace.
|
|
824
|
"""
|
|
824
|
"""
|
|
825
|
|
|
825
|
|
|
826
|
|
|
826
|
|
|
827
|
# We must ensure that __builtin__ (without the final 's') is always
|
|
827
|
# We must ensure that __builtin__ (without the final 's') is always
|
|
828
|
# available and pointing to the __builtin__ *module*. For more details:
|
|
828
|
# available and pointing to the __builtin__ *module*. For more details:
|
|
829
|
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
|
|
829
|
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
|
|
830
|
|
|
830
|
|
|
831
|
if user_ns is None:
|
|
831
|
if user_ns is None:
|
|
832
|
# Set __name__ to __main__ to better match the behavior of the
|
|
832
|
# Set __name__ to __main__ to better match the behavior of the
|
|
833
|
# normal interpreter.
|
|
833
|
# normal interpreter.
|
|
834
|
user_ns = {'__name__' :'__main__',
|
|
834
|
user_ns = {'__name__' :'__main__',
|
|
835
|
'__builtin__' : __builtin__,
|
|
835
|
'__builtin__' : __builtin__,
|
|
836
|
'__builtins__' : __builtin__,
|
|
836
|
'__builtins__' : __builtin__,
|
|
837
|
}
|
|
837
|
}
|
|
838
|
else:
|
|
838
|
else:
|
|
839
|
user_ns.setdefault('__name__','__main__')
|
|
839
|
user_ns.setdefault('__name__','__main__')
|
|
840
|
user_ns.setdefault('__builtin__',__builtin__)
|
|
840
|
user_ns.setdefault('__builtin__',__builtin__)
|
|
841
|
user_ns.setdefault('__builtins__',__builtin__)
|
|
841
|
user_ns.setdefault('__builtins__',__builtin__)
|
|
842
|
|
|
842
|
|
|
843
|
if user_global_ns is None:
|
|
843
|
if user_global_ns is None:
|
|
844
|
user_global_ns = user_ns
|
|
844
|
user_global_ns = user_ns
|
|
845
|
if type(user_global_ns) is not dict:
|
|
845
|
if type(user_global_ns) is not dict:
|
|
846
|
raise TypeError("user_global_ns must be a true dict; got %r"
|
|
846
|
raise TypeError("user_global_ns must be a true dict; got %r"
|
|
847
|
% type(user_global_ns))
|
|
847
|
% type(user_global_ns))
|
|
848
|
|
|
848
|
|
|
849
|
return user_ns, user_global_ns
|
|
849
|
return user_ns, user_global_ns
|
|
850
|
|
|
850
|
|
|
851
|
def init_sys_modules(self):
|
|
851
|
def init_sys_modules(self):
|
|
852
|
# We need to insert into sys.modules something that looks like a
|
|
852
|
# We need to insert into sys.modules something that looks like a
|
|
853
|
# module but which accesses the IPython namespace, for shelve and
|
|
853
|
# module but which accesses the IPython namespace, for shelve and
|
|
854
|
# pickle to work interactively. Normally they rely on getting
|
|
854
|
# pickle to work interactively. Normally they rely on getting
|
|
855
|
# everything out of __main__, but for embedding purposes each IPython
|
|
855
|
# everything out of __main__, but for embedding purposes each IPython
|
|
856
|
# instance has its own private namespace, so we can't go shoving
|
|
856
|
# instance has its own private namespace, so we can't go shoving
|
|
857
|
# everything into __main__.
|
|
857
|
# everything into __main__.
|
|
858
|
|
|
858
|
|
|
859
|
# note, however, that we should only do this for non-embedded
|
|
859
|
# note, however, that we should only do this for non-embedded
|
|
860
|
# ipythons, which really mimic the __main__.__dict__ with their own
|
|
860
|
# ipythons, which really mimic the __main__.__dict__ with their own
|
|
861
|
# namespace. Embedded instances, on the other hand, should not do
|
|
861
|
# namespace. Embedded instances, on the other hand, should not do
|
|
862
|
# this because they need to manage the user local/global namespaces
|
|
862
|
# this because they need to manage the user local/global namespaces
|
|
863
|
# only, but they live within a 'normal' __main__ (meaning, they
|
|
863
|
# only, but they live within a 'normal' __main__ (meaning, they
|
|
864
|
# shouldn't overtake the execution environment of the script they're
|
|
864
|
# shouldn't overtake the execution environment of the script they're
|
|
865
|
# embedded in).
|
|
865
|
# embedded in).
|
|
866
|
|
|
866
|
|
|
867
|
# This is overridden in the InteractiveShellEmbed subclass to a no-op.
|
|
867
|
# This is overridden in the InteractiveShellEmbed subclass to a no-op.
|
|
868
|
|
|
868
|
|
|
869
|
try:
|
|
869
|
try:
|
|
870
|
main_name = self.user_ns['__name__']
|
|
870
|
main_name = self.user_ns['__name__']
|
|
871
|
except KeyError:
|
|
871
|
except KeyError:
|
|
872
|
raise KeyError('user_ns dictionary MUST have a "__name__" key')
|
|
872
|
raise KeyError('user_ns dictionary MUST have a "__name__" key')
|
|
873
|
else:
|
|
873
|
else:
|
|
874
|
sys.modules[main_name] = FakeModule(self.user_ns)
|
|
874
|
sys.modules[main_name] = FakeModule(self.user_ns)
|
|
875
|
|
|
875
|
|
|
876
|
def init_user_ns(self):
|
|
876
|
def init_user_ns(self):
|
|
877
|
"""Initialize all user-visible namespaces to their minimum defaults.
|
|
877
|
"""Initialize all user-visible namespaces to their minimum defaults.
|
|
878
|
|
|
878
|
|
|
879
|
Certain history lists are also initialized here, as they effectively
|
|
879
|
Certain history lists are also initialized here, as they effectively
|
|
880
|
act as user namespaces.
|
|
880
|
act as user namespaces.
|
|
881
|
|
|
881
|
|
|
882
|
Notes
|
|
882
|
Notes
|
|
883
|
-----
|
|
883
|
-----
|
|
884
|
All data structures here are only filled in, they are NOT reset by this
|
|
884
|
All data structures here are only filled in, they are NOT reset by this
|
|
885
|
method. If they were not empty before, data will simply be added to
|
|
885
|
method. If they were not empty before, data will simply be added to
|
|
886
|
therm.
|
|
886
|
therm.
|
|
887
|
"""
|
|
887
|
"""
|
|
888
|
# This function works in two parts: first we put a few things in
|
|
888
|
# This function works in two parts: first we put a few things in
|
|
889
|
# user_ns, and we sync that contents into user_ns_hidden so that these
|
|
889
|
# user_ns, and we sync that contents into user_ns_hidden so that these
|
|
890
|
# initial variables aren't shown by %who. After the sync, we add the
|
|
890
|
# initial variables aren't shown by %who. After the sync, we add the
|
|
891
|
# rest of what we *do* want the user to see with %who even on a new
|
|
891
|
# rest of what we *do* want the user to see with %who even on a new
|
|
892
|
# session (probably nothing, so theye really only see their own stuff)
|
|
892
|
# session (probably nothing, so theye really only see their own stuff)
|
|
893
|
|
|
893
|
|
|
894
|
# The user dict must *always* have a __builtin__ reference to the
|
|
894
|
# The user dict must *always* have a __builtin__ reference to the
|
|
895
|
# Python standard __builtin__ namespace, which must be imported.
|
|
895
|
# Python standard __builtin__ namespace, which must be imported.
|
|
896
|
# This is so that certain operations in prompt evaluation can be
|
|
896
|
# This is so that certain operations in prompt evaluation can be
|
|
897
|
# reliably executed with builtins. Note that we can NOT use
|
|
897
|
# reliably executed with builtins. Note that we can NOT use
|
|
898
|
# __builtins__ (note the 's'), because that can either be a dict or a
|
|
898
|
# __builtins__ (note the 's'), because that can either be a dict or a
|
|
899
|
# module, and can even mutate at runtime, depending on the context
|
|
899
|
# module, and can even mutate at runtime, depending on the context
|
|
900
|
# (Python makes no guarantees on it). In contrast, __builtin__ is
|
|
900
|
# (Python makes no guarantees on it). In contrast, __builtin__ is
|
|
901
|
# always a module object, though it must be explicitly imported.
|
|
901
|
# always a module object, though it must be explicitly imported.
|
|
902
|
|
|
902
|
|
|
903
|
# For more details:
|
|
903
|
# For more details:
|
|
904
|
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
|
|
904
|
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
|
|
905
|
ns = dict(__builtin__ = __builtin__)
|
|
905
|
ns = dict(__builtin__ = __builtin__)
|
|
906
|
|
|
906
|
|
|
907
|
# Put 'help' in the user namespace
|
|
907
|
# Put 'help' in the user namespace
|
|
908
|
try:
|
|
908
|
try:
|
|
909
|
from site import _Helper
|
|
909
|
from site import _Helper
|
|
910
|
ns['help'] = _Helper()
|
|
910
|
ns['help'] = _Helper()
|
|
911
|
except ImportError:
|
|
911
|
except ImportError:
|
|
912
|
warn('help() not available - check site.py')
|
|
912
|
warn('help() not available - check site.py')
|
|
913
|
|
|
913
|
|
|
914
|
# make global variables for user access to the histories
|
|
914
|
# make global variables for user access to the histories
|
|
915
|
ns['_ih'] = self.input_hist
|
|
915
|
ns['_ih'] = self.input_hist
|
|
916
|
ns['_oh'] = self.output_hist
|
|
916
|
ns['_oh'] = self.output_hist
|
|
917
|
ns['_dh'] = self.dir_hist
|
|
917
|
ns['_dh'] = self.dir_hist
|
|
918
|
|
|
918
|
|
|
919
|
ns['_sh'] = shadowns
|
|
919
|
ns['_sh'] = shadowns
|
|
920
|
|
|
920
|
|
|
921
|
# user aliases to input and output histories. These shouldn't show up
|
|
921
|
# user aliases to input and output histories. These shouldn't show up
|
|
922
|
# in %who, as they can have very large reprs.
|
|
922
|
# in %who, as they can have very large reprs.
|
|
923
|
ns['In'] = self.input_hist
|
|
923
|
ns['In'] = self.input_hist
|
|
924
|
ns['Out'] = self.output_hist
|
|
924
|
ns['Out'] = self.output_hist
|
|
925
|
|
|
925
|
|
|
926
|
# Store myself as the public api!!!
|
|
926
|
# Store myself as the public api!!!
|
|
927
|
ns['get_ipython'] = self.get_ipython
|
|
927
|
ns['get_ipython'] = self.get_ipython
|
|
928
|
|
|
928
|
|
|
929
|
# Sync what we've added so far to user_ns_hidden so these aren't seen
|
|
929
|
# Sync what we've added so far to user_ns_hidden so these aren't seen
|
|
930
|
# by %who
|
|
930
|
# by %who
|
|
931
|
self.user_ns_hidden.update(ns)
|
|
931
|
self.user_ns_hidden.update(ns)
|
|
932
|
|
|
932
|
|
|
933
|
# Anything put into ns now would show up in %who. Think twice before
|
|
933
|
# Anything put into ns now would show up in %who. Think twice before
|
|
934
|
# putting anything here, as we really want %who to show the user their
|
|
934
|
# putting anything here, as we really want %who to show the user their
|
|
935
|
# stuff, not our variables.
|
|
935
|
# stuff, not our variables.
|
|
936
|
|
|
936
|
|
|
937
|
# Finally, update the real user's namespace
|
|
937
|
# Finally, update the real user's namespace
|
|
938
|
self.user_ns.update(ns)
|
|
938
|
self.user_ns.update(ns)
|
|
939
|
|
|
939
|
|
|
940
|
|
|
940
|
|
|
941
|
def reset(self):
|
|
941
|
def reset(self):
|
|
942
|
"""Clear all internal namespaces.
|
|
942
|
"""Clear all internal namespaces.
|
|
943
|
|
|
943
|
|
|
944
|
Note that this is much more aggressive than %reset, since it clears
|
|
944
|
Note that this is much more aggressive than %reset, since it clears
|
|
945
|
fully all namespaces, as well as all input/output lists.
|
|
945
|
fully all namespaces, as well as all input/output lists.
|
|
946
|
"""
|
|
946
|
"""
|
|
947
|
for ns in self.ns_refs_table:
|
|
947
|
for ns in self.ns_refs_table:
|
|
948
|
ns.clear()
|
|
948
|
ns.clear()
|
|
949
|
|
|
949
|
|
|
950
|
self.alias_manager.clear_aliases()
|
|
950
|
self.alias_manager.clear_aliases()
|
|
951
|
|
|
951
|
|
|
952
|
# Clear input and output histories
|
|
952
|
# Clear input and output histories
|
|
953
|
self.input_hist[:] = []
|
|
953
|
self.input_hist[:] = []
|
|
954
|
self.input_hist_raw[:] = []
|
|
954
|
self.input_hist_raw[:] = []
|
|
955
|
self.output_hist.clear()
|
|
955
|
self.output_hist.clear()
|
|
956
|
|
|
956
|
|
|
957
|
# Restore the user namespaces to minimal usability
|
|
957
|
# Restore the user namespaces to minimal usability
|
|
958
|
self.init_user_ns()
|
|
958
|
self.init_user_ns()
|
|
959
|
|
|
959
|
|
|
960
|
# Restore the default and user aliases
|
|
960
|
# Restore the default and user aliases
|
|
961
|
self.alias_manager.init_aliases()
|
|
961
|
self.alias_manager.init_aliases()
|
|
962
|
|
|
962
|
|
|
963
|
def reset_selective(self, regex=None):
|
|
963
|
def reset_selective(self, regex=None):
|
|
964
|
"""Clear selective variables from internal namespaces based on a
|
|
964
|
"""Clear selective variables from internal namespaces based on a
|
|
965
|
specified regular expression.
|
|
965
|
specified regular expression.
|
|
966
|
|
|
966
|
|
|
967
|
Parameters
|
|
967
|
Parameters
|
|
968
|
----------
|
|
968
|
----------
|
|
969
|
regex : string or compiled pattern, optional
|
|
969
|
regex : string or compiled pattern, optional
|
|
970
|
A regular expression pattern that will be used in searching
|
|
970
|
A regular expression pattern that will be used in searching
|
|
971
|
variable names in the users namespaces.
|
|
971
|
variable names in the users namespaces.
|
|
972
|
"""
|
|
972
|
"""
|
|
973
|
if regex is not None:
|
|
973
|
if regex is not None:
|
|
974
|
try:
|
|
974
|
try:
|
|
975
|
m = re.compile(regex)
|
|
975
|
m = re.compile(regex)
|
|
976
|
except TypeError:
|
|
976
|
except TypeError:
|
|
977
|
raise TypeError('regex must be a string or compiled pattern')
|
|
977
|
raise TypeError('regex must be a string or compiled pattern')
|
|
978
|
# Search for keys in each namespace that match the given regex
|
|
978
|
# Search for keys in each namespace that match the given regex
|
|
979
|
# If a match is found, delete the key/value pair.
|
|
979
|
# If a match is found, delete the key/value pair.
|
|
980
|
for ns in self.ns_refs_table:
|
|
980
|
for ns in self.ns_refs_table:
|
|
981
|
for var in ns:
|
|
981
|
for var in ns:
|
|
982
|
if m.search(var):
|
|
982
|
if m.search(var):
|
|
983
|
del ns[var]
|
|
983
|
del ns[var]
|
|
984
|
|
|
984
|
|
|
985
|
def push(self, variables, interactive=True):
|
|
985
|
def push(self, variables, interactive=True):
|
|
986
|
"""Inject a group of variables into the IPython user namespace.
|
|
986
|
"""Inject a group of variables into the IPython user namespace.
|
|
987
|
|
|
987
|
|
|
988
|
Parameters
|
|
988
|
Parameters
|
|
989
|
----------
|
|
989
|
----------
|
|
990
|
variables : dict, str or list/tuple of str
|
|
990
|
variables : dict, str or list/tuple of str
|
|
991
|
The variables to inject into the user's namespace. If a dict, a
|
|
991
|
The variables to inject into the user's namespace. If a dict, a
|
|
992
|
simple update is done. If a str, the string is assumed to have
|
|
992
|
simple update is done. If a str, the string is assumed to have
|
|
993
|
variable names separated by spaces. A list/tuple of str can also
|
|
993
|
variable names separated by spaces. A list/tuple of str can also
|
|
994
|
be used to give the variable names. If just the variable names are
|
|
994
|
be used to give the variable names. If just the variable names are
|
|
995
|
give (list/tuple/str) then the variable values looked up in the
|
|
995
|
give (list/tuple/str) then the variable values looked up in the
|
|
996
|
callers frame.
|
|
996
|
callers frame.
|
|
997
|
interactive : bool
|
|
997
|
interactive : bool
|
|
998
|
If True (default), the variables will be listed with the ``who``
|
|
998
|
If True (default), the variables will be listed with the ``who``
|
|
999
|
magic.
|
|
999
|
magic.
|
|
1000
|
"""
|
|
1000
|
"""
|
|
1001
|
vdict = None
|
|
1001
|
vdict = None
|
|
1002
|
|
|
1002
|
|
|
1003
|
# We need a dict of name/value pairs to do namespace updates.
|
|
1003
|
# We need a dict of name/value pairs to do namespace updates.
|
|
1004
|
if isinstance(variables, dict):
|
|
1004
|
if isinstance(variables, dict):
|
|
1005
|
vdict = variables
|
|
1005
|
vdict = variables
|
|
1006
|
elif isinstance(variables, (basestring, list, tuple)):
|
|
1006
|
elif isinstance(variables, (basestring, list, tuple)):
|
|
1007
|
if isinstance(variables, basestring):
|
|
1007
|
if isinstance(variables, basestring):
|
|
1008
|
vlist = variables.split()
|
|
1008
|
vlist = variables.split()
|
|
1009
|
else:
|
|
1009
|
else:
|
|
1010
|
vlist = variables
|
|
1010
|
vlist = variables
|
|
1011
|
vdict = {}
|
|
1011
|
vdict = {}
|
|
1012
|
cf = sys._getframe(1)
|
|
1012
|
cf = sys._getframe(1)
|
|
1013
|
for name in vlist:
|
|
1013
|
for name in vlist:
|
|
1014
|
try:
|
|
1014
|
try:
|
|
1015
|
vdict[name] = eval(name, cf.f_globals, cf.f_locals)
|
|
1015
|
vdict[name] = eval(name, cf.f_globals, cf.f_locals)
|
|
1016
|
except:
|
|
1016
|
except:
|
|
1017
|
print ('Could not get variable %s from %s' %
|
|
1017
|
print ('Could not get variable %s from %s' %
|
|
1018
|
(name,cf.f_code.co_name))
|
|
1018
|
(name,cf.f_code.co_name))
|
|
1019
|
else:
|
|
1019
|
else:
|
|
1020
|
raise ValueError('variables must be a dict/str/list/tuple')
|
|
1020
|
raise ValueError('variables must be a dict/str/list/tuple')
|
|
1021
|
|
|
1021
|
|
|
1022
|
# Propagate variables to user namespace
|
|
1022
|
# Propagate variables to user namespace
|
|
1023
|
self.user_ns.update(vdict)
|
|
1023
|
self.user_ns.update(vdict)
|
|
1024
|
|
|
1024
|
|
|
1025
|
# And configure interactive visibility
|
|
1025
|
# And configure interactive visibility
|
|
1026
|
config_ns = self.user_ns_hidden
|
|
1026
|
config_ns = self.user_ns_hidden
|
|
1027
|
if interactive:
|
|
1027
|
if interactive:
|
|
1028
|
for name, val in vdict.iteritems():
|
|
1028
|
for name, val in vdict.iteritems():
|
|
1029
|
config_ns.pop(name, None)
|
|
1029
|
config_ns.pop(name, None)
|
|
1030
|
else:
|
|
1030
|
else:
|
|
1031
|
for name,val in vdict.iteritems():
|
|
1031
|
for name,val in vdict.iteritems():
|
|
1032
|
config_ns[name] = val
|
|
1032
|
config_ns[name] = val
|
|
1033
|
|
|
1033
|
|
|
1034
|
#-------------------------------------------------------------------------
|
|
1034
|
#-------------------------------------------------------------------------
|
|
1035
|
# Things related to object introspection
|
|
1035
|
# Things related to object introspection
|
|
1036
|
#-------------------------------------------------------------------------
|
|
1036
|
#-------------------------------------------------------------------------
|
|
1037
|
def _ofind(self, oname, namespaces=None):
|
|
1037
|
def _ofind(self, oname, namespaces=None):
|
|
1038
|
"""Find an object in the available namespaces.
|
|
1038
|
"""Find an object in the available namespaces.
|
|
1039
|
|
|
1039
|
|
|
1040
|
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
|
|
1040
|
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
|
|
1041
|
|
|
1041
|
|
|
1042
|
Has special code to detect magic functions.
|
|
1042
|
Has special code to detect magic functions.
|
|
1043
|
"""
|
|
1043
|
"""
|
|
1044
|
#oname = oname.strip()
|
|
1044
|
#oname = oname.strip()
|
|
1045
|
#print '1- oname: <%r>' % oname # dbg
|
|
1045
|
#print '1- oname: <%r>' % oname # dbg
|
|
1046
|
try:
|
|
1046
|
try:
|
|
1047
|
oname = oname.strip().encode('ascii')
|
|
1047
|
oname = oname.strip().encode('ascii')
|
|
1048
|
#print '2- oname: <%r>' % oname # dbg
|
|
1048
|
#print '2- oname: <%r>' % oname # dbg
|
|
1049
|
except UnicodeEncodeError:
|
|
1049
|
except UnicodeEncodeError:
|
|
1050
|
print 'Python identifiers can only contain ascii characters.'
|
|
1050
|
print 'Python identifiers can only contain ascii characters.'
|
|
1051
|
return dict(found=False)
|
|
1051
|
return dict(found=False)
|
|
1052
|
|
|
1052
|
|
|
1053
|
alias_ns = None
|
|
1053
|
alias_ns = None
|
|
1054
|
if namespaces is None:
|
|
1054
|
if namespaces is None:
|
|
1055
|
# Namespaces to search in:
|
|
1055
|
# Namespaces to search in:
|
|
1056
|
# Put them in a list. The order is important so that we
|
|
1056
|
# Put them in a list. The order is important so that we
|
|
1057
|
# find things in the same order that Python finds them.
|
|
1057
|
# find things in the same order that Python finds them.
|
|
1058
|
namespaces = [ ('Interactive', self.user_ns),
|
|
1058
|
namespaces = [ ('Interactive', self.user_ns),
|
|
1059
|
('IPython internal', self.internal_ns),
|
|
1059
|
('IPython internal', self.internal_ns),
|
|
1060
|
('Python builtin', __builtin__.__dict__),
|
|
1060
|
('Python builtin', __builtin__.__dict__),
|
|
1061
|
('Alias', self.alias_manager.alias_table),
|
|
1061
|
('Alias', self.alias_manager.alias_table),
|
|
1062
|
]
|
|
1062
|
]
|
|
1063
|
alias_ns = self.alias_manager.alias_table
|
|
1063
|
alias_ns = self.alias_manager.alias_table
|
|
1064
|
|
|
1064
|
|
|
1065
|
# initialize results to 'null'
|
|
1065
|
# initialize results to 'null'
|
|
1066
|
found = False; obj = None; ospace = None; ds = None;
|
|
1066
|
found = False; obj = None; ospace = None; ds = None;
|
|
1067
|
ismagic = False; isalias = False; parent = None
|
|
1067
|
ismagic = False; isalias = False; parent = None
|
|
1068
|
|
|
1068
|
|
|
1069
|
# We need to special-case 'print', which as of python2.6 registers as a
|
|
1069
|
# We need to special-case 'print', which as of python2.6 registers as a
|
|
1070
|
# function but should only be treated as one if print_function was
|
|
1070
|
# function but should only be treated as one if print_function was
|
|
1071
|
# loaded with a future import. In this case, just bail.
|
|
1071
|
# loaded with a future import. In this case, just bail.
|
|
1072
|
if (oname == 'print' and not (self.compile.compiler.flags &
|
|
1072
|
if (oname == 'print' and not (self.compile.compiler.flags &
|
|
1073
|
__future__.CO_FUTURE_PRINT_FUNCTION)):
|
|
1073
|
__future__.CO_FUTURE_PRINT_FUNCTION)):
|
|
1074
|
return {'found':found, 'obj':obj, 'namespace':ospace,
|
|
1074
|
return {'found':found, 'obj':obj, 'namespace':ospace,
|
|
1075
|
'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
|
|
1075
|
'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
|
|
1076
|
|
|
1076
|
|
|
1077
|
# Look for the given name by splitting it in parts. If the head is
|
|
1077
|
# Look for the given name by splitting it in parts. If the head is
|
|
1078
|
# found, then we look for all the remaining parts as members, and only
|
|
1078
|
# found, then we look for all the remaining parts as members, and only
|
|
1079
|
# declare success if we can find them all.
|
|
1079
|
# declare success if we can find them all.
|
|
1080
|
oname_parts = oname.split('.')
|
|
1080
|
oname_parts = oname.split('.')
|
|
1081
|
oname_head, oname_rest = oname_parts[0],oname_parts[1:]
|
|
1081
|
oname_head, oname_rest = oname_parts[0],oname_parts[1:]
|
|
1082
|
for nsname,ns in namespaces:
|
|
1082
|
for nsname,ns in namespaces:
|
|
1083
|
try:
|
|
1083
|
try:
|
|
1084
|
obj = ns[oname_head]
|
|
1084
|
obj = ns[oname_head]
|
|
1085
|
except KeyError:
|
|
1085
|
except KeyError:
|
|
1086
|
continue
|
|
1086
|
continue
|
|
1087
|
else:
|
|
1087
|
else:
|
|
1088
|
#print 'oname_rest:', oname_rest # dbg
|
|
1088
|
#print 'oname_rest:', oname_rest # dbg
|
|
1089
|
for part in oname_rest:
|
|
1089
|
for part in oname_rest:
|
|
1090
|
try:
|
|
1090
|
try:
|
|
1091
|
parent = obj
|
|
1091
|
parent = obj
|
|
1092
|
obj = getattr(obj,part)
|
|
1092
|
obj = getattr(obj,part)
|
|
1093
|
except:
|
|
1093
|
except:
|
|
1094
|
# Blanket except b/c some badly implemented objects
|
|
1094
|
# Blanket except b/c some badly implemented objects
|
|
1095
|
# allow __getattr__ to raise exceptions other than
|
|
1095
|
# allow __getattr__ to raise exceptions other than
|
|
1096
|
# AttributeError, which then crashes IPython.
|
|
1096
|
# AttributeError, which then crashes IPython.
|
|
1097
|
break
|
|
1097
|
break
|
|
1098
|
else:
|
|
1098
|
else:
|
|
1099
|
# If we finish the for loop (no break), we got all members
|
|
1099
|
# If we finish the for loop (no break), we got all members
|
|
1100
|
found = True
|
|
1100
|
found = True
|
|
1101
|
ospace = nsname
|
|
1101
|
ospace = nsname
|
|
1102
|
if ns == alias_ns:
|
|
1102
|
if ns == alias_ns:
|
|
1103
|
isalias = True
|
|
1103
|
isalias = True
|
|
1104
|
break # namespace loop
|
|
1104
|
break # namespace loop
|
|
1105
|
|
|
1105
|
|
|
1106
|
# Try to see if it's magic
|
|
1106
|
# Try to see if it's magic
|
|
1107
|
if not found:
|
|
1107
|
if not found:
|
|
1108
|
if oname.startswith(ESC_MAGIC):
|
|
1108
|
if oname.startswith(ESC_MAGIC):
|
|
1109
|
oname = oname[1:]
|
|
1109
|
oname = oname[1:]
|
|
1110
|
obj = getattr(self,'magic_'+oname,None)
|
|
1110
|
obj = getattr(self,'magic_'+oname,None)
|
|
1111
|
if obj is not None:
|
|
1111
|
if obj is not None:
|
|
1112
|
found = True
|
|
1112
|
found = True
|
|
1113
|
ospace = 'IPython internal'
|
|
1113
|
ospace = 'IPython internal'
|
|
1114
|
ismagic = True
|
|
1114
|
ismagic = True
|
|
1115
|
|
|
1115
|
|
|
1116
|
# Last try: special-case some literals like '', [], {}, etc:
|
|
1116
|
# Last try: special-case some literals like '', [], {}, etc:
|
|
1117
|
if not found and oname_head in ["''",'""','[]','{}','()']:
|
|
1117
|
if not found and oname_head in ["''",'""','[]','{}','()']:
|
|
1118
|
obj = eval(oname_head)
|
|
1118
|
obj = eval(oname_head)
|
|
1119
|
found = True
|
|
1119
|
found = True
|
|
1120
|
ospace = 'Interactive'
|
|
1120
|
ospace = 'Interactive'
|
|
1121
|
|
|
1121
|
|
|
1122
|
return {'found':found, 'obj':obj, 'namespace':ospace,
|
|
1122
|
return {'found':found, 'obj':obj, 'namespace':ospace,
|
|
1123
|
'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
|
|
1123
|
'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
|
|
1124
|
|
|
1124
|
|
|
1125
|
def _ofind_property(self, oname, info):
|
|
1125
|
def _ofind_property(self, oname, info):
|
|
1126
|
"""Second part of object finding, to look for property details."""
|
|
1126
|
"""Second part of object finding, to look for property details."""
|
|
1127
|
if info.found:
|
|
1127
|
if info.found:
|
|
1128
|
# Get the docstring of the class property if it exists.
|
|
1128
|
# Get the docstring of the class property if it exists.
|
|
1129
|
path = oname.split('.')
|
|
1129
|
path = oname.split('.')
|
|
1130
|
root = '.'.join(path[:-1])
|
|
1130
|
root = '.'.join(path[:-1])
|
|
1131
|
if info.parent is not None:
|
|
1131
|
if info.parent is not None:
|
|
1132
|
try:
|
|
1132
|
try:
|
|
1133
|
target = getattr(info.parent, '__class__')
|
|
1133
|
target = getattr(info.parent, '__class__')
|
|
1134
|
# The object belongs to a class instance.
|
|
1134
|
# The object belongs to a class instance.
|
|
1135
|
try:
|
|
1135
|
try:
|
|
1136
|
target = getattr(target, path[-1])
|
|
1136
|
target = getattr(target, path[-1])
|
|
1137
|
# The class defines the object.
|
|
1137
|
# The class defines the object.
|
|
1138
|
if isinstance(target, property):
|
|
1138
|
if isinstance(target, property):
|
|
1139
|
oname = root + '.__class__.' + path[-1]
|
|
1139
|
oname = root + '.__class__.' + path[-1]
|
|
1140
|
info = Struct(self._ofind(oname))
|
|
1140
|
info = Struct(self._ofind(oname))
|
|
1141
|
except AttributeError: pass
|
|
1141
|
except AttributeError: pass
|
|
1142
|
except AttributeError: pass
|
|
1142
|
except AttributeError: pass
|
|
1143
|
|
|
1143
|
|
|
1144
|
# We return either the new info or the unmodified input if the object
|
|
1144
|
# We return either the new info or the unmodified input if the object
|
|
1145
|
# hadn't been found
|
|
1145
|
# hadn't been found
|
|
1146
|
return info
|
|
1146
|
return info
|
|
1147
|
|
|
1147
|
|
|
1148
|
def _object_find(self, oname, namespaces=None):
|
|
1148
|
def _object_find(self, oname, namespaces=None):
|
|
1149
|
"""Find an object and return a struct with info about it."""
|
|
1149
|
"""Find an object and return a struct with info about it."""
|
|
1150
|
inf = Struct(self._ofind(oname, namespaces))
|
|
1150
|
inf = Struct(self._ofind(oname, namespaces))
|
|
1151
|
return Struct(self._ofind_property(oname, inf))
|
|
1151
|
return Struct(self._ofind_property(oname, inf))
|
|
1152
|
|
|
1152
|
|
|
1153
|
def _inspect(self, meth, oname, namespaces=None, **kw):
|
|
1153
|
def _inspect(self, meth, oname, namespaces=None, **kw):
|
|
1154
|
"""Generic interface to the inspector system.
|
|
1154
|
"""Generic interface to the inspector system.
|
|
1155
|
|
|
1155
|
|
|
1156
|
This function is meant to be called by pdef, pdoc & friends."""
|
|
1156
|
This function is meant to be called by pdef, pdoc & friends."""
|
|
1157
|
info = self._object_find(oname)
|
|
1157
|
info = self._object_find(oname)
|
|
1158
|
if info.found:
|
|
1158
|
if info.found:
|
|
1159
|
pmethod = getattr(self.inspector, meth)
|
|
1159
|
pmethod = getattr(self.inspector, meth)
|
|
1160
|
formatter = format_screen if info.ismagic else None
|
|
1160
|
formatter = format_screen if info.ismagic else None
|
|
1161
|
if meth == 'pdoc':
|
|
1161
|
if meth == 'pdoc':
|
|
1162
|
pmethod(info.obj, oname, formatter)
|
|
1162
|
pmethod(info.obj, oname, formatter)
|
|
1163
|
elif meth == 'pinfo':
|
|
1163
|
elif meth == 'pinfo':
|
|
1164
|
pmethod(info.obj, oname, formatter, info, **kw)
|
|
1164
|
pmethod(info.obj, oname, formatter, info, **kw)
|
|
1165
|
else:
|
|
1165
|
else:
|
|
1166
|
pmethod(info.obj, oname)
|
|
1166
|
pmethod(info.obj, oname)
|
|
1167
|
else:
|
|
1167
|
else:
|
|
1168
|
print 'Object `%s` not found.' % oname
|
|
1168
|
print 'Object `%s` not found.' % oname
|
|
1169
|
return 'not found' # so callers can take other action
|
|
1169
|
return 'not found' # so callers can take other action
|
|
1170
|
|
|
1170
|
|
|
1171
|
def object_inspect(self, oname):
|
|
1171
|
def object_inspect(self, oname):
|
|
1172
|
info = self._object_find(oname)
|
|
1172
|
info = self._object_find(oname)
|
|
1173
|
if info.found:
|
|
1173
|
if info.found:
|
|
1174
|
return self.inspector.info(info.obj, info=info)
|
|
1174
|
return self.inspector.info(info.obj, info=info)
|
|
1175
|
else:
|
|
1175
|
else:
|
|
1176
|
return oinspect.mk_object_info({'found' : False})
|
|
1176
|
return oinspect.mk_object_info({'found' : False})
|
|
1177
|
|
|
1177
|
|
|
1178
|
#-------------------------------------------------------------------------
|
|
1178
|
#-------------------------------------------------------------------------
|
|
1179
|
# Things related to history management
|
|
1179
|
# Things related to history management
|
|
1180
|
#-------------------------------------------------------------------------
|
|
1180
|
#-------------------------------------------------------------------------
|
|
1181
|
|
|
1181
|
|
|
1182
|
def init_history(self):
|
|
1182
|
def init_history(self):
|
|
1183
|
# List of input with multi-line handling.
|
|
1183
|
# List of input with multi-line handling.
|
|
1184
|
self.input_hist = InputList()
|
|
1184
|
self.input_hist = InputList()
|
|
1185
|
# This one will hold the 'raw' input history, without any
|
|
1185
|
# This one will hold the 'raw' input history, without any
|
|
1186
|
# pre-processing. This will allow users to retrieve the input just as
|
|
1186
|
# pre-processing. This will allow users to retrieve the input just as
|
|
1187
|
# it was exactly typed in by the user, with %hist -r.
|
|
1187
|
# it was exactly typed in by the user, with %hist -r.
|
|
1188
|
self.input_hist_raw = InputList()
|
|
1188
|
self.input_hist_raw = InputList()
|
|
1189
|
|
|
1189
|
|
|
1190
|
# list of visited directories
|
|
1190
|
# list of visited directories
|
|
1191
|
try:
|
|
1191
|
try:
|
|
1192
|
self.dir_hist = [os.getcwd()]
|
|
1192
|
self.dir_hist = [os.getcwd()]
|
|
1193
|
except OSError:
|
|
1193
|
except OSError:
|
|
1194
|
self.dir_hist = []
|
|
1194
|
self.dir_hist = []
|
|
1195
|
|
|
1195
|
|
|
1196
|
# dict of output history
|
|
1196
|
# dict of output history
|
|
1197
|
self.output_hist = {}
|
|
1197
|
self.output_hist = {}
|
|
1198
|
|
|
1198
|
|
|
1199
|
# Now the history file
|
|
1199
|
# Now the history file
|
|
1200
|
if self.profile:
|
|
1200
|
if self.profile:
|
|
1201
|
histfname = 'history-%s' % self.profile
|
|
1201
|
histfname = 'history-%s' % self.profile
|
|
1202
|
else:
|
|
1202
|
else:
|
|
1203
|
histfname = 'history'
|
|
1203
|
histfname = 'history'
|
|
1204
|
self.histfile = os.path.join(self.ipython_dir, histfname)
|
|
1204
|
self.histfile = os.path.join(self.ipython_dir, histfname)
|
|
1205
|
|
|
1205
|
|
|
1206
|
# Fill the history zero entry, user counter starts at 1
|
|
1206
|
# Fill the history zero entry, user counter starts at 1
|
|
1207
|
self.input_hist.append('\n')
|
|
1207
|
self.input_hist.append('\n')
|
|
1208
|
self.input_hist_raw.append('\n')
|
|
1208
|
self.input_hist_raw.append('\n')
|
|
1209
|
|
|
1209
|
|
|
1210
|
def init_shadow_hist(self):
|
|
1210
|
def init_shadow_hist(self):
|
|
1211
|
try:
|
|
1211
|
try:
|
|
1212
|
self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
|
|
1212
|
self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
|
|
1213
|
except exceptions.UnicodeDecodeError:
|
|
1213
|
except exceptions.UnicodeDecodeError:
|
|
1214
|
print "Your ipython_dir can't be decoded to unicode!"
|
|
1214
|
print "Your ipython_dir can't be decoded to unicode!"
|
|
1215
|
print "Please set HOME environment variable to something that"
|
|
1215
|
print "Please set HOME environment variable to something that"
|
|
1216
|
print r"only has ASCII characters, e.g. c:\home"
|
|
1216
|
print r"only has ASCII characters, e.g. c:\home"
|
|
1217
|
print "Now it is", self.ipython_dir
|
|
1217
|
print "Now it is", self.ipython_dir
|
|
1218
|
sys.exit()
|
|
1218
|
sys.exit()
|
|
1219
|
self.shadowhist = ipcorehist.ShadowHist(self.db)
|
|
1219
|
self.shadowhist = ipcorehist.ShadowHist(self.db)
|
|
1220
|
|
|
1220
|
|
|
1221
|
def savehist(self):
|
|
1221
|
def savehist(self):
|
|
1222
|
"""Save input history to a file (via readline library)."""
|
|
1222
|
"""Save input history to a file (via readline library)."""
|
|
1223
|
|
|
1223
|
|
|
1224
|
try:
|
|
1224
|
try:
|
|
1225
|
self.readline.write_history_file(self.histfile)
|
|
1225
|
self.readline.write_history_file(self.histfile)
|
|
1226
|
except:
|
|
1226
|
except:
|
|
1227
|
print 'Unable to save IPython command history to file: ' + \
|
|
1227
|
print 'Unable to save IPython command history to file: ' + \
|
|
1228
|
`self.histfile`
|
|
1228
|
`self.histfile`
|
|
1229
|
|
|
1229
|
|
|
1230
|
def reloadhist(self):
|
|
1230
|
def reloadhist(self):
|
|
1231
|
"""Reload the input history from disk file."""
|
|
1231
|
"""Reload the input history from disk file."""
|
|
1232
|
|
|
1232
|
|
|
1233
|
try:
|
|
1233
|
try:
|
|
1234
|
self.readline.clear_history()
|
|
1234
|
self.readline.clear_history()
|
|
1235
|
self.readline.read_history_file(self.shell.histfile)
|
|
1235
|
self.readline.read_history_file(self.shell.histfile)
|
|
1236
|
except AttributeError:
|
|
1236
|
except AttributeError:
|
|
1237
|
pass
|
|
1237
|
pass
|
|
1238
|
|
|
1238
|
|
|
1239
|
def history_saving_wrapper(self, func):
|
|
1239
|
def history_saving_wrapper(self, func):
|
|
1240
|
""" Wrap func for readline history saving
|
|
1240
|
""" Wrap func for readline history saving
|
|
1241
|
|
|
1241
|
|
|
1242
|
Convert func into callable that saves & restores
|
|
1242
|
Convert func into callable that saves & restores
|
|
1243
|
history around the call """
|
|
1243
|
history around the call """
|
|
1244
|
|
|
1244
|
|
|
1245
|
if self.has_readline:
|
|
1245
|
if self.has_readline:
|
|
1246
|
from IPython.utils import rlineimpl as readline
|
|
1246
|
from IPython.utils import rlineimpl as readline
|
|
1247
|
else:
|
|
1247
|
else:
|
|
1248
|
return func
|
|
1248
|
return func
|
|
1249
|
|
|
1249
|
|
|
1250
|
def wrapper():
|
|
1250
|
def wrapper():
|
|
1251
|
self.savehist()
|
|
1251
|
self.savehist()
|
|
1252
|
try:
|
|
1252
|
try:
|
|
1253
|
func()
|
|
1253
|
func()
|
|
1254
|
finally:
|
|
1254
|
finally:
|
|
1255
|
readline.read_history_file(self.histfile)
|
|
1255
|
readline.read_history_file(self.histfile)
|
|
1256
|
return wrapper
|
|
1256
|
return wrapper
|
|
1257
|
|
|
1257
|
|
|
1258
|
def get_history(self, index=None, raw=False, output=True):
|
|
1258
|
def get_history(self, index=None, raw=False, output=True):
|
|
1259
|
"""Get the history list.
|
|
1259
|
"""Get the history list.
|
|
1260
|
|
|
1260
|
|
|
1261
|
Get the input and output history.
|
|
1261
|
Get the input and output history.
|
|
1262
|
|
|
1262
|
|
|
1263
|
Parameters
|
|
1263
|
Parameters
|
|
1264
|
----------
|
|
1264
|
----------
|
|
1265
|
index : n or (n1, n2) or None
|
|
1265
|
index : n or (n1, n2) or None
|
|
1266
|
If n, then the last entries. If a tuple, then all in
|
|
1266
|
If n, then the last entries. If a tuple, then all in
|
|
1267
|
range(n1, n2). If None, then all entries. Raises IndexError if
|
|
1267
|
range(n1, n2). If None, then all entries. Raises IndexError if
|
|
1268
|
the format of index is incorrect.
|
|
1268
|
the format of index is incorrect.
|
|
1269
|
raw : bool
|
|
1269
|
raw : bool
|
|
1270
|
If True, return the raw input.
|
|
1270
|
If True, return the raw input.
|
|
1271
|
output : bool
|
|
1271
|
output : bool
|
|
1272
|
If True, then return the output as well.
|
|
1272
|
If True, then return the output as well.
|
|
1273
|
|
|
1273
|
|
|
1274
|
Returns
|
|
1274
|
Returns
|
|
1275
|
-------
|
|
1275
|
-------
|
|
1276
|
If output is True, then return a dict of tuples, keyed by the prompt
|
|
1276
|
If output is True, then return a dict of tuples, keyed by the prompt
|
|
1277
|
numbers and with values of (input, output). If output is False, then
|
|
1277
|
numbers and with values of (input, output). If output is False, then
|
|
1278
|
a dict, keyed by the prompt number with the values of input. Raises
|
|
1278
|
a dict, keyed by the prompt number with the values of input. Raises
|
|
1279
|
IndexError if no history is found.
|
|
1279
|
IndexError if no history is found.
|
|
1280
|
"""
|
|
1280
|
"""
|
|
1281
|
if raw:
|
|
1281
|
if raw:
|
|
1282
|
input_hist = self.input_hist_raw
|
|
1282
|
input_hist = self.input_hist_raw
|
|
1283
|
else:
|
|
1283
|
else:
|
|
1284
|
input_hist = self.input_hist
|
|
1284
|
input_hist = self.input_hist
|
|
1285
|
if output:
|
|
1285
|
if output:
|
|
1286
|
output_hist = self.user_ns['Out']
|
|
1286
|
output_hist = self.user_ns['Out']
|
|
1287
|
n = len(input_hist)
|
|
1287
|
n = len(input_hist)
|
|
1288
|
if index is None:
|
|
1288
|
if index is None:
|
|
1289
|
start=0; stop=n
|
|
1289
|
start=0; stop=n
|
|
1290
|
elif isinstance(index, int):
|
|
1290
|
elif isinstance(index, int):
|
|
1291
|
start=n-index; stop=n
|
|
1291
|
start=n-index; stop=n
|
|
1292
|
elif isinstance(index, tuple) and len(index) == 2:
|
|
1292
|
elif isinstance(index, tuple) and len(index) == 2:
|
|
1293
|
start=index[0]; stop=index[1]
|
|
1293
|
start=index[0]; stop=index[1]
|
|
1294
|
else:
|
|
1294
|
else:
|
|
1295
|
raise IndexError('Not a valid index for the input history: %r'
|
|
1295
|
raise IndexError('Not a valid index for the input history: %r'
|
|
1296
|
% index)
|
|
1296
|
% index)
|
|
1297
|
hist = {}
|
|
1297
|
hist = {}
|
|
1298
|
for i in range(start, stop):
|
|
1298
|
for i in range(start, stop):
|
|
1299
|
if output:
|
|
1299
|
if output:
|
|
1300
|
hist[i] = (input_hist[i], output_hist.get(i))
|
|
1300
|
hist[i] = (input_hist[i], output_hist.get(i))
|
|
1301
|
else:
|
|
1301
|
else:
|
|
1302
|
hist[i] = input_hist[i]
|
|
1302
|
hist[i] = input_hist[i]
|
|
1303
|
if len(hist)==0:
|
|
1303
|
if len(hist)==0:
|
|
1304
|
raise IndexError('No history for range of indices: %r' % index)
|
|
1304
|
raise IndexError('No history for range of indices: %r' % index)
|
|
1305
|
return hist
|
|
1305
|
return hist
|
|
1306
|
|
|
1306
|
|
|
1307
|
#-------------------------------------------------------------------------
|
|
1307
|
#-------------------------------------------------------------------------
|
|
1308
|
# Things related to exception handling and tracebacks (not debugging)
|
|
1308
|
# Things related to exception handling and tracebacks (not debugging)
|
|
1309
|
#-------------------------------------------------------------------------
|
|
1309
|
#-------------------------------------------------------------------------
|
|
1310
|
|
|
1310
|
|
|
1311
|
def init_traceback_handlers(self, custom_exceptions):
|
|
1311
|
def init_traceback_handlers(self, custom_exceptions):
|
|
1312
|
# Syntax error handler.
|
|
1312
|
# Syntax error handler.
|
|
1313
|
self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
|
|
1313
|
self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
|
|
1314
|
|
|
1314
|
|
|
1315
|
# The interactive one is initialized with an offset, meaning we always
|
|
1315
|
# The interactive one is initialized with an offset, meaning we always
|
|
1316
|
# want to remove the topmost item in the traceback, which is our own
|
|
1316
|
# want to remove the topmost item in the traceback, which is our own
|
|
1317
|
# internal code. Valid modes: ['Plain','Context','Verbose']
|
|
1317
|
# internal code. Valid modes: ['Plain','Context','Verbose']
|
|
1318
|
self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
|
|
1318
|
self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
|
|
1319
|
color_scheme='NoColor',
|
|
1319
|
color_scheme='NoColor',
|
|
1320
|
tb_offset = 1)
|
|
1320
|
tb_offset = 1)
|
|
1321
|
|
|
1321
|
|
|
1322
|
# The instance will store a pointer to the system-wide exception hook,
|
|
1322
|
# The instance will store a pointer to the system-wide exception hook,
|
|
1323
|
# so that runtime code (such as magics) can access it. This is because
|
|
1323
|
# so that runtime code (such as magics) can access it. This is because
|
|
1324
|
# during the read-eval loop, it may get temporarily overwritten.
|
|
1324
|
# during the read-eval loop, it may get temporarily overwritten.
|
|
1325
|
self.sys_excepthook = sys.excepthook
|
|
1325
|
self.sys_excepthook = sys.excepthook
|
|
1326
|
|
|
1326
|
|
|
1327
|
# and add any custom exception handlers the user may have specified
|
|
1327
|
# and add any custom exception handlers the user may have specified
|
|
1328
|
self.set_custom_exc(*custom_exceptions)
|
|
1328
|
self.set_custom_exc(*custom_exceptions)
|
|
1329
|
|
|
1329
|
|
|
1330
|
# Set the exception mode
|
|
1330
|
# Set the exception mode
|
|
1331
|
self.InteractiveTB.set_mode(mode=self.xmode)
|
|
1331
|
self.InteractiveTB.set_mode(mode=self.xmode)
|
|
1332
|
|
|
1332
|
|
|
1333
|
def set_custom_exc(self, exc_tuple, handler):
|
|
1333
|
def set_custom_exc(self, exc_tuple, handler):
|
|
1334
|
"""set_custom_exc(exc_tuple,handler)
|
|
1334
|
"""set_custom_exc(exc_tuple,handler)
|
|
1335
|
|
|
1335
|
|
|
1336
|
Set a custom exception handler, which will be called if any of the
|
|
1336
|
Set a custom exception handler, which will be called if any of the
|
|
1337
|
exceptions in exc_tuple occur in the mainloop (specifically, in the
|
|
1337
|
exceptions in exc_tuple occur in the mainloop (specifically, in the
|
|
1338
|
runcode() method.
|
|
1338
|
runcode() method.
|
|
1339
|
|
|
1339
|
|
|
1340
|
Inputs:
|
|
1340
|
Inputs:
|
|
1341
|
|
|
1341
|
|
|
1342
|
- exc_tuple: a *tuple* of valid exceptions to call the defined
|
|
1342
|
- exc_tuple: a *tuple* of valid exceptions to call the defined
|
|
1343
|
handler for. It is very important that you use a tuple, and NOT A
|
|
1343
|
handler for. It is very important that you use a tuple, and NOT A
|
|
1344
|
LIST here, because of the way Python's except statement works. If
|
|
1344
|
LIST here, because of the way Python's except statement works. If
|
|
1345
|
you only want to trap a single exception, use a singleton tuple:
|
|
1345
|
you only want to trap a single exception, use a singleton tuple:
|
|
1346
|
|
|
1346
|
|
|
1347
|
exc_tuple == (MyCustomException,)
|
|
1347
|
exc_tuple == (MyCustomException,)
|
|
1348
|
|
|
1348
|
|
|
1349
|
- handler: this must be defined as a function with the following
|
|
1349
|
- handler: this must be defined as a function with the following
|
|
1350
|
basic interface::
|
|
1350
|
basic interface::
|
|
1351
|
|
|
1351
|
|
|
1352
|
def my_handler(self, etype, value, tb, tb_offset=None)
|
|
1352
|
def my_handler(self, etype, value, tb, tb_offset=None)
|
|
1353
|
...
|
|
1353
|
...
|
|
1354
|
# The return value must be
|
|
1354
|
# The return value must be
|
|
1355
|
return structured_traceback
|
|
1355
|
return structured_traceback
|
|
1356
|
|
|
1356
|
|
|
1357
|
This will be made into an instance method (via new.instancemethod)
|
|
1357
|
This will be made into an instance method (via new.instancemethod)
|
|
1358
|
of IPython itself, and it will be called if any of the exceptions
|
|
1358
|
of IPython itself, and it will be called if any of the exceptions
|
|
1359
|
listed in the exc_tuple are caught. If the handler is None, an
|
|
1359
|
listed in the exc_tuple are caught. If the handler is None, an
|
|
1360
|
internal basic one is used, which just prints basic info.
|
|
1360
|
internal basic one is used, which just prints basic info.
|
|
1361
|
|
|
1361
|
|
|
1362
|
WARNING: by putting in your own exception handler into IPython's main
|
|
1362
|
WARNING: by putting in your own exception handler into IPython's main
|
|
1363
|
execution loop, you run a very good chance of nasty crashes. This
|
|
1363
|
execution loop, you run a very good chance of nasty crashes. This
|
|
1364
|
facility should only be used if you really know what you are doing."""
|
|
1364
|
facility should only be used if you really know what you are doing."""
|
|
1365
|
|
|
1365
|
|
|
1366
|
assert type(exc_tuple)==type(()) , \
|
|
1366
|
assert type(exc_tuple)==type(()) , \
|
|
1367
|
"The custom exceptions must be given AS A TUPLE."
|
|
1367
|
"The custom exceptions must be given AS A TUPLE."
|
|
1368
|
|
|
1368
|
|
|
1369
|
def dummy_handler(self,etype,value,tb):
|
|
1369
|
def dummy_handler(self,etype,value,tb):
|
|
1370
|
print '*** Simple custom exception handler ***'
|
|
1370
|
print '*** Simple custom exception handler ***'
|
|
1371
|
print 'Exception type :',etype
|
|
1371
|
print 'Exception type :',etype
|
|
1372
|
print 'Exception value:',value
|
|
1372
|
print 'Exception value:',value
|
|
1373
|
print 'Traceback :',tb
|
|
1373
|
print 'Traceback :',tb
|
|
1374
|
print 'Source code :','\n'.join(self.buffer)
|
|
1374
|
print 'Source code :','\n'.join(self.buffer)
|
|
1375
|
|
|
1375
|
|
|
1376
|
if handler is None: handler = dummy_handler
|
|
1376
|
if handler is None: handler = dummy_handler
|
|
1377
|
|
|
1377
|
|
|
1378
|
self.CustomTB = new.instancemethod(handler,self,self.__class__)
|
|
1378
|
self.CustomTB = new.instancemethod(handler,self,self.__class__)
|
|
1379
|
self.custom_exceptions = exc_tuple
|
|
1379
|
self.custom_exceptions = exc_tuple
|
|
1380
|
|
|
1380
|
|
|
1381
|
def excepthook(self, etype, value, tb):
|
|
1381
|
def excepthook(self, etype, value, tb):
|
|
1382
|
"""One more defense for GUI apps that call sys.excepthook.
|
|
1382
|
"""One more defense for GUI apps that call sys.excepthook.
|
|
1383
|
|
|
1383
|
|
|
1384
|
GUI frameworks like wxPython trap exceptions and call
|
|
1384
|
GUI frameworks like wxPython trap exceptions and call
|
|
1385
|
sys.excepthook themselves. I guess this is a feature that
|
|
1385
|
sys.excepthook themselves. I guess this is a feature that
|
|
1386
|
enables them to keep running after exceptions that would
|
|
1386
|
enables them to keep running after exceptions that would
|
|
1387
|
otherwise kill their mainloop. This is a bother for IPython
|
|
1387
|
otherwise kill their mainloop. This is a bother for IPython
|
|
1388
|
which excepts to catch all of the program exceptions with a try:
|
|
1388
|
which excepts to catch all of the program exceptions with a try:
|
|
1389
|
except: statement.
|
|
1389
|
except: statement.
|
|
1390
|
|
|
1390
|
|
|
1391
|
Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
|
|
1391
|
Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
|
|
1392
|
any app directly invokes sys.excepthook, it will look to the user like
|
|
1392
|
any app directly invokes sys.excepthook, it will look to the user like
|
|
1393
|
IPython crashed. In order to work around this, we can disable the
|
|
1393
|
IPython crashed. In order to work around this, we can disable the
|
|
1394
|
CrashHandler and replace it with this excepthook instead, which prints a
|
|
1394
|
CrashHandler and replace it with this excepthook instead, which prints a
|
|
1395
|
regular traceback using our InteractiveTB. In this fashion, apps which
|
|
1395
|
regular traceback using our InteractiveTB. In this fashion, apps which
|
|
1396
|
call sys.excepthook will generate a regular-looking exception from
|
|
1396
|
call sys.excepthook will generate a regular-looking exception from
|
|
1397
|
IPython, and the CrashHandler will only be triggered by real IPython
|
|
1397
|
IPython, and the CrashHandler will only be triggered by real IPython
|
|
1398
|
crashes.
|
|
1398
|
crashes.
|
|
1399
|
|
|
1399
|
|
|
1400
|
This hook should be used sparingly, only in places which are not likely
|
|
1400
|
This hook should be used sparingly, only in places which are not likely
|
|
1401
|
to be true IPython errors.
|
|
1401
|
to be true IPython errors.
|
|
1402
|
"""
|
|
1402
|
"""
|
|
1403
|
self.showtraceback((etype,value,tb),tb_offset=0)
|
|
1403
|
self.showtraceback((etype,value,tb),tb_offset=0)
|
|
1404
|
|
|
1404
|
|
|
1405
|
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
|
|
1405
|
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
|
|
1406
|
exception_only=False):
|
|
1406
|
exception_only=False):
|
|
1407
|
"""Display the exception that just occurred.
|
|
1407
|
"""Display the exception that just occurred.
|
|
1408
|
|
|
1408
|
|
|
1409
|
If nothing is known about the exception, this is the method which
|
|
1409
|
If nothing is known about the exception, this is the method which
|
|
1410
|
should be used throughout the code for presenting user tracebacks,
|
|
1410
|
should be used throughout the code for presenting user tracebacks,
|
|
1411
|
rather than directly invoking the InteractiveTB object.
|
|
1411
|
rather than directly invoking the InteractiveTB object.
|
|
1412
|
|
|
1412
|
|
|
1413
|
A specific showsyntaxerror() also exists, but this method can take
|
|
1413
|
A specific showsyntaxerror() also exists, but this method can take
|
|
1414
|
care of calling it if needed, so unless you are explicitly catching a
|
|
1414
|
care of calling it if needed, so unless you are explicitly catching a
|
|
1415
|
SyntaxError exception, don't try to analyze the stack manually and
|
|
1415
|
SyntaxError exception, don't try to analyze the stack manually and
|
|
1416
|
simply call this method."""
|
|
1416
|
simply call this method."""
|
|
1417
|
|
|
1417
|
|
|
1418
|
try:
|
|
1418
|
try:
|
|
1419
|
if exc_tuple is None:
|
|
1419
|
if exc_tuple is None:
|
|
1420
|
etype, value, tb = sys.exc_info()
|
|
1420
|
etype, value, tb = sys.exc_info()
|
|
1421
|
else:
|
|
1421
|
else:
|
|
1422
|
etype, value, tb = exc_tuple
|
|
1422
|
etype, value, tb = exc_tuple
|
|
1423
|
|
|
1423
|
|
|
1424
|
if etype is None:
|
|
1424
|
if etype is None:
|
|
1425
|
if hasattr(sys, 'last_type'):
|
|
1425
|
if hasattr(sys, 'last_type'):
|
|
1426
|
etype, value, tb = sys.last_type, sys.last_value, \
|
|
1426
|
etype, value, tb = sys.last_type, sys.last_value, \
|
|
1427
|
sys.last_traceback
|
|
1427
|
sys.last_traceback
|
|
1428
|
else:
|
|
1428
|
else:
|
|
1429
|
self.write_err('No traceback available to show.\n')
|
|
1429
|
self.write_err('No traceback available to show.\n')
|
|
1430
|
return
|
|
1430
|
return
|
|
1431
|
|
|
1431
|
|
|
1432
|
if etype is SyntaxError:
|
|
1432
|
if etype is SyntaxError:
|
|
1433
|
# Though this won't be called by syntax errors in the input
|
|
1433
|
# Though this won't be called by syntax errors in the input
|
|
1434
|
# line, there may be SyntaxError cases whith imported code.
|
|
1434
|
# line, there may be SyntaxError cases whith imported code.
|
|
1435
|
self.showsyntaxerror(filename)
|
|
1435
|
self.showsyntaxerror(filename)
|
|
1436
|
elif etype is UsageError:
|
|
1436
|
elif etype is UsageError:
|
|
1437
|
print "UsageError:", value
|
|
1437
|
print "UsageError:", value
|
|
1438
|
else:
|
|
1438
|
else:
|
|
1439
|
# WARNING: these variables are somewhat deprecated and not
|
|
1439
|
# WARNING: these variables are somewhat deprecated and not
|
|
1440
|
# necessarily safe to use in a threaded environment, but tools
|
|
1440
|
# necessarily safe to use in a threaded environment, but tools
|
|
1441
|
# like pdb depend on their existence, so let's set them. If we
|
|
1441
|
# like pdb depend on their existence, so let's set them. If we
|
|
1442
|
# find problems in the field, we'll need to revisit their use.
|
|
1442
|
# find problems in the field, we'll need to revisit their use.
|
|
1443
|
sys.last_type = etype
|
|
1443
|
sys.last_type = etype
|
|
1444
|
sys.last_value = value
|
|
1444
|
sys.last_value = value
|
|
1445
|
sys.last_traceback = tb
|
|
1445
|
sys.last_traceback = tb
|
|
1446
|
|
|
1446
|
|
|
1447
|
if etype in self.custom_exceptions:
|
|
1447
|
if etype in self.custom_exceptions:
|
|
1448
|
# FIXME: Old custom traceback objects may just return a
|
|
1448
|
# FIXME: Old custom traceback objects may just return a
|
|
1449
|
# string, in that case we just put it into a list
|
|
1449
|
# string, in that case we just put it into a list
|
|
1450
|
stb = self.CustomTB(etype, value, tb, tb_offset)
|
|
1450
|
stb = self.CustomTB(etype, value, tb, tb_offset)
|
|
1451
|
if isinstance(ctb, basestring):
|
|
1451
|
if isinstance(ctb, basestring):
|
|
1452
|
stb = [stb]
|
|
1452
|
stb = [stb]
|
|
1453
|
else:
|
|
1453
|
else:
|
|
1454
|
if exception_only:
|
|
1454
|
if exception_only:
|
|
1455
|
stb = ['An exception has occurred, use %tb to see '
|
|
1455
|
stb = ['An exception has occurred, use %tb to see '
|
|
1456
|
'the full traceback.\n']
|
|
1456
|
'the full traceback.\n']
|
|
1457
|
stb.extend(self.InteractiveTB.get_exception_only(etype,
|
|
1457
|
stb.extend(self.InteractiveTB.get_exception_only(etype,
|
|
1458
|
value))
|
|
1458
|
value))
|
|
1459
|
else:
|
|
1459
|
else:
|
|
1460
|
stb = self.InteractiveTB.structured_traceback(etype,
|
|
1460
|
stb = self.InteractiveTB.structured_traceback(etype,
|
|
1461
|
value, tb, tb_offset=tb_offset)
|
|
1461
|
value, tb, tb_offset=tb_offset)
|
|
1462
|
# FIXME: the pdb calling should be done by us, not by
|
|
1462
|
# FIXME: the pdb calling should be done by us, not by
|
|
1463
|
# the code computing the traceback.
|
|
1463
|
# the code computing the traceback.
|
|
1464
|
if self.InteractiveTB.call_pdb:
|
|
1464
|
if self.InteractiveTB.call_pdb:
|
|
1465
|
# pdb mucks up readline, fix it back
|
|
1465
|
# pdb mucks up readline, fix it back
|
|
1466
|
self.set_readline_completer()
|
|
1466
|
self.set_readline_completer()
|
|
1467
|
|
|
1467
|
|
|
1468
|
# Actually show the traceback
|
|
1468
|
# Actually show the traceback
|
|
1469
|
self._showtraceback(etype, value, stb)
|
|
1469
|
self._showtraceback(etype, value, stb)
|
|
1470
|
|
|
1470
|
|
|
1471
|
except KeyboardInterrupt:
|
|
1471
|
except KeyboardInterrupt:
|
|
1472
|
self.write_err("\nKeyboardInterrupt\n")
|
|
1472
|
self.write_err("\nKeyboardInterrupt\n")
|
|
1473
|
|
|
1473
|
|
|
1474
|
def _showtraceback(self, etype, evalue, stb):
|
|
1474
|
def _showtraceback(self, etype, evalue, stb):
|
|
1475
|
"""Actually show a traceback.
|
|
1475
|
"""Actually show a traceback.
|
|
1476
|
|
|
1476
|
|
|
1477
|
Subclasses may override this method to put the traceback on a different
|
|
1477
|
Subclasses may override this method to put the traceback on a different
|
|
1478
|
place, like a side channel.
|
|
1478
|
place, like a side channel.
|
|
1479
|
"""
|
|
1479
|
"""
|
|
1480
|
# FIXME: this should use the proper write channels, but our test suite
|
|
1480
|
# FIXME: this should use the proper write channels, but our test suite
|
|
1481
|
# relies on it coming out of stdout...
|
|
1481
|
# relies on it coming out of stdout...
|
|
1482
|
print >> sys.stdout, self.InteractiveTB.stb2text(stb)
|
|
1482
|
print >> sys.stdout, self.InteractiveTB.stb2text(stb)
|
|
1483
|
|
|
1483
|
|
|
1484
|
def showsyntaxerror(self, filename=None):
|
|
1484
|
def showsyntaxerror(self, filename=None):
|
|
1485
|
"""Display the syntax error that just occurred.
|
|
1485
|
"""Display the syntax error that just occurred.
|
|
1486
|
|
|
1486
|
|
|
1487
|
This doesn't display a stack trace because there isn't one.
|
|
1487
|
This doesn't display a stack trace because there isn't one.
|
|
1488
|
|
|
1488
|
|
|
1489
|
If a filename is given, it is stuffed in the exception instead
|
|
1489
|
If a filename is given, it is stuffed in the exception instead
|
|
1490
|
of what was there before (because Python's parser always uses
|
|
1490
|
of what was there before (because Python's parser always uses
|
|
1491
|
"<string>" when reading from a string).
|
|
1491
|
"<string>" when reading from a string).
|
|
1492
|
"""
|
|
1492
|
"""
|
|
1493
|
etype, value, last_traceback = sys.exc_info()
|
|
1493
|
etype, value, last_traceback = sys.exc_info()
|
|
1494
|
|
|
1494
|
|
|
1495
|
# See note about these variables in showtraceback() above
|
|
1495
|
# See note about these variables in showtraceback() above
|
|
1496
|
sys.last_type = etype
|
|
1496
|
sys.last_type = etype
|
|
1497
|
sys.last_value = value
|
|
1497
|
sys.last_value = value
|
|
1498
|
sys.last_traceback = last_traceback
|
|
1498
|
sys.last_traceback = last_traceback
|
|
1499
|
|
|
1499
|
|
|
1500
|
if filename and etype is SyntaxError:
|
|
1500
|
if filename and etype is SyntaxError:
|
|
1501
|
# Work hard to stuff the correct filename in the exception
|
|
1501
|
# Work hard to stuff the correct filename in the exception
|
|
1502
|
try:
|
|
1502
|
try:
|
|
1503
|
msg, (dummy_filename, lineno, offset, line) = value
|
|
1503
|
msg, (dummy_filename, lineno, offset, line) = value
|
|
1504
|
except:
|
|
1504
|
except:
|
|
1505
|
# Not the format we expect; leave it alone
|
|
1505
|
# Not the format we expect; leave it alone
|
|
1506
|
pass
|
|
1506
|
pass
|
|
1507
|
else:
|
|
1507
|
else:
|
|
1508
|
# Stuff in the right filename
|
|
1508
|
# Stuff in the right filename
|
|
1509
|
try:
|
|
1509
|
try:
|
|
1510
|
# Assume SyntaxError is a class exception
|
|
1510
|
# Assume SyntaxError is a class exception
|
|
1511
|
value = SyntaxError(msg, (filename, lineno, offset, line))
|
|
1511
|
value = SyntaxError(msg, (filename, lineno, offset, line))
|
|
1512
|
except:
|
|
1512
|
except:
|
|
1513
|
# If that failed, assume SyntaxError is a string
|
|
1513
|
# If that failed, assume SyntaxError is a string
|
|
1514
|
value = msg, (filename, lineno, offset, line)
|
|
1514
|
value = msg, (filename, lineno, offset, line)
|
|
1515
|
stb = self.SyntaxTB.structured_traceback(etype, value, [])
|
|
1515
|
stb = self.SyntaxTB.structured_traceback(etype, value, [])
|
|
1516
|
self._showtraceback(etype, value, stb)
|
|
1516
|
self._showtraceback(etype, value, stb)
|
|
1517
|
|
|
1517
|
|
|
1518
|
#-------------------------------------------------------------------------
|
|
1518
|
#-------------------------------------------------------------------------
|
|
1519
|
# Things related to readline
|
|
1519
|
# Things related to readline
|
|
1520
|
#-------------------------------------------------------------------------
|
|
1520
|
#-------------------------------------------------------------------------
|
|
1521
|
|
|
1521
|
|
|
1522
|
def init_readline(self):
|
|
1522
|
def init_readline(self):
|
|
1523
|
"""Command history completion/saving/reloading."""
|
|
1523
|
"""Command history completion/saving/reloading."""
|
|
1524
|
|
|
1524
|
|
|
1525
|
if self.readline_use:
|
|
1525
|
if self.readline_use:
|
|
1526
|
import IPython.utils.rlineimpl as readline
|
|
1526
|
import IPython.utils.rlineimpl as readline
|
|
1527
|
|
|
1527
|
|
|
1528
|
self.rl_next_input = None
|
|
1528
|
self.rl_next_input = None
|
|
1529
|
self.rl_do_indent = False
|
|
1529
|
self.rl_do_indent = False
|
|
1530
|
|
|
1530
|
|
|
1531
|
if not self.readline_use or not readline.have_readline:
|
|
1531
|
if not self.readline_use or not readline.have_readline:
|
|
1532
|
self.has_readline = False
|
|
1532
|
self.has_readline = False
|
|
1533
|
self.readline = None
|
|
1533
|
self.readline = None
|
|
1534
|
# Set a number of methods that depend on readline to be no-op
|
|
1534
|
# Set a number of methods that depend on readline to be no-op
|
|
1535
|
self.savehist = no_op
|
|
1535
|
self.savehist = no_op
|
|
1536
|
self.reloadhist = no_op
|
|
1536
|
self.reloadhist = no_op
|
|
1537
|
self.set_readline_completer = no_op
|
|
1537
|
self.set_readline_completer = no_op
|
|
1538
|
self.set_custom_completer = no_op
|
|
1538
|
self.set_custom_completer = no_op
|
|
1539
|
self.set_completer_frame = no_op
|
|
1539
|
self.set_completer_frame = no_op
|
|
1540
|
warn('Readline services not available or not loaded.')
|
|
1540
|
warn('Readline services not available or not loaded.')
|
|
1541
|
else:
|
|
1541
|
else:
|
|
1542
|
self.has_readline = True
|
|
1542
|
self.has_readline = True
|
|
1543
|
self.readline = readline
|
|
1543
|
self.readline = readline
|
|
1544
|
sys.modules['readline'] = readline
|
|
1544
|
sys.modules['readline'] = readline
|
|
1545
|
|
|
1545
|
|
|
1546
|
# Platform-specific configuration
|
|
1546
|
# Platform-specific configuration
|
|
1547
|
if os.name == 'nt':
|
|
1547
|
if os.name == 'nt':
|
|
1548
|
# FIXME - check with Frederick to see if we can harmonize
|
|
1548
|
# FIXME - check with Frederick to see if we can harmonize
|
|
1549
|
# naming conventions with pyreadline to avoid this
|
|
1549
|
# naming conventions with pyreadline to avoid this
|
|
1550
|
# platform-dependent check
|
|
1550
|
# platform-dependent check
|
|
1551
|
self.readline_startup_hook = readline.set_pre_input_hook
|
|
1551
|
self.readline_startup_hook = readline.set_pre_input_hook
|
|
1552
|
else:
|
|
1552
|
else:
|
|
1553
|
self.readline_startup_hook = readline.set_startup_hook
|
|
1553
|
self.readline_startup_hook = readline.set_startup_hook
|
|
1554
|
|
|
1554
|
|
|
1555
|
# Load user's initrc file (readline config)
|
|
1555
|
# Load user's initrc file (readline config)
|
|
1556
|
# Or if libedit is used, load editrc.
|
|
1556
|
# Or if libedit is used, load editrc.
|
|
1557
|
inputrc_name = os.environ.get('INPUTRC')
|
|
1557
|
inputrc_name = os.environ.get('INPUTRC')
|
|
1558
|
if inputrc_name is None:
|
|
1558
|
if inputrc_name is None:
|
|
1559
|
home_dir = get_home_dir()
|
|
1559
|
home_dir = get_home_dir()
|
|
1560
|
if home_dir is not None:
|
|
1560
|
if home_dir is not None:
|
|
1561
|
inputrc_name = '.inputrc'
|
|
1561
|
inputrc_name = '.inputrc'
|
|
1562
|
if readline.uses_libedit:
|
|
1562
|
if readline.uses_libedit:
|
|
1563
|
inputrc_name = '.editrc'
|
|
1563
|
inputrc_name = '.editrc'
|
|
1564
|
inputrc_name = os.path.join(home_dir, inputrc_name)
|
|
1564
|
inputrc_name = os.path.join(home_dir, inputrc_name)
|
|
1565
|
if os.path.isfile(inputrc_name):
|
|
1565
|
if os.path.isfile(inputrc_name):
|
|
1566
|
try:
|
|
1566
|
try:
|
|
1567
|
readline.read_init_file(inputrc_name)
|
|
1567
|
readline.read_init_file(inputrc_name)
|
|
1568
|
except:
|
|
1568
|
except:
|
|
1569
|
warn('Problems reading readline initialization file <%s>'
|
|
1569
|
warn('Problems reading readline initialization file <%s>'
|
|
1570
|
% inputrc_name)
|
|
1570
|
% inputrc_name)
|
|
1571
|
|
|
1571
|
|
|
1572
|
# Configure readline according to user's prefs
|
|
1572
|
# Configure readline according to user's prefs
|
|
1573
|
# This is only done if GNU readline is being used. If libedit
|
|
1573
|
# This is only done if GNU readline is being used. If libedit
|
|
1574
|
# is being used (as on Leopard) the readline config is
|
|
1574
|
# is being used (as on Leopard) the readline config is
|
|
1575
|
# not run as the syntax for libedit is different.
|
|
1575
|
# not run as the syntax for libedit is different.
|
|
1576
|
if not readline.uses_libedit:
|
|
1576
|
if not readline.uses_libedit:
|
|
1577
|
for rlcommand in self.readline_parse_and_bind:
|
|
1577
|
for rlcommand in self.readline_parse_and_bind:
|
|
1578
|
#print "loading rl:",rlcommand # dbg
|
|
1578
|
#print "loading rl:",rlcommand # dbg
|
|
1579
|
readline.parse_and_bind(rlcommand)
|
|
1579
|
readline.parse_and_bind(rlcommand)
|
|
1580
|
|
|
1580
|
|
|
1581
|
# Remove some chars from the delimiters list. If we encounter
|
|
1581
|
# Remove some chars from the delimiters list. If we encounter
|
|
1582
|
# unicode chars, discard them.
|
|
1582
|
# unicode chars, discard them.
|
|
1583
|
delims = readline.get_completer_delims().encode("ascii", "ignore")
|
|
1583
|
delims = readline.get_completer_delims().encode("ascii", "ignore")
|
|
1584
|
delims = delims.translate(string._idmap,
|
|
1584
|
delims = delims.translate(string._idmap,
|
|
1585
|
self.readline_remove_delims)
|
|
1585
|
self.readline_remove_delims)
|
|
1586
|
delims = delims.replace(ESC_MAGIC, '')
|
|
1586
|
delims = delims.replace(ESC_MAGIC, '')
|
|
1587
|
readline.set_completer_delims(delims)
|
|
1587
|
readline.set_completer_delims(delims)
|
|
1588
|
# otherwise we end up with a monster history after a while:
|
|
1588
|
# otherwise we end up with a monster history after a while:
|
|
1589
|
readline.set_history_length(1000)
|
|
1589
|
readline.set_history_length(1000)
|
|
1590
|
try:
|
|
1590
|
try:
|
|
1591
|
#print '*** Reading readline history' # dbg
|
|
1591
|
#print '*** Reading readline history' # dbg
|
|
1592
|
readline.read_history_file(self.histfile)
|
|
1592
|
readline.read_history_file(self.histfile)
|
|
1593
|
except IOError:
|
|
1593
|
except IOError:
|
|
1594
|
pass # It doesn't exist yet.
|
|
1594
|
pass # It doesn't exist yet.
|
|
1595
|
|
|
1595
|
|
|
1596
|
# If we have readline, we want our history saved upon ipython
|
|
1596
|
# If we have readline, we want our history saved upon ipython
|
|
1597
|
# exiting.
|
|
1597
|
# exiting.
|
|
1598
|
atexit.register(self.savehist)
|
|
1598
|
atexit.register(self.savehist)
|
|
1599
|
|
|
1599
|
|
|
1600
|
# Configure auto-indent for all platforms
|
|
1600
|
# Configure auto-indent for all platforms
|
|
1601
|
self.set_autoindent(self.autoindent)
|
|
1601
|
self.set_autoindent(self.autoindent)
|
|
1602
|
|
|
1602
|
|
|
1603
|
def set_next_input(self, s):
|
|
1603
|
def set_next_input(self, s):
|
|
1604
|
""" Sets the 'default' input string for the next command line.
|
|
1604
|
""" Sets the 'default' input string for the next command line.
|
|
1605
|
|
|
1605
|
|
|
1606
|
Requires readline.
|
|
1606
|
Requires readline.
|
|
1607
|
|
|
1607
|
|
|
1608
|
Example:
|
|
1608
|
Example:
|
|
1609
|
|
|
1609
|
|
|
1610
|
[D:\ipython]|1> _ip.set_next_input("Hello Word")
|
|
1610
|
[D:\ipython]|1> _ip.set_next_input("Hello Word")
|
|
1611
|
[D:\ipython]|2> Hello Word_ # cursor is here
|
|
1611
|
[D:\ipython]|2> Hello Word_ # cursor is here
|
|
1612
|
"""
|
|
1612
|
"""
|
|
1613
|
|
|
1613
|
|
|
1614
|
self.rl_next_input = s
|
|
1614
|
self.rl_next_input = s
|
|
1615
|
|
|
1615
|
|
|
1616
|
# Maybe move this to the terminal subclass?
|
|
1616
|
# Maybe move this to the terminal subclass?
|
|
1617
|
def pre_readline(self):
|
|
1617
|
def pre_readline(self):
|
|
1618
|
"""readline hook to be used at the start of each line.
|
|
1618
|
"""readline hook to be used at the start of each line.
|
|
1619
|
|
|
1619
|
|
|
1620
|
Currently it handles auto-indent only."""
|
|
1620
|
Currently it handles auto-indent only."""
|
|
1621
|
|
|
1621
|
|
|
1622
|
if self.rl_do_indent:
|
|
1622
|
if self.rl_do_indent:
|
|
1623
|
self.readline.insert_text(self._indent_current_str())
|
|
1623
|
self.readline.insert_text(self._indent_current_str())
|
|
1624
|
if self.rl_next_input is not None:
|
|
1624
|
if self.rl_next_input is not None:
|
|
1625
|
self.readline.insert_text(self.rl_next_input)
|
|
1625
|
self.readline.insert_text(self.rl_next_input)
|
|
1626
|
self.rl_next_input = None
|
|
1626
|
self.rl_next_input = None
|
|
1627
|
|
|
1627
|
|
|
1628
|
def _indent_current_str(self):
|
|
1628
|
def _indent_current_str(self):
|
|
1629
|
"""return the current level of indentation as a string"""
|
|
1629
|
"""return the current level of indentation as a string"""
|
|
1630
|
return self.indent_current_nsp * ' '
|
|
1630
|
return self.indent_current_nsp * ' '
|
|
1631
|
|
|
1631
|
|
|
1632
|
#-------------------------------------------------------------------------
|
|
1632
|
#-------------------------------------------------------------------------
|
|
1633
|
# Things related to text completion
|
|
1633
|
# Things related to text completion
|
|
1634
|
#-------------------------------------------------------------------------
|
|
1634
|
#-------------------------------------------------------------------------
|
|
1635
|
|
|
1635
|
|
|
1636
|
def init_completer(self):
|
|
1636
|
def init_completer(self):
|
|
1637
|
"""Initialize the completion machinery.
|
|
1637
|
"""Initialize the completion machinery.
|
|
1638
|
|
|
1638
|
|
|
1639
|
This creates completion machinery that can be used by client code,
|
|
1639
|
This creates completion machinery that can be used by client code,
|
|
1640
|
either interactively in-process (typically triggered by the readline
|
|
1640
|
either interactively in-process (typically triggered by the readline
|
|
1641
|
library), programatically (such as in test suites) or out-of-prcess
|
|
1641
|
library), programatically (such as in test suites) or out-of-prcess
|
|
1642
|
(typically over the network by remote frontends).
|
|
1642
|
(typically over the network by remote frontends).
|
|
1643
|
"""
|
|
1643
|
"""
|
|
1644
|
from IPython.core.completer import IPCompleter
|
|
1644
|
from IPython.core.completer import IPCompleter
|
|
|
|
|
1645
|
from IPython.core.completerlib import (module_completer,
|
|
|
|
|
1646
|
magic_run_completer, cd_completer)
|
|
|
|
|
1647
|
|
|
1645
|
self.Completer = IPCompleter(self,
|
|
1648
|
self.Completer = IPCompleter(self,
|
|
1646
|
self.user_ns,
|
|
1649
|
self.user_ns,
|
|
1647
|
self.user_global_ns,
|
|
1650
|
self.user_global_ns,
|
|
1648
|
self.readline_omit__names,
|
|
1651
|
self.readline_omit__names,
|
|
1649
|
self.alias_manager.alias_table,
|
|
1652
|
self.alias_manager.alias_table,
|
|
1650
|
self.has_readline)
|
|
1653
|
self.has_readline)
|
|
|
|
|
1654
|
|
|
|
|
|
1655
|
# Add custom completers to the basic ones built into IPCompleter
|
|
1651
|
sdisp = self.strdispatchers.get('complete_command', StrDispatch())
|
|
1656
|
sdisp = self.strdispatchers.get('complete_command', StrDispatch())
|
|
1652
|
self.strdispatchers['complete_command'] = sdisp
|
|
1657
|
self.strdispatchers['complete_command'] = sdisp
|
|
1653
|
self.Completer.custom_completers = sdisp
|
|
1658
|
self.Completer.custom_completers = sdisp
|
|
1654
|
|
|
1659
|
|
|
|
|
|
1660
|
self.set_hook('complete_command', module_completer, str_key = 'import')
|
|
|
|
|
1661
|
self.set_hook('complete_command', module_completer, str_key = 'from')
|
|
|
|
|
1662
|
self.set_hook('complete_command', magic_run_completer, str_key = '%run')
|
|
|
|
|
1663
|
self.set_hook('complete_command', cd_completer, str_key = '%cd')
|
|
|
|
|
1664
|
|
|
|
|
|
1665
|
# Only configure readline if we truly are using readline. IPython can
|
|
|
|
|
1666
|
# do tab-completion over the network, in GUIs, etc, where readline
|
|
|
|
|
1667
|
# itself may be absent
|
|
1655
|
if self.has_readline:
|
|
1668
|
if self.has_readline:
|
|
1656
|
self.set_readline_completer()
|
|
1669
|
self.set_readline_completer()
|
|
1657
|
|
|
1670
|
|
|
1658
|
def complete(self, text, line=None, cursor_pos=None):
|
|
1671
|
def complete(self, text, line=None, cursor_pos=None):
|
|
1659
|
"""Return the completed text and a list of completions.
|
|
1672
|
"""Return the completed text and a list of completions.
|
|
1660
|
|
|
1673
|
|
|
1661
|
Parameters
|
|
1674
|
Parameters
|
|
1662
|
----------
|
|
1675
|
----------
|
|
1663
|
|
|
1676
|
|
|
1664
|
text : string
|
|
1677
|
text : string
|
|
1665
|
A string of text to be completed on. It can be given as empty and
|
|
1678
|
A string of text to be completed on. It can be given as empty and
|
|
1666
|
instead a line/position pair are given. In this case, the
|
|
1679
|
instead a line/position pair are given. In this case, the
|
|
1667
|
completer itself will split the line like readline does.
|
|
1680
|
completer itself will split the line like readline does.
|
|
1668
|
|
|
1681
|
|
|
1669
|
line : string, optional
|
|
1682
|
line : string, optional
|
|
1670
|
The complete line that text is part of.
|
|
1683
|
The complete line that text is part of.
|
|
1671
|
|
|
1684
|
|
|
1672
|
cursor_pos : int, optional
|
|
1685
|
cursor_pos : int, optional
|
|
1673
|
The position of the cursor on the input line.
|
|
1686
|
The position of the cursor on the input line.
|
|
1674
|
|
|
1687
|
|
|
1675
|
Returns
|
|
1688
|
Returns
|
|
1676
|
-------
|
|
1689
|
-------
|
|
1677
|
text : string
|
|
1690
|
text : string
|
|
1678
|
The actual text that was completed.
|
|
1691
|
The actual text that was completed.
|
|
1679
|
|
|
1692
|
|
|
1680
|
matches : list
|
|
1693
|
matches : list
|
|
1681
|
A sorted list with all possible completions.
|
|
1694
|
A sorted list with all possible completions.
|
|
1682
|
|
|
1695
|
|
|
1683
|
The optional arguments allow the completion to take more context into
|
|
1696
|
The optional arguments allow the completion to take more context into
|
|
1684
|
account, and are part of the low-level completion API.
|
|
1697
|
account, and are part of the low-level completion API.
|
|
1685
|
|
|
1698
|
|
|
1686
|
This is a wrapper around the completion mechanism, similar to what
|
|
1699
|
This is a wrapper around the completion mechanism, similar to what
|
|
1687
|
readline does at the command line when the TAB key is hit. By
|
|
1700
|
readline does at the command line when the TAB key is hit. By
|
|
1688
|
exposing it as a method, it can be used by other non-readline
|
|
1701
|
exposing it as a method, it can be used by other non-readline
|
|
1689
|
environments (such as GUIs) for text completion.
|
|
1702
|
environments (such as GUIs) for text completion.
|
|
1690
|
|
|
1703
|
|
|
1691
|
Simple usage example:
|
|
1704
|
Simple usage example:
|
|
1692
|
|
|
1705
|
|
|
1693
|
In [1]: x = 'hello'
|
|
1706
|
In [1]: x = 'hello'
|
|
1694
|
|
|
1707
|
|
|
1695
|
In [2]: _ip.complete('x.l')
|
|
1708
|
In [2]: _ip.complete('x.l')
|
|
1696
|
Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
|
|
1709
|
Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
|
|
1697
|
"""
|
|
1710
|
"""
|
|
1698
|
|
|
1711
|
|
|
1699
|
# Inject names into __builtin__ so we can complete on the added names.
|
|
1712
|
# Inject names into __builtin__ so we can complete on the added names.
|
|
1700
|
with self.builtin_trap:
|
|
1713
|
with self.builtin_trap:
|
|
1701
|
return self.Completer.complete(text, line, cursor_pos)
|
|
1714
|
return self.Completer.complete(text, line, cursor_pos)
|
|
1702
|
|
|
1715
|
|
|
1703
|
def set_custom_completer(self, completer, pos=0):
|
|
1716
|
def set_custom_completer(self, completer, pos=0):
|
|
1704
|
"""Adds a new custom completer function.
|
|
1717
|
"""Adds a new custom completer function.
|
|
1705
|
|
|
1718
|
|
|
1706
|
The position argument (defaults to 0) is the index in the completers
|
|
1719
|
The position argument (defaults to 0) is the index in the completers
|
|
1707
|
list where you want the completer to be inserted."""
|
|
1720
|
list where you want the completer to be inserted."""
|
|
1708
|
|
|
1721
|
|
|
1709
|
newcomp = new.instancemethod(completer,self.Completer,
|
|
1722
|
newcomp = new.instancemethod(completer,self.Completer,
|
|
1710
|
self.Completer.__class__)
|
|
1723
|
self.Completer.__class__)
|
|
1711
|
self.Completer.matchers.insert(pos,newcomp)
|
|
1724
|
self.Completer.matchers.insert(pos,newcomp)
|
|
1712
|
|
|
1725
|
|
|
1713
|
def set_readline_completer(self):
|
|
1726
|
def set_readline_completer(self):
|
|
1714
|
"""Reset readline's completer to be our own."""
|
|
1727
|
"""Reset readline's completer to be our own."""
|
|
1715
|
self.readline.set_completer(self.Completer.rlcomplete)
|
|
1728
|
self.readline.set_completer(self.Completer.rlcomplete)
|
|
1716
|
|
|
1729
|
|
|
1717
|
def set_completer_frame(self, frame=None):
|
|
1730
|
def set_completer_frame(self, frame=None):
|
|
1718
|
"""Set the frame of the completer."""
|
|
1731
|
"""Set the frame of the completer."""
|
|
1719
|
if frame:
|
|
1732
|
if frame:
|
|
1720
|
self.Completer.namespace = frame.f_locals
|
|
1733
|
self.Completer.namespace = frame.f_locals
|
|
1721
|
self.Completer.global_namespace = frame.f_globals
|
|
1734
|
self.Completer.global_namespace = frame.f_globals
|
|
1722
|
else:
|
|
1735
|
else:
|
|
1723
|
self.Completer.namespace = self.user_ns
|
|
1736
|
self.Completer.namespace = self.user_ns
|
|
1724
|
self.Completer.global_namespace = self.user_global_ns
|
|
1737
|
self.Completer.global_namespace = self.user_global_ns
|
|
1725
|
|
|
1738
|
|
|
1726
|
#-------------------------------------------------------------------------
|
|
1739
|
#-------------------------------------------------------------------------
|
|
1727
|
# Things related to magics
|
|
1740
|
# Things related to magics
|
|
1728
|
#-------------------------------------------------------------------------
|
|
1741
|
#-------------------------------------------------------------------------
|
|
1729
|
|
|
1742
|
|
|
1730
|
def init_magics(self):
|
|
1743
|
def init_magics(self):
|
|
1731
|
# FIXME: Move the color initialization to the DisplayHook, which
|
|
1744
|
# FIXME: Move the color initialization to the DisplayHook, which
|
|
1732
|
# should be split into a prompt manager and displayhook. We probably
|
|
1745
|
# should be split into a prompt manager and displayhook. We probably
|
|
1733
|
# even need a centralize colors management object.
|
|
1746
|
# even need a centralize colors management object.
|
|
1734
|
self.magic_colors(self.colors)
|
|
1747
|
self.magic_colors(self.colors)
|
|
1735
|
# History was moved to a separate module
|
|
1748
|
# History was moved to a separate module
|
|
1736
|
from . import history
|
|
1749
|
from . import history
|
|
1737
|
history.init_ipython(self)
|
|
1750
|
history.init_ipython(self)
|
|
1738
|
|
|
1751
|
|
|
1739
|
def magic(self,arg_s):
|
|
1752
|
def magic(self,arg_s):
|
|
1740
|
"""Call a magic function by name.
|
|
1753
|
"""Call a magic function by name.
|
|
1741
|
|
|
1754
|
|
|
1742
|
Input: a string containing the name of the magic function to call and
|
|
1755
|
Input: a string containing the name of the magic function to call and
|
|
1743
|
any additional arguments to be passed to the magic.
|
|
1756
|
any additional arguments to be passed to the magic.
|
|
1744
|
|
|
1757
|
|
|
1745
|
magic('name -opt foo bar') is equivalent to typing at the ipython
|
|
1758
|
magic('name -opt foo bar') is equivalent to typing at the ipython
|
|
1746
|
prompt:
|
|
1759
|
prompt:
|
|
1747
|
|
|
1760
|
|
|
1748
|
In[1]: %name -opt foo bar
|
|
1761
|
In[1]: %name -opt foo bar
|
|
1749
|
|
|
1762
|
|
|
1750
|
To call a magic without arguments, simply use magic('name').
|
|
1763
|
To call a magic without arguments, simply use magic('name').
|
|
1751
|
|
|
1764
|
|
|
1752
|
This provides a proper Python function to call IPython's magics in any
|
|
1765
|
This provides a proper Python function to call IPython's magics in any
|
|
1753
|
valid Python code you can type at the interpreter, including loops and
|
|
1766
|
valid Python code you can type at the interpreter, including loops and
|
|
1754
|
compound statements.
|
|
1767
|
compound statements.
|
|
1755
|
"""
|
|
1768
|
"""
|
|
1756
|
args = arg_s.split(' ',1)
|
|
1769
|
args = arg_s.split(' ',1)
|
|
1757
|
magic_name = args[0]
|
|
1770
|
magic_name = args[0]
|
|
1758
|
magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
|
|
1771
|
magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
|
|
1759
|
|
|
1772
|
|
|
1760
|
try:
|
|
1773
|
try:
|
|
1761
|
magic_args = args[1]
|
|
1774
|
magic_args = args[1]
|
|
1762
|
except IndexError:
|
|
1775
|
except IndexError:
|
|
1763
|
magic_args = ''
|
|
1776
|
magic_args = ''
|
|
1764
|
fn = getattr(self,'magic_'+magic_name,None)
|
|
1777
|
fn = getattr(self,'magic_'+magic_name,None)
|
|
1765
|
if fn is None:
|
|
1778
|
if fn is None:
|
|
1766
|
error("Magic function `%s` not found." % magic_name)
|
|
1779
|
error("Magic function `%s` not found." % magic_name)
|
|
1767
|
else:
|
|
1780
|
else:
|
|
1768
|
magic_args = self.var_expand(magic_args,1)
|
|
1781
|
magic_args = self.var_expand(magic_args,1)
|
|
1769
|
with nested(self.builtin_trap,):
|
|
1782
|
with nested(self.builtin_trap,):
|
|
1770
|
result = fn(magic_args)
|
|
1783
|
result = fn(magic_args)
|
|
1771
|
return result
|
|
1784
|
return result
|
|
1772
|
|
|
1785
|
|
|
1773
|
def define_magic(self, magicname, func):
|
|
1786
|
def define_magic(self, magicname, func):
|
|
1774
|
"""Expose own function as magic function for ipython
|
|
1787
|
"""Expose own function as magic function for ipython
|
|
1775
|
|
|
1788
|
|
|
1776
|
def foo_impl(self,parameter_s=''):
|
|
1789
|
def foo_impl(self,parameter_s=''):
|
|
1777
|
'My very own magic!. (Use docstrings, IPython reads them).'
|
|
1790
|
'My very own magic!. (Use docstrings, IPython reads them).'
|
|
1778
|
print 'Magic function. Passed parameter is between < >:'
|
|
1791
|
print 'Magic function. Passed parameter is between < >:'
|
|
1779
|
print '<%s>' % parameter_s
|
|
1792
|
print '<%s>' % parameter_s
|
|
1780
|
print 'The self object is:',self
|
|
1793
|
print 'The self object is:',self
|
|
1781
|
|
|
1794
|
|
|
1782
|
self.define_magic('foo',foo_impl)
|
|
1795
|
self.define_magic('foo',foo_impl)
|
|
1783
|
"""
|
|
1796
|
"""
|
|
1784
|
|
|
1797
|
|
|
1785
|
import new
|
|
1798
|
import new
|
|
1786
|
im = new.instancemethod(func,self, self.__class__)
|
|
1799
|
im = new.instancemethod(func,self, self.__class__)
|
|
1787
|
old = getattr(self, "magic_" + magicname, None)
|
|
1800
|
old = getattr(self, "magic_" + magicname, None)
|
|
1788
|
setattr(self, "magic_" + magicname, im)
|
|
1801
|
setattr(self, "magic_" + magicname, im)
|
|
1789
|
return old
|
|
1802
|
return old
|
|
1790
|
|
|
1803
|
|
|
1791
|
#-------------------------------------------------------------------------
|
|
1804
|
#-------------------------------------------------------------------------
|
|
1792
|
# Things related to macros
|
|
1805
|
# Things related to macros
|
|
1793
|
#-------------------------------------------------------------------------
|
|
1806
|
#-------------------------------------------------------------------------
|
|
1794
|
|
|
1807
|
|
|
1795
|
def define_macro(self, name, themacro):
|
|
1808
|
def define_macro(self, name, themacro):
|
|
1796
|
"""Define a new macro
|
|
1809
|
"""Define a new macro
|
|
1797
|
|
|
1810
|
|
|
1798
|
Parameters
|
|
1811
|
Parameters
|
|
1799
|
----------
|
|
1812
|
----------
|
|
1800
|
name : str
|
|
1813
|
name : str
|
|
1801
|
The name of the macro.
|
|
1814
|
The name of the macro.
|
|
1802
|
themacro : str or Macro
|
|
1815
|
themacro : str or Macro
|
|
1803
|
The action to do upon invoking the macro. If a string, a new
|
|
1816
|
The action to do upon invoking the macro. If a string, a new
|
|
1804
|
Macro object is created by passing the string to it.
|
|
1817
|
Macro object is created by passing the string to it.
|
|
1805
|
"""
|
|
1818
|
"""
|
|
1806
|
|
|
1819
|
|
|
1807
|
from IPython.core import macro
|
|
1820
|
from IPython.core import macro
|
|
1808
|
|
|
1821
|
|
|
1809
|
if isinstance(themacro, basestring):
|
|
1822
|
if isinstance(themacro, basestring):
|
|
1810
|
themacro = macro.Macro(themacro)
|
|
1823
|
themacro = macro.Macro(themacro)
|
|
1811
|
if not isinstance(themacro, macro.Macro):
|
|
1824
|
if not isinstance(themacro, macro.Macro):
|
|
1812
|
raise ValueError('A macro must be a string or a Macro instance.')
|
|
1825
|
raise ValueError('A macro must be a string or a Macro instance.')
|
|
1813
|
self.user_ns[name] = themacro
|
|
1826
|
self.user_ns[name] = themacro
|
|
1814
|
|
|
1827
|
|
|
1815
|
#-------------------------------------------------------------------------
|
|
1828
|
#-------------------------------------------------------------------------
|
|
1816
|
# Things related to the running of system commands
|
|
1829
|
# Things related to the running of system commands
|
|
1817
|
#-------------------------------------------------------------------------
|
|
1830
|
#-------------------------------------------------------------------------
|
|
1818
|
|
|
1831
|
|
|
1819
|
def system(self, cmd):
|
|
1832
|
def system(self, cmd):
|
|
1820
|
"""Call the given cmd in a subprocess."""
|
|
1833
|
"""Call the given cmd in a subprocess."""
|
|
1821
|
# We do not support backgrounding processes because we either use
|
|
1834
|
# We do not support backgrounding processes because we either use
|
|
1822
|
# pexpect or pipes to read from. Users can always just call
|
|
1835
|
# pexpect or pipes to read from. Users can always just call
|
|
1823
|
# os.system() if they really want a background process.
|
|
1836
|
# os.system() if they really want a background process.
|
|
1824
|
if cmd.endswith('&'):
|
|
1837
|
if cmd.endswith('&'):
|
|
1825
|
raise OSError("Background processes not supported.")
|
|
1838
|
raise OSError("Background processes not supported.")
|
|
1826
|
|
|
1839
|
|
|
1827
|
return system(self.var_expand(cmd, depth=2))
|
|
1840
|
return system(self.var_expand(cmd, depth=2))
|
|
1828
|
|
|
1841
|
|
|
1829
|
def getoutput(self, cmd):
|
|
1842
|
def getoutput(self, cmd):
|
|
1830
|
"""Get output (possibly including stderr) from a subprocess."""
|
|
1843
|
"""Get output (possibly including stderr) from a subprocess."""
|
|
1831
|
if cmd.endswith('&'):
|
|
1844
|
if cmd.endswith('&'):
|
|
1832
|
raise OSError("Background processes not supported.")
|
|
1845
|
raise OSError("Background processes not supported.")
|
|
1833
|
return getoutput(self.var_expand(cmd, depth=2))
|
|
1846
|
return getoutput(self.var_expand(cmd, depth=2))
|
|
1834
|
|
|
1847
|
|
|
1835
|
#-------------------------------------------------------------------------
|
|
1848
|
#-------------------------------------------------------------------------
|
|
1836
|
# Things related to aliases
|
|
1849
|
# Things related to aliases
|
|
1837
|
#-------------------------------------------------------------------------
|
|
1850
|
#-------------------------------------------------------------------------
|
|
1838
|
|
|
1851
|
|
|
1839
|
def init_alias(self):
|
|
1852
|
def init_alias(self):
|
|
1840
|
self.alias_manager = AliasManager(shell=self, config=self.config)
|
|
1853
|
self.alias_manager = AliasManager(shell=self, config=self.config)
|
|
1841
|
self.ns_table['alias'] = self.alias_manager.alias_table,
|
|
1854
|
self.ns_table['alias'] = self.alias_manager.alias_table,
|
|
1842
|
|
|
1855
|
|
|
1843
|
#-------------------------------------------------------------------------
|
|
1856
|
#-------------------------------------------------------------------------
|
|
1844
|
# Things related to extensions and plugins
|
|
1857
|
# Things related to extensions and plugins
|
|
1845
|
#-------------------------------------------------------------------------
|
|
1858
|
#-------------------------------------------------------------------------
|
|
1846
|
|
|
1859
|
|
|
1847
|
def init_extension_manager(self):
|
|
1860
|
def init_extension_manager(self):
|
|
1848
|
self.extension_manager = ExtensionManager(shell=self, config=self.config)
|
|
1861
|
self.extension_manager = ExtensionManager(shell=self, config=self.config)
|
|
1849
|
|
|
1862
|
|
|
1850
|
def init_plugin_manager(self):
|
|
1863
|
def init_plugin_manager(self):
|
|
1851
|
self.plugin_manager = PluginManager(config=self.config)
|
|
1864
|
self.plugin_manager = PluginManager(config=self.config)
|
|
1852
|
|
|
1865
|
|
|
1853
|
#-------------------------------------------------------------------------
|
|
1866
|
#-------------------------------------------------------------------------
|
|
1854
|
# Things related to payloads
|
|
1867
|
# Things related to payloads
|
|
1855
|
#-------------------------------------------------------------------------
|
|
1868
|
#-------------------------------------------------------------------------
|
|
1856
|
|
|
1869
|
|
|
1857
|
def init_payload(self):
|
|
1870
|
def init_payload(self):
|
|
1858
|
self.payload_manager = PayloadManager(config=self.config)
|
|
1871
|
self.payload_manager = PayloadManager(config=self.config)
|
|
1859
|
|
|
1872
|
|
|
1860
|
#-------------------------------------------------------------------------
|
|
1873
|
#-------------------------------------------------------------------------
|
|
1861
|
# Things related to the prefilter
|
|
1874
|
# Things related to the prefilter
|
|
1862
|
#-------------------------------------------------------------------------
|
|
1875
|
#-------------------------------------------------------------------------
|
|
1863
|
|
|
1876
|
|
|
1864
|
def init_prefilter(self):
|
|
1877
|
def init_prefilter(self):
|
|
1865
|
self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
|
|
1878
|
self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
|
|
1866
|
# Ultimately this will be refactored in the new interpreter code, but
|
|
1879
|
# Ultimately this will be refactored in the new interpreter code, but
|
|
1867
|
# for now, we should expose the main prefilter method (there's legacy
|
|
1880
|
# for now, we should expose the main prefilter method (there's legacy
|
|
1868
|
# code out there that may rely on this).
|
|
1881
|
# code out there that may rely on this).
|
|
1869
|
self.prefilter = self.prefilter_manager.prefilter_lines
|
|
1882
|
self.prefilter = self.prefilter_manager.prefilter_lines
|
|
1870
|
|
|
1883
|
|
|
1871
|
|
|
1884
|
|
|
1872
|
def auto_rewrite_input(self, cmd):
|
|
1885
|
def auto_rewrite_input(self, cmd):
|
|
1873
|
"""Print to the screen the rewritten form of the user's command.
|
|
1886
|
"""Print to the screen the rewritten form of the user's command.
|
|
1874
|
|
|
1887
|
|
|
1875
|
This shows visual feedback by rewriting input lines that cause
|
|
1888
|
This shows visual feedback by rewriting input lines that cause
|
|
1876
|
automatic calling to kick in, like::
|
|
1889
|
automatic calling to kick in, like::
|
|
1877
|
|
|
1890
|
|
|
1878
|
/f x
|
|
1891
|
/f x
|
|
1879
|
|
|
1892
|
|
|
1880
|
into::
|
|
1893
|
into::
|
|
1881
|
|
|
1894
|
|
|
1882
|
------> f(x)
|
|
1895
|
------> f(x)
|
|
1883
|
|
|
1896
|
|
|
1884
|
after the user's input prompt. This helps the user understand that the
|
|
1897
|
after the user's input prompt. This helps the user understand that the
|
|
1885
|
input line was transformed automatically by IPython.
|
|
1898
|
input line was transformed automatically by IPython.
|
|
1886
|
"""
|
|
1899
|
"""
|
|
1887
|
rw = self.displayhook.prompt1.auto_rewrite() + cmd
|
|
1900
|
rw = self.displayhook.prompt1.auto_rewrite() + cmd
|
|
1888
|
|
|
1901
|
|
|
1889
|
try:
|
|
1902
|
try:
|
|
1890
|
# plain ascii works better w/ pyreadline, on some machines, so
|
|
1903
|
# plain ascii works better w/ pyreadline, on some machines, so
|
|
1891
|
# we use it and only print uncolored rewrite if we have unicode
|
|
1904
|
# we use it and only print uncolored rewrite if we have unicode
|
|
1892
|
rw = str(rw)
|
|
1905
|
rw = str(rw)
|
|
1893
|
print >> IPython.utils.io.Term.cout, rw
|
|
1906
|
print >> IPython.utils.io.Term.cout, rw
|
|
1894
|
except UnicodeEncodeError:
|
|
1907
|
except UnicodeEncodeError:
|
|
1895
|
print "------> " + cmd
|
|
1908
|
print "------> " + cmd
|
|
1896
|
|
|
1909
|
|
|
1897
|
#-------------------------------------------------------------------------
|
|
1910
|
#-------------------------------------------------------------------------
|
|
1898
|
# Things related to extracting values/expressions from kernel and user_ns
|
|
1911
|
# Things related to extracting values/expressions from kernel and user_ns
|
|
1899
|
#-------------------------------------------------------------------------
|
|
1912
|
#-------------------------------------------------------------------------
|
|
1900
|
|
|
1913
|
|
|
1901
|
def _simple_error(self):
|
|
1914
|
def _simple_error(self):
|
|
1902
|
etype, value = sys.exc_info()[:2]
|
|
1915
|
etype, value = sys.exc_info()[:2]
|
|
1903
|
return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
|
|
1916
|
return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
|
|
1904
|
|
|
1917
|
|
|
1905
|
def get_user_variables(self, names):
|
|
1918
|
def get_user_variables(self, names):
|
|
1906
|
"""Get a list of variable names from the user's namespace.
|
|
1919
|
"""Get a list of variable names from the user's namespace.
|
|
1907
|
|
|
1920
|
|
|
1908
|
The return value is a dict with the repr() of each value.
|
|
1921
|
The return value is a dict with the repr() of each value.
|
|
1909
|
"""
|
|
1922
|
"""
|
|
1910
|
out = {}
|
|
1923
|
out = {}
|
|
1911
|
user_ns = self.user_ns
|
|
1924
|
user_ns = self.user_ns
|
|
1912
|
for varname in names:
|
|
1925
|
for varname in names:
|
|
1913
|
try:
|
|
1926
|
try:
|
|
1914
|
value = repr(user_ns[varname])
|
|
1927
|
value = repr(user_ns[varname])
|
|
1915
|
except:
|
|
1928
|
except:
|
|
1916
|
value = self._simple_error()
|
|
1929
|
value = self._simple_error()
|
|
1917
|
out[varname] = value
|
|
1930
|
out[varname] = value
|
|
1918
|
return out
|
|
1931
|
return out
|
|
1919
|
|
|
1932
|
|
|
1920
|
def eval_expressions(self, expressions):
|
|
1933
|
def eval_expressions(self, expressions):
|
|
1921
|
"""Evaluate a dict of expressions in the user's namespace.
|
|
1934
|
"""Evaluate a dict of expressions in the user's namespace.
|
|
1922
|
|
|
1935
|
|
|
1923
|
The return value is a dict with the repr() of each value.
|
|
1936
|
The return value is a dict with the repr() of each value.
|
|
1924
|
"""
|
|
1937
|
"""
|
|
1925
|
out = {}
|
|
1938
|
out = {}
|
|
1926
|
user_ns = self.user_ns
|
|
1939
|
user_ns = self.user_ns
|
|
1927
|
global_ns = self.user_global_ns
|
|
1940
|
global_ns = self.user_global_ns
|
|
1928
|
for key, expr in expressions.iteritems():
|
|
1941
|
for key, expr in expressions.iteritems():
|
|
1929
|
try:
|
|
1942
|
try:
|
|
1930
|
value = repr(eval(expr, global_ns, user_ns))
|
|
1943
|
value = repr(eval(expr, global_ns, user_ns))
|
|
1931
|
except:
|
|
1944
|
except:
|
|
1932
|
value = self._simple_error()
|
|
1945
|
value = self._simple_error()
|
|
1933
|
out[key] = value
|
|
1946
|
out[key] = value
|
|
1934
|
return out
|
|
1947
|
return out
|
|
1935
|
|
|
1948
|
|
|
1936
|
#-------------------------------------------------------------------------
|
|
1949
|
#-------------------------------------------------------------------------
|
|
1937
|
# Things related to the running of code
|
|
1950
|
# Things related to the running of code
|
|
1938
|
#-------------------------------------------------------------------------
|
|
1951
|
#-------------------------------------------------------------------------
|
|
1939
|
|
|
1952
|
|
|
1940
|
def ex(self, cmd):
|
|
1953
|
def ex(self, cmd):
|
|
1941
|
"""Execute a normal python statement in user namespace."""
|
|
1954
|
"""Execute a normal python statement in user namespace."""
|
|
1942
|
with nested(self.builtin_trap,):
|
|
1955
|
with nested(self.builtin_trap,):
|
|
1943
|
exec cmd in self.user_global_ns, self.user_ns
|
|
1956
|
exec cmd in self.user_global_ns, self.user_ns
|
|
1944
|
|
|
1957
|
|
|
1945
|
def ev(self, expr):
|
|
1958
|
def ev(self, expr):
|
|
1946
|
"""Evaluate python expression expr in user namespace.
|
|
1959
|
"""Evaluate python expression expr in user namespace.
|
|
1947
|
|
|
1960
|
|
|
1948
|
Returns the result of evaluation
|
|
1961
|
Returns the result of evaluation
|
|
1949
|
"""
|
|
1962
|
"""
|
|
1950
|
with nested(self.builtin_trap,):
|
|
1963
|
with nested(self.builtin_trap,):
|
|
1951
|
return eval(expr, self.user_global_ns, self.user_ns)
|
|
1964
|
return eval(expr, self.user_global_ns, self.user_ns)
|
|
1952
|
|
|
1965
|
|
|
1953
|
def safe_execfile(self, fname, *where, **kw):
|
|
1966
|
def safe_execfile(self, fname, *where, **kw):
|
|
1954
|
"""A safe version of the builtin execfile().
|
|
1967
|
"""A safe version of the builtin execfile().
|
|
1955
|
|
|
1968
|
|
|
1956
|
This version will never throw an exception, but instead print
|
|
1969
|
This version will never throw an exception, but instead print
|
|
1957
|
helpful error messages to the screen. This only works on pure
|
|
1970
|
helpful error messages to the screen. This only works on pure
|
|
1958
|
Python files with the .py extension.
|
|
1971
|
Python files with the .py extension.
|
|
1959
|
|
|
1972
|
|
|
1960
|
Parameters
|
|
1973
|
Parameters
|
|
1961
|
----------
|
|
1974
|
----------
|
|
1962
|
fname : string
|
|
1975
|
fname : string
|
|
1963
|
The name of the file to be executed.
|
|
1976
|
The name of the file to be executed.
|
|
1964
|
where : tuple
|
|
1977
|
where : tuple
|
|
1965
|
One or two namespaces, passed to execfile() as (globals,locals).
|
|
1978
|
One or two namespaces, passed to execfile() as (globals,locals).
|
|
1966
|
If only one is given, it is passed as both.
|
|
1979
|
If only one is given, it is passed as both.
|
|
1967
|
exit_ignore : bool (False)
|
|
1980
|
exit_ignore : bool (False)
|
|
1968
|
If True, then silence SystemExit for non-zero status (it is always
|
|
1981
|
If True, then silence SystemExit for non-zero status (it is always
|
|
1969
|
silenced for zero status, as it is so common).
|
|
1982
|
silenced for zero status, as it is so common).
|
|
1970
|
"""
|
|
1983
|
"""
|
|
1971
|
kw.setdefault('exit_ignore', False)
|
|
1984
|
kw.setdefault('exit_ignore', False)
|
|
1972
|
|
|
1985
|
|
|
1973
|
fname = os.path.abspath(os.path.expanduser(fname))
|
|
1986
|
fname = os.path.abspath(os.path.expanduser(fname))
|
|
1974
|
|
|
1987
|
|
|
1975
|
# Make sure we have a .py file
|
|
1988
|
# Make sure we have a .py file
|
|
1976
|
if not fname.endswith('.py'):
|
|
1989
|
if not fname.endswith('.py'):
|
|
1977
|
warn('File must end with .py to be run using execfile: <%s>' % fname)
|
|
1990
|
warn('File must end with .py to be run using execfile: <%s>' % fname)
|
|
1978
|
|
|
1991
|
|
|
1979
|
# Make sure we can open the file
|
|
1992
|
# Make sure we can open the file
|
|
1980
|
try:
|
|
1993
|
try:
|
|
1981
|
with open(fname) as thefile:
|
|
1994
|
with open(fname) as thefile:
|
|
1982
|
pass
|
|
1995
|
pass
|
|
1983
|
except:
|
|
1996
|
except:
|
|
1984
|
warn('Could not open file <%s> for safe execution.' % fname)
|
|
1997
|
warn('Could not open file <%s> for safe execution.' % fname)
|
|
1985
|
return
|
|
1998
|
return
|
|
1986
|
|
|
1999
|
|
|
1987
|
# Find things also in current directory. This is needed to mimic the
|
|
2000
|
# Find things also in current directory. This is needed to mimic the
|
|
1988
|
# behavior of running a script from the system command line, where
|
|
2001
|
# behavior of running a script from the system command line, where
|
|
1989
|
# Python inserts the script's directory into sys.path
|
|
2002
|
# Python inserts the script's directory into sys.path
|
|
1990
|
dname = os.path.dirname(fname)
|
|
2003
|
dname = os.path.dirname(fname)
|
|
1991
|
|
|
2004
|
|
|
1992
|
with prepended_to_syspath(dname):
|
|
2005
|
with prepended_to_syspath(dname):
|
|
1993
|
try:
|
|
2006
|
try:
|
|
1994
|
execfile(fname,*where)
|
|
2007
|
execfile(fname,*where)
|
|
1995
|
except SystemExit, status:
|
|
2008
|
except SystemExit, status:
|
|
1996
|
# If the call was made with 0 or None exit status (sys.exit(0)
|
|
2009
|
# If the call was made with 0 or None exit status (sys.exit(0)
|
|
1997
|
# or sys.exit() ), don't bother showing a traceback, as both of
|
|
2010
|
# or sys.exit() ), don't bother showing a traceback, as both of
|
|
1998
|
# these are considered normal by the OS:
|
|
2011
|
# these are considered normal by the OS:
|
|
1999
|
# > python -c'import sys;sys.exit(0)'; echo $?
|
|
2012
|
# > python -c'import sys;sys.exit(0)'; echo $?
|
|
2000
|
# 0
|
|
2013
|
# 0
|
|
2001
|
# > python -c'import sys;sys.exit()'; echo $?
|
|
2014
|
# > python -c'import sys;sys.exit()'; echo $?
|
|
2002
|
# 0
|
|
2015
|
# 0
|
|
2003
|
# For other exit status, we show the exception unless
|
|
2016
|
# For other exit status, we show the exception unless
|
|
2004
|
# explicitly silenced, but only in short form.
|
|
2017
|
# explicitly silenced, but only in short form.
|
|
2005
|
if status.code not in (0, None) and not kw['exit_ignore']:
|
|
2018
|
if status.code not in (0, None) and not kw['exit_ignore']:
|
|
2006
|
self.showtraceback(exception_only=True)
|
|
2019
|
self.showtraceback(exception_only=True)
|
|
2007
|
except:
|
|
2020
|
except:
|
|
2008
|
self.showtraceback()
|
|
2021
|
self.showtraceback()
|
|
2009
|
|
|
2022
|
|
|
2010
|
def safe_execfile_ipy(self, fname):
|
|
2023
|
def safe_execfile_ipy(self, fname):
|
|
2011
|
"""Like safe_execfile, but for .ipy files with IPython syntax.
|
|
2024
|
"""Like safe_execfile, but for .ipy files with IPython syntax.
|
|
2012
|
|
|
2025
|
|
|
2013
|
Parameters
|
|
2026
|
Parameters
|
|
2014
|
----------
|
|
2027
|
----------
|
|
2015
|
fname : str
|
|
2028
|
fname : str
|
|
2016
|
The name of the file to execute. The filename must have a
|
|
2029
|
The name of the file to execute. The filename must have a
|
|
2017
|
.ipy extension.
|
|
2030
|
.ipy extension.
|
|
2018
|
"""
|
|
2031
|
"""
|
|
2019
|
fname = os.path.abspath(os.path.expanduser(fname))
|
|
2032
|
fname = os.path.abspath(os.path.expanduser(fname))
|
|
2020
|
|
|
2033
|
|
|
2021
|
# Make sure we have a .py file
|
|
2034
|
# Make sure we have a .py file
|
|
2022
|
if not fname.endswith('.ipy'):
|
|
2035
|
if not fname.endswith('.ipy'):
|
|
2023
|
warn('File must end with .py to be run using execfile: <%s>' % fname)
|
|
2036
|
warn('File must end with .py to be run using execfile: <%s>' % fname)
|
|
2024
|
|
|
2037
|
|
|
2025
|
# Make sure we can open the file
|
|
2038
|
# Make sure we can open the file
|
|
2026
|
try:
|
|
2039
|
try:
|
|
2027
|
with open(fname) as thefile:
|
|
2040
|
with open(fname) as thefile:
|
|
2028
|
pass
|
|
2041
|
pass
|
|
2029
|
except:
|
|
2042
|
except:
|
|
2030
|
warn('Could not open file <%s> for safe execution.' % fname)
|
|
2043
|
warn('Could not open file <%s> for safe execution.' % fname)
|
|
2031
|
return
|
|
2044
|
return
|
|
2032
|
|
|
2045
|
|
|
2033
|
# Find things also in current directory. This is needed to mimic the
|
|
2046
|
# Find things also in current directory. This is needed to mimic the
|
|
2034
|
# behavior of running a script from the system command line, where
|
|
2047
|
# behavior of running a script from the system command line, where
|
|
2035
|
# Python inserts the script's directory into sys.path
|
|
2048
|
# Python inserts the script's directory into sys.path
|
|
2036
|
dname = os.path.dirname(fname)
|
|
2049
|
dname = os.path.dirname(fname)
|
|
2037
|
|
|
2050
|
|
|
2038
|
with prepended_to_syspath(dname):
|
|
2051
|
with prepended_to_syspath(dname):
|
|
2039
|
try:
|
|
2052
|
try:
|
|
2040
|
with open(fname) as thefile:
|
|
2053
|
with open(fname) as thefile:
|
|
2041
|
script = thefile.read()
|
|
2054
|
script = thefile.read()
|
|
2042
|
# self.runlines currently captures all exceptions
|
|
2055
|
# self.runlines currently captures all exceptions
|
|
2043
|
# raise in user code. It would be nice if there were
|
|
2056
|
# raise in user code. It would be nice if there were
|
|
2044
|
# versions of runlines, execfile that did raise, so
|
|
2057
|
# versions of runlines, execfile that did raise, so
|
|
2045
|
# we could catch the errors.
|
|
2058
|
# we could catch the errors.
|
|
2046
|
self.runlines(script, clean=True)
|
|
2059
|
self.runlines(script, clean=True)
|
|
2047
|
except:
|
|
2060
|
except:
|
|
2048
|
self.showtraceback()
|
|
2061
|
self.showtraceback()
|
|
2049
|
warn('Unknown failure executing file: <%s>' % fname)
|
|
2062
|
warn('Unknown failure executing file: <%s>' % fname)
|
|
2050
|
|
|
2063
|
|
|
2051
|
def runlines(self, lines, clean=False):
|
|
2064
|
def runlines(self, lines, clean=False):
|
|
2052
|
"""Run a string of one or more lines of source.
|
|
2065
|
"""Run a string of one or more lines of source.
|
|
2053
|
|
|
2066
|
|
|
2054
|
This method is capable of running a string containing multiple source
|
|
2067
|
This method is capable of running a string containing multiple source
|
|
2055
|
lines, as if they had been entered at the IPython prompt. Since it
|
|
2068
|
lines, as if they had been entered at the IPython prompt. Since it
|
|
2056
|
exposes IPython's processing machinery, the given strings can contain
|
|
2069
|
exposes IPython's processing machinery, the given strings can contain
|
|
2057
|
magic calls (%magic), special shell access (!cmd), etc.
|
|
2070
|
magic calls (%magic), special shell access (!cmd), etc.
|
|
2058
|
"""
|
|
2071
|
"""
|
|
2059
|
|
|
2072
|
|
|
2060
|
if isinstance(lines, (list, tuple)):
|
|
2073
|
if isinstance(lines, (list, tuple)):
|
|
2061
|
lines = '\n'.join(lines)
|
|
2074
|
lines = '\n'.join(lines)
|
|
2062
|
|
|
2075
|
|
|
2063
|
if clean:
|
|
2076
|
if clean:
|
|
2064
|
lines = self._cleanup_ipy_script(lines)
|
|
2077
|
lines = self._cleanup_ipy_script(lines)
|
|
2065
|
|
|
2078
|
|
|
2066
|
# We must start with a clean buffer, in case this is run from an
|
|
2079
|
# We must start with a clean buffer, in case this is run from an
|
|
2067
|
# interactive IPython session (via a magic, for example).
|
|
2080
|
# interactive IPython session (via a magic, for example).
|
|
2068
|
self.resetbuffer()
|
|
2081
|
self.resetbuffer()
|
|
2069
|
lines = lines.splitlines()
|
|
2082
|
lines = lines.splitlines()
|
|
2070
|
more = 0
|
|
2083
|
more = 0
|
|
2071
|
with nested(self.builtin_trap, self.display_trap):
|
|
2084
|
with nested(self.builtin_trap, self.display_trap):
|
|
2072
|
for line in lines:
|
|
2085
|
for line in lines:
|
|
2073
|
# skip blank lines so we don't mess up the prompt counter, but
|
|
2086
|
# skip blank lines so we don't mess up the prompt counter, but
|
|
2074
|
# do NOT skip even a blank line if we are in a code block (more
|
|
2087
|
# do NOT skip even a blank line if we are in a code block (more
|
|
2075
|
# is true)
|
|
2088
|
# is true)
|
|
2076
|
|
|
2089
|
|
|
2077
|
if line or more:
|
|
2090
|
if line or more:
|
|
2078
|
# push to raw history, so hist line numbers stay in sync
|
|
2091
|
# push to raw history, so hist line numbers stay in sync
|
|
2079
|
self.input_hist_raw.append(line + '\n')
|
|
2092
|
self.input_hist_raw.append(line + '\n')
|
|
2080
|
prefiltered = self.prefilter_manager.prefilter_lines(line,
|
|
2093
|
prefiltered = self.prefilter_manager.prefilter_lines(line,
|
|
2081
|
more)
|
|
2094
|
more)
|
|
2082
|
more = self.push_line(prefiltered)
|
|
2095
|
more = self.push_line(prefiltered)
|
|
2083
|
# IPython's runsource returns None if there was an error
|
|
2096
|
# IPython's runsource returns None if there was an error
|
|
2084
|
# compiling the code. This allows us to stop processing
|
|
2097
|
# compiling the code. This allows us to stop processing
|
|
2085
|
# right away, so the user gets the error message at the
|
|
2098
|
# right away, so the user gets the error message at the
|
|
2086
|
# right place.
|
|
2099
|
# right place.
|
|
2087
|
if more is None:
|
|
2100
|
if more is None:
|
|
2088
|
break
|
|
2101
|
break
|
|
2089
|
else:
|
|
2102
|
else:
|
|
2090
|
self.input_hist_raw.append("\n")
|
|
2103
|
self.input_hist_raw.append("\n")
|
|
2091
|
# final newline in case the input didn't have it, so that the code
|
|
2104
|
# final newline in case the input didn't have it, so that the code
|
|
2092
|
# actually does get executed
|
|
2105
|
# actually does get executed
|
|
2093
|
if more:
|
|
2106
|
if more:
|
|
2094
|
self.push_line('\n')
|
|
2107
|
self.push_line('\n')
|
|
2095
|
|
|
2108
|
|
|
2096
|
def runsource(self, source, filename='<input>', symbol='single'):
|
|
2109
|
def runsource(self, source, filename='<input>', symbol='single'):
|
|
2097
|
"""Compile and run some source in the interpreter.
|
|
2110
|
"""Compile and run some source in the interpreter.
|
|
2098
|
|
|
2111
|
|
|
2099
|
Arguments are as for compile_command().
|
|
2112
|
Arguments are as for compile_command().
|
|
2100
|
|
|
2113
|
|
|
2101
|
One several things can happen:
|
|
2114
|
One several things can happen:
|
|
2102
|
|
|
2115
|
|
|
2103
|
1) The input is incorrect; compile_command() raised an
|
|
2116
|
1) The input is incorrect; compile_command() raised an
|
|
2104
|
exception (SyntaxError or OverflowError). A syntax traceback
|
|
2117
|
exception (SyntaxError or OverflowError). A syntax traceback
|
|
2105
|
will be printed by calling the showsyntaxerror() method.
|
|
2118
|
will be printed by calling the showsyntaxerror() method.
|
|
2106
|
|
|
2119
|
|
|
2107
|
2) The input is incomplete, and more input is required;
|
|
2120
|
2) The input is incomplete, and more input is required;
|
|
2108
|
compile_command() returned None. Nothing happens.
|
|
2121
|
compile_command() returned None. Nothing happens.
|
|
2109
|
|
|
2122
|
|
|
2110
|
3) The input is complete; compile_command() returned a code
|
|
2123
|
3) The input is complete; compile_command() returned a code
|
|
2111
|
object. The code is executed by calling self.runcode() (which
|
|
2124
|
object. The code is executed by calling self.runcode() (which
|
|
2112
|
also handles run-time exceptions, except for SystemExit).
|
|
2125
|
also handles run-time exceptions, except for SystemExit).
|
|
2113
|
|
|
2126
|
|
|
2114
|
The return value is:
|
|
2127
|
The return value is:
|
|
2115
|
|
|
2128
|
|
|
2116
|
- True in case 2
|
|
2129
|
- True in case 2
|
|
2117
|
|
|
2130
|
|
|
2118
|
- False in the other cases, unless an exception is raised, where
|
|
2131
|
- False in the other cases, unless an exception is raised, where
|
|
2119
|
None is returned instead. This can be used by external callers to
|
|
2132
|
None is returned instead. This can be used by external callers to
|
|
2120
|
know whether to continue feeding input or not.
|
|
2133
|
know whether to continue feeding input or not.
|
|
2121
|
|
|
2134
|
|
|
2122
|
The return value can be used to decide whether to use sys.ps1 or
|
|
2135
|
The return value can be used to decide whether to use sys.ps1 or
|
|
2123
|
sys.ps2 to prompt the next line."""
|
|
2136
|
sys.ps2 to prompt the next line."""
|
|
2124
|
|
|
2137
|
|
|
2125
|
# if the source code has leading blanks, add 'if 1:\n' to it
|
|
2138
|
# if the source code has leading blanks, add 'if 1:\n' to it
|
|
2126
|
# this allows execution of indented pasted code. It is tempting
|
|
2139
|
# this allows execution of indented pasted code. It is tempting
|
|
2127
|
# to add '\n' at the end of source to run commands like ' a=1'
|
|
2140
|
# to add '\n' at the end of source to run commands like ' a=1'
|
|
2128
|
# directly, but this fails for more complicated scenarios
|
|
2141
|
# directly, but this fails for more complicated scenarios
|
|
2129
|
source=source.encode(self.stdin_encoding)
|
|
2142
|
source=source.encode(self.stdin_encoding)
|
|
2130
|
if source[:1] in [' ', '\t']:
|
|
2143
|
if source[:1] in [' ', '\t']:
|
|
2131
|
source = 'if 1:\n%s' % source
|
|
2144
|
source = 'if 1:\n%s' % source
|
|
2132
|
|
|
2145
|
|
|
2133
|
try:
|
|
2146
|
try:
|
|
2134
|
code = self.compile(source,filename,symbol)
|
|
2147
|
code = self.compile(source,filename,symbol)
|
|
2135
|
except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
|
|
2148
|
except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
|
|
2136
|
# Case 1
|
|
2149
|
# Case 1
|
|
2137
|
self.showsyntaxerror(filename)
|
|
2150
|
self.showsyntaxerror(filename)
|
|
2138
|
return None
|
|
2151
|
return None
|
|
2139
|
|
|
2152
|
|
|
2140
|
if code is None:
|
|
2153
|
if code is None:
|
|
2141
|
# Case 2
|
|
2154
|
# Case 2
|
|
2142
|
return True
|
|
2155
|
return True
|
|
2143
|
|
|
2156
|
|
|
2144
|
# Case 3
|
|
2157
|
# Case 3
|
|
2145
|
# We store the code object so that threaded shells and
|
|
2158
|
# We store the code object so that threaded shells and
|
|
2146
|
# custom exception handlers can access all this info if needed.
|
|
2159
|
# custom exception handlers can access all this info if needed.
|
|
2147
|
# The source corresponding to this can be obtained from the
|
|
2160
|
# The source corresponding to this can be obtained from the
|
|
2148
|
# buffer attribute as '\n'.join(self.buffer).
|
|
2161
|
# buffer attribute as '\n'.join(self.buffer).
|
|
2149
|
self.code_to_run = code
|
|
2162
|
self.code_to_run = code
|
|
2150
|
# now actually execute the code object
|
|
2163
|
# now actually execute the code object
|
|
2151
|
if self.runcode(code) == 0:
|
|
2164
|
if self.runcode(code) == 0:
|
|
2152
|
return False
|
|
2165
|
return False
|
|
2153
|
else:
|
|
2166
|
else:
|
|
2154
|
return None
|
|
2167
|
return None
|
|
2155
|
|
|
2168
|
|
|
2156
|
def runcode(self,code_obj):
|
|
2169
|
def runcode(self,code_obj):
|
|
2157
|
"""Execute a code object.
|
|
2170
|
"""Execute a code object.
|
|
2158
|
|
|
2171
|
|
|
2159
|
When an exception occurs, self.showtraceback() is called to display a
|
|
2172
|
When an exception occurs, self.showtraceback() is called to display a
|
|
2160
|
traceback.
|
|
2173
|
traceback.
|
|
2161
|
|
|
2174
|
|
|
2162
|
Return value: a flag indicating whether the code to be run completed
|
|
2175
|
Return value: a flag indicating whether the code to be run completed
|
|
2163
|
successfully:
|
|
2176
|
successfully:
|
|
2164
|
|
|
2177
|
|
|
2165
|
- 0: successful execution.
|
|
2178
|
- 0: successful execution.
|
|
2166
|
- 1: an error occurred.
|
|
2179
|
- 1: an error occurred.
|
|
2167
|
"""
|
|
2180
|
"""
|
|
2168
|
|
|
2181
|
|
|
2169
|
# Set our own excepthook in case the user code tries to call it
|
|
2182
|
# Set our own excepthook in case the user code tries to call it
|
|
2170
|
# directly, so that the IPython crash handler doesn't get triggered
|
|
2183
|
# directly, so that the IPython crash handler doesn't get triggered
|
|
2171
|
old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
|
|
2184
|
old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
|
|
2172
|
|
|
2185
|
|
|
2173
|
# we save the original sys.excepthook in the instance, in case config
|
|
2186
|
# we save the original sys.excepthook in the instance, in case config
|
|
2174
|
# code (such as magics) needs access to it.
|
|
2187
|
# code (such as magics) needs access to it.
|
|
2175
|
self.sys_excepthook = old_excepthook
|
|
2188
|
self.sys_excepthook = old_excepthook
|
|
2176
|
outflag = 1 # happens in more places, so it's easier as default
|
|
2189
|
outflag = 1 # happens in more places, so it's easier as default
|
|
2177
|
try:
|
|
2190
|
try:
|
|
2178
|
try:
|
|
2191
|
try:
|
|
2179
|
self.hooks.pre_runcode_hook()
|
|
2192
|
self.hooks.pre_runcode_hook()
|
|
2180
|
#rprint('Running code') # dbg
|
|
2193
|
#rprint('Running code') # dbg
|
|
2181
|
exec code_obj in self.user_global_ns, self.user_ns
|
|
2194
|
exec code_obj in self.user_global_ns, self.user_ns
|
|
2182
|
finally:
|
|
2195
|
finally:
|
|
2183
|
# Reset our crash handler in place
|
|
2196
|
# Reset our crash handler in place
|
|
2184
|
sys.excepthook = old_excepthook
|
|
2197
|
sys.excepthook = old_excepthook
|
|
2185
|
except SystemExit:
|
|
2198
|
except SystemExit:
|
|
2186
|
self.resetbuffer()
|
|
2199
|
self.resetbuffer()
|
|
2187
|
self.showtraceback(exception_only=True)
|
|
2200
|
self.showtraceback(exception_only=True)
|
|
2188
|
warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
|
|
2201
|
warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
|
|
2189
|
except self.custom_exceptions:
|
|
2202
|
except self.custom_exceptions:
|
|
2190
|
etype,value,tb = sys.exc_info()
|
|
2203
|
etype,value,tb = sys.exc_info()
|
|
2191
|
self.CustomTB(etype,value,tb)
|
|
2204
|
self.CustomTB(etype,value,tb)
|
|
2192
|
except:
|
|
2205
|
except:
|
|
2193
|
self.showtraceback()
|
|
2206
|
self.showtraceback()
|
|
2194
|
else:
|
|
2207
|
else:
|
|
2195
|
outflag = 0
|
|
2208
|
outflag = 0
|
|
2196
|
if softspace(sys.stdout, 0):
|
|
2209
|
if softspace(sys.stdout, 0):
|
|
2197
|
print
|
|
2210
|
print
|
|
2198
|
# Flush out code object which has been run (and source)
|
|
2211
|
# Flush out code object which has been run (and source)
|
|
2199
|
self.code_to_run = None
|
|
2212
|
self.code_to_run = None
|
|
2200
|
return outflag
|
|
2213
|
return outflag
|
|
2201
|
|
|
2214
|
|
|
2202
|
def push_line(self, line):
|
|
2215
|
def push_line(self, line):
|
|
2203
|
"""Push a line to the interpreter.
|
|
2216
|
"""Push a line to the interpreter.
|
|
2204
|
|
|
2217
|
|
|
2205
|
The line should not have a trailing newline; it may have
|
|
2218
|
The line should not have a trailing newline; it may have
|
|
2206
|
internal newlines. The line is appended to a buffer and the
|
|
2219
|
internal newlines. The line is appended to a buffer and the
|
|
2207
|
interpreter's runsource() method is called with the
|
|
2220
|
interpreter's runsource() method is called with the
|
|
2208
|
concatenated contents of the buffer as source. If this
|
|
2221
|
concatenated contents of the buffer as source. If this
|
|
2209
|
indicates that the command was executed or invalid, the buffer
|
|
2222
|
indicates that the command was executed or invalid, the buffer
|
|
2210
|
is reset; otherwise, the command is incomplete, and the buffer
|
|
2223
|
is reset; otherwise, the command is incomplete, and the buffer
|
|
2211
|
is left as it was after the line was appended. The return
|
|
2224
|
is left as it was after the line was appended. The return
|
|
2212
|
value is 1 if more input is required, 0 if the line was dealt
|
|
2225
|
value is 1 if more input is required, 0 if the line was dealt
|
|
2213
|
with in some way (this is the same as runsource()).
|
|
2226
|
with in some way (this is the same as runsource()).
|
|
2214
|
"""
|
|
2227
|
"""
|
|
2215
|
|
|
2228
|
|
|
2216
|
# autoindent management should be done here, and not in the
|
|
2229
|
# autoindent management should be done here, and not in the
|
|
2217
|
# interactive loop, since that one is only seen by keyboard input. We
|
|
2230
|
# interactive loop, since that one is only seen by keyboard input. We
|
|
2218
|
# need this done correctly even for code run via runlines (which uses
|
|
2231
|
# need this done correctly even for code run via runlines (which uses
|
|
2219
|
# push).
|
|
2232
|
# push).
|
|
2220
|
|
|
2233
|
|
|
2221
|
#print 'push line: <%s>' % line # dbg
|
|
2234
|
#print 'push line: <%s>' % line # dbg
|
|
2222
|
for subline in line.splitlines():
|
|
2235
|
for subline in line.splitlines():
|
|
2223
|
self._autoindent_update(subline)
|
|
2236
|
self._autoindent_update(subline)
|
|
2224
|
self.buffer.append(line)
|
|
2237
|
self.buffer.append(line)
|
|
2225
|
more = self.runsource('\n'.join(self.buffer), self.filename)
|
|
2238
|
more = self.runsource('\n'.join(self.buffer), self.filename)
|
|
2226
|
if not more:
|
|
2239
|
if not more:
|
|
2227
|
self.resetbuffer()
|
|
2240
|
self.resetbuffer()
|
|
2228
|
return more
|
|
2241
|
return more
|
|
2229
|
|
|
2242
|
|
|
2230
|
def resetbuffer(self):
|
|
2243
|
def resetbuffer(self):
|
|
2231
|
"""Reset the input buffer."""
|
|
2244
|
"""Reset the input buffer."""
|
|
2232
|
self.buffer[:] = []
|
|
2245
|
self.buffer[:] = []
|
|
2233
|
|
|
2246
|
|
|
2234
|
def _is_secondary_block_start(self, s):
|
|
2247
|
def _is_secondary_block_start(self, s):
|
|
2235
|
if not s.endswith(':'):
|
|
2248
|
if not s.endswith(':'):
|
|
2236
|
return False
|
|
2249
|
return False
|
|
2237
|
if (s.startswith('elif') or
|
|
2250
|
if (s.startswith('elif') or
|
|
2238
|
s.startswith('else') or
|
|
2251
|
s.startswith('else') or
|
|
2239
|
s.startswith('except') or
|
|
2252
|
s.startswith('except') or
|
|
2240
|
s.startswith('finally')):
|
|
2253
|
s.startswith('finally')):
|
|
2241
|
return True
|
|
2254
|
return True
|
|
2242
|
|
|
2255
|
|
|
2243
|
def _cleanup_ipy_script(self, script):
|
|
2256
|
def _cleanup_ipy_script(self, script):
|
|
2244
|
"""Make a script safe for self.runlines()
|
|
2257
|
"""Make a script safe for self.runlines()
|
|
2245
|
|
|
2258
|
|
|
2246
|
Currently, IPython is lines based, with blocks being detected by
|
|
2259
|
Currently, IPython is lines based, with blocks being detected by
|
|
2247
|
empty lines. This is a problem for block based scripts that may
|
|
2260
|
empty lines. This is a problem for block based scripts that may
|
|
2248
|
not have empty lines after blocks. This script adds those empty
|
|
2261
|
not have empty lines after blocks. This script adds those empty
|
|
2249
|
lines to make scripts safe for running in the current line based
|
|
2262
|
lines to make scripts safe for running in the current line based
|
|
2250
|
IPython.
|
|
2263
|
IPython.
|
|
2251
|
"""
|
|
2264
|
"""
|
|
2252
|
res = []
|
|
2265
|
res = []
|
|
2253
|
lines = script.splitlines()
|
|
2266
|
lines = script.splitlines()
|
|
2254
|
level = 0
|
|
2267
|
level = 0
|
|
2255
|
|
|
2268
|
|
|
2256
|
for l in lines:
|
|
2269
|
for l in lines:
|
|
2257
|
lstripped = l.lstrip()
|
|
2270
|
lstripped = l.lstrip()
|
|
2258
|
stripped = l.strip()
|
|
2271
|
stripped = l.strip()
|
|
2259
|
if not stripped:
|
|
2272
|
if not stripped:
|
|
2260
|
continue
|
|
2273
|
continue
|
|
2261
|
newlevel = len(l) - len(lstripped)
|
|
2274
|
newlevel = len(l) - len(lstripped)
|
|
2262
|
if level > 0 and newlevel == 0 and \
|
|
2275
|
if level > 0 and newlevel == 0 and \
|
|
2263
|
not self._is_secondary_block_start(stripped):
|
|
2276
|
not self._is_secondary_block_start(stripped):
|
|
2264
|
# add empty line
|
|
2277
|
# add empty line
|
|
2265
|
res.append('')
|
|
2278
|
res.append('')
|
|
2266
|
res.append(l)
|
|
2279
|
res.append(l)
|
|
2267
|
level = newlevel
|
|
2280
|
level = newlevel
|
|
2268
|
|
|
2281
|
|
|
2269
|
return '\n'.join(res) + '\n'
|
|
2282
|
return '\n'.join(res) + '\n'
|
|
2270
|
|
|
2283
|
|
|
2271
|
def _autoindent_update(self,line):
|
|
2284
|
def _autoindent_update(self,line):
|
|
2272
|
"""Keep track of the indent level."""
|
|
2285
|
"""Keep track of the indent level."""
|
|
2273
|
|
|
2286
|
|
|
2274
|
#debugx('line')
|
|
2287
|
#debugx('line')
|
|
2275
|
#debugx('self.indent_current_nsp')
|
|
2288
|
#debugx('self.indent_current_nsp')
|
|
2276
|
if self.autoindent:
|
|
2289
|
if self.autoindent:
|
|
2277
|
if line:
|
|
2290
|
if line:
|
|
2278
|
inisp = num_ini_spaces(line)
|
|
2291
|
inisp = num_ini_spaces(line)
|
|
2279
|
if inisp < self.indent_current_nsp:
|
|
2292
|
if inisp < self.indent_current_nsp:
|
|
2280
|
self.indent_current_nsp = inisp
|
|
2293
|
self.indent_current_nsp = inisp
|
|
2281
|
|
|
2294
|
|
|
2282
|
if line[-1] == ':':
|
|
2295
|
if line[-1] == ':':
|
|
2283
|
self.indent_current_nsp += 4
|
|
2296
|
self.indent_current_nsp += 4
|
|
2284
|
elif dedent_re.match(line):
|
|
2297
|
elif dedent_re.match(line):
|
|
2285
|
self.indent_current_nsp -= 4
|
|
2298
|
self.indent_current_nsp -= 4
|
|
2286
|
else:
|
|
2299
|
else:
|
|
2287
|
self.indent_current_nsp = 0
|
|
2300
|
self.indent_current_nsp = 0
|
|
2288
|
|
|
2301
|
|
|
2289
|
#-------------------------------------------------------------------------
|
|
2302
|
#-------------------------------------------------------------------------
|
|
2290
|
# Things related to GUI support and pylab
|
|
2303
|
# Things related to GUI support and pylab
|
|
2291
|
#-------------------------------------------------------------------------
|
|
2304
|
#-------------------------------------------------------------------------
|
|
2292
|
|
|
2305
|
|
|
2293
|
def enable_pylab(self, gui=None):
|
|
2306
|
def enable_pylab(self, gui=None):
|
|
2294
|
raise NotImplementedError('Implement enable_pylab in a subclass')
|
|
2307
|
raise NotImplementedError('Implement enable_pylab in a subclass')
|
|
2295
|
|
|
2308
|
|
|
2296
|
#-------------------------------------------------------------------------
|
|
2309
|
#-------------------------------------------------------------------------
|
|
2297
|
# Utilities
|
|
2310
|
# Utilities
|
|
2298
|
#-------------------------------------------------------------------------
|
|
2311
|
#-------------------------------------------------------------------------
|
|
2299
|
|
|
2312
|
|
|
2300
|
def var_expand(self,cmd,depth=0):
|
|
2313
|
def var_expand(self,cmd,depth=0):
|
|
2301
|
"""Expand python variables in a string.
|
|
2314
|
"""Expand python variables in a string.
|
|
2302
|
|
|
2315
|
|
|
2303
|
The depth argument indicates how many frames above the caller should
|
|
2316
|
The depth argument indicates how many frames above the caller should
|
|
2304
|
be walked to look for the local namespace where to expand variables.
|
|
2317
|
be walked to look for the local namespace where to expand variables.
|
|
2305
|
|
|
2318
|
|
|
2306
|
The global namespace for expansion is always the user's interactive
|
|
2319
|
The global namespace for expansion is always the user's interactive
|
|
2307
|
namespace.
|
|
2320
|
namespace.
|
|
2308
|
"""
|
|
2321
|
"""
|
|
2309
|
|
|
2322
|
|
|
2310
|
return str(ItplNS(cmd,
|
|
2323
|
return str(ItplNS(cmd,
|
|
2311
|
self.user_ns, # globals
|
|
2324
|
self.user_ns, # globals
|
|
2312
|
# Skip our own frame in searching for locals:
|
|
2325
|
# Skip our own frame in searching for locals:
|
|
2313
|
sys._getframe(depth+1).f_locals # locals
|
|
2326
|
sys._getframe(depth+1).f_locals # locals
|
|
2314
|
))
|
|
2327
|
))
|
|
2315
|
|
|
2328
|
|
|
2316
|
def mktempfile(self,data=None):
|
|
2329
|
def mktempfile(self,data=None):
|
|
2317
|
"""Make a new tempfile and return its filename.
|
|
2330
|
"""Make a new tempfile and return its filename.
|
|
2318
|
|
|
2331
|
|
|
2319
|
This makes a call to tempfile.mktemp, but it registers the created
|
|
2332
|
This makes a call to tempfile.mktemp, but it registers the created
|
|
2320
|
filename internally so ipython cleans it up at exit time.
|
|
2333
|
filename internally so ipython cleans it up at exit time.
|
|
2321
|
|
|
2334
|
|
|
2322
|
Optional inputs:
|
|
2335
|
Optional inputs:
|
|
2323
|
|
|
2336
|
|
|
2324
|
- data(None): if data is given, it gets written out to the temp file
|
|
2337
|
- data(None): if data is given, it gets written out to the temp file
|
|
2325
|
immediately, and the file is closed again."""
|
|
2338
|
immediately, and the file is closed again."""
|
|
2326
|
|
|
2339
|
|
|
2327
|
filename = tempfile.mktemp('.py','ipython_edit_')
|
|
2340
|
filename = tempfile.mktemp('.py','ipython_edit_')
|
|
2328
|
self.tempfiles.append(filename)
|
|
2341
|
self.tempfiles.append(filename)
|
|
2329
|
|
|
2342
|
|
|
2330
|
if data:
|
|
2343
|
if data:
|
|
2331
|
tmp_file = open(filename,'w')
|
|
2344
|
tmp_file = open(filename,'w')
|
|
2332
|
tmp_file.write(data)
|
|
2345
|
tmp_file.write(data)
|
|
2333
|
tmp_file.close()
|
|
2346
|
tmp_file.close()
|
|
2334
|
return filename
|
|
2347
|
return filename
|
|
2335
|
|
|
2348
|
|
|
2336
|
# TODO: This should be removed when Term is refactored.
|
|
2349
|
# TODO: This should be removed when Term is refactored.
|
|
2337
|
def write(self,data):
|
|
2350
|
def write(self,data):
|
|
2338
|
"""Write a string to the default output"""
|
|
2351
|
"""Write a string to the default output"""
|
|
2339
|
io.Term.cout.write(data)
|
|
2352
|
io.Term.cout.write(data)
|
|
2340
|
|
|
2353
|
|
|
2341
|
# TODO: This should be removed when Term is refactored.
|
|
2354
|
# TODO: This should be removed when Term is refactored.
|
|
2342
|
def write_err(self,data):
|
|
2355
|
def write_err(self,data):
|
|
2343
|
"""Write a string to the default error output"""
|
|
2356
|
"""Write a string to the default error output"""
|
|
2344
|
io.Term.cerr.write(data)
|
|
2357
|
io.Term.cerr.write(data)
|
|
2345
|
|
|
2358
|
|
|
2346
|
def ask_yes_no(self,prompt,default=True):
|
|
2359
|
def ask_yes_no(self,prompt,default=True):
|
|
2347
|
if self.quiet:
|
|
2360
|
if self.quiet:
|
|
2348
|
return True
|
|
2361
|
return True
|
|
2349
|
return ask_yes_no(prompt,default)
|
|
2362
|
return ask_yes_no(prompt,default)
|
|
2350
|
|
|
2363
|
|
|
2351
|
def show_usage(self):
|
|
2364
|
def show_usage(self):
|
|
2352
|
"""Show a usage message"""
|
|
2365
|
"""Show a usage message"""
|
|
2353
|
page.page(IPython.core.usage.interactive_usage)
|
|
2366
|
page.page(IPython.core.usage.interactive_usage)
|
|
2354
|
|
|
2367
|
|
|
2355
|
#-------------------------------------------------------------------------
|
|
2368
|
#-------------------------------------------------------------------------
|
|
2356
|
# Things related to IPython exiting
|
|
2369
|
# Things related to IPython exiting
|
|
2357
|
#-------------------------------------------------------------------------
|
|
2370
|
#-------------------------------------------------------------------------
|
|
2358
|
def atexit_operations(self):
|
|
2371
|
def atexit_operations(self):
|
|
2359
|
"""This will be executed at the time of exit.
|
|
2372
|
"""This will be executed at the time of exit.
|
|
2360
|
|
|
2373
|
|
|
2361
|
Cleanup operations and saving of persistent data that is done
|
|
2374
|
Cleanup operations and saving of persistent data that is done
|
|
2362
|
unconditionally by IPython should be performed here.
|
|
2375
|
unconditionally by IPython should be performed here.
|
|
2363
|
|
|
2376
|
|
|
2364
|
For things that may depend on startup flags or platform specifics (such
|
|
2377
|
For things that may depend on startup flags or platform specifics (such
|
|
2365
|
as having readline or not), register a separate atexit function in the
|
|
2378
|
as having readline or not), register a separate atexit function in the
|
|
2366
|
code that has the appropriate information, rather than trying to
|
|
2379
|
code that has the appropriate information, rather than trying to
|
|
2367
|
clutter
|
|
2380
|
clutter
|
|
2368
|
"""
|
|
2381
|
"""
|
|
2369
|
# Cleanup all tempfiles left around
|
|
2382
|
# Cleanup all tempfiles left around
|
|
2370
|
for tfile in self.tempfiles:
|
|
2383
|
for tfile in self.tempfiles:
|
|
2371
|
try:
|
|
2384
|
try:
|
|
2372
|
os.unlink(tfile)
|
|
2385
|
os.unlink(tfile)
|
|
2373
|
except OSError:
|
|
2386
|
except OSError:
|
|
2374
|
pass
|
|
2387
|
pass
|
|
2375
|
|
|
2388
|
|
|
2376
|
# Clear all user namespaces to release all references cleanly.
|
|
2389
|
# Clear all user namespaces to release all references cleanly.
|
|
2377
|
self.reset()
|
|
2390
|
self.reset()
|
|
2378
|
|
|
2391
|
|
|
2379
|
# Run user hooks
|
|
2392
|
# Run user hooks
|
|
2380
|
self.hooks.shutdown_hook()
|
|
2393
|
self.hooks.shutdown_hook()
|
|
2381
|
|
|
2394
|
|
|
2382
|
def cleanup(self):
|
|
2395
|
def cleanup(self):
|
|
2383
|
self.restore_sys_module_state()
|
|
2396
|
self.restore_sys_module_state()
|
|
2384
|
|
|
2397
|
|
|
2385
|
|
|
2398
|
|
|
2386
|
class InteractiveShellABC(object):
|
|
2399
|
class InteractiveShellABC(object):
|
|
2387
|
"""An abstract base class for InteractiveShell."""
|
|
2400
|
"""An abstract base class for InteractiveShell."""
|
|
2388
|
__metaclass__ = abc.ABCMeta
|
|
2401
|
__metaclass__ = abc.ABCMeta
|
|
2389
|
|
|
2402
|
|
|
2390
|
InteractiveShellABC.register(InteractiveShell)
|
|
2403
|
InteractiveShellABC.register(InteractiveShell)
|