This diff has been collapsed as it changes many lines, (512 lines changed)
Show them
Hide them
|
|
@@
-1,2157
+1,1887
b''
|
|
1
|
# -*- coding: utf-8 -*-
|
|
1
|
# -*- coding: utf-8 -*-
|
|
2
|
"""
|
|
2
|
"""
|
|
3
|
IPython -- An enhanced Interactive Python
|
|
3
|
IPython -- An enhanced Interactive Python
|
|
4
|
|
|
4
|
|
|
5
|
Requires Python 2.1 or newer.
|
|
5
|
Requires Python 2.1 or newer.
|
|
6
|
|
|
6
|
|
|
7
|
This file contains all the classes and helper functions specific to IPython.
|
|
7
|
This file contains all the classes and helper functions specific to IPython.
|
|
8
|
|
|
8
|
|
|
9
|
$Id: iplib.py 955 2005-12-27 07:50:29Z fperez $
|
|
9
|
$Id: iplib.py 957 2005-12-27 22:33:22Z fperez $
|
|
10
|
"""
|
|
10
|
"""
|
|
11
|
|
|
11
|
|
|
12
|
#*****************************************************************************
|
|
12
|
#*****************************************************************************
|
|
13
|
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
|
|
13
|
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
|
|
14
|
# Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
|
|
14
|
# Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
|
|
15
|
#
|
|
15
|
#
|
|
16
|
# Distributed under the terms of the BSD License. The full license is in
|
|
16
|
# Distributed under the terms of the BSD License. The full license is in
|
|
17
|
# the file COPYING, distributed as part of this software.
|
|
17
|
# the file COPYING, distributed as part of this software.
|
|
18
|
#
|
|
18
|
#
|
|
19
|
# Note: this code originally subclassed code.InteractiveConsole from the
|
|
19
|
# Note: this code originally subclassed code.InteractiveConsole from the
|
|
20
|
# Python standard library. Over time, much of that class has been copied
|
|
20
|
# Python standard library. Over time, all of that class has been copied
|
|
21
|
# verbatim here for modifications which could not be accomplished by
|
|
21
|
# verbatim here for modifications which could not be accomplished by
|
|
22
|
# subclassing. The Python License (sec. 2) allows for this, but it's always
|
|
22
|
# subclassing. At this point, there are no dependencies at all on the code
|
|
23
|
# nice to acknowledge credit where credit is due.
|
|
23
|
# module anymore (it is not even imported). The Python License (sec. 2)
|
|
|
|
|
24
|
# allows for this, but it's always nice to acknowledge credit where credit is
|
|
|
|
|
25
|
# due.
|
|
24
|
#*****************************************************************************
|
|
26
|
#*****************************************************************************
|
|
25
|
|
|
27
|
|
|
26
|
#****************************************************************************
|
|
28
|
#****************************************************************************
|
|
27
|
# Modules and globals
|
|
29
|
# Modules and globals
|
|
28
|
|
|
30
|
|
|
29
|
from __future__ import generators # for 2.2 backwards-compatibility
|
|
31
|
from __future__ import generators # for 2.2 backwards-compatibility
|
|
30
|
|
|
32
|
|
|
31
|
from IPython import Release
|
|
33
|
from IPython import Release
|
|
32
|
__author__ = '%s <%s>\n%s <%s>' % \
|
|
34
|
__author__ = '%s <%s>\n%s <%s>' % \
|
|
33
|
( Release.authors['Janko'] + Release.authors['Fernando'] )
|
|
35
|
( Release.authors['Janko'] + Release.authors['Fernando'] )
|
|
34
|
__license__ = Release.license
|
|
36
|
__license__ = Release.license
|
|
35
|
__version__ = Release.version
|
|
37
|
__version__ = Release.version
|
|
36
|
|
|
38
|
|
|
37
|
# Python standard modules
|
|
39
|
# Python standard modules
|
|
38
|
import __main__
|
|
40
|
import __main__
|
|
39
|
import __builtin__
|
|
41
|
import __builtin__
|
|
|
|
|
42
|
import bdb
|
|
|
|
|
43
|
import codeop
|
|
|
|
|
44
|
import cPickle as pickle
|
|
40
|
import exceptions
|
|
45
|
import exceptions
|
|
|
|
|
46
|
import glob
|
|
|
|
|
47
|
import inspect
|
|
41
|
import keyword
|
|
48
|
import keyword
|
|
42
|
import new
|
|
49
|
import new
|
|
43
|
import os, sys, shutil
|
|
50
|
import os
|
|
44
|
import code, glob, types, re
|
|
51
|
import pdb
|
|
45
|
import string, StringIO
|
|
52
|
import pydoc
|
|
46
|
import inspect, pydoc
|
|
53
|
import re
|
|
47
|
import bdb, pdb
|
|
54
|
import shutil
|
|
48
|
import UserList # don't subclass list so this works with Python2.1
|
|
55
|
import string
|
|
49
|
from pprint import pprint, pformat
|
|
56
|
import StringIO
|
|
50
|
import cPickle as pickle
|
|
57
|
import sys
|
|
51
|
import traceback
|
|
58
|
import traceback
|
|
52
|
from codeop import CommandCompiler
|
|
59
|
import types
|
|
|
|
|
60
|
|
|
|
|
|
61
|
from pprint import pprint, pformat
|
|
53
|
|
|
62
|
|
|
54
|
# IPython's own modules
|
|
63
|
# IPython's own modules
|
|
55
|
import IPython
|
|
64
|
import IPython
|
|
56
|
from IPython import OInspect,PyColorize,ultraTB
|
|
65
|
from IPython import OInspect,PyColorize,ultraTB
|
|
57
|
from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
|
|
66
|
from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
|
|
58
|
from IPython.Logger import Logger
|
|
67
|
from IPython.Logger import Logger
|
|
59
|
from IPython.Magic import Magic,magic2python,shlex_split
|
|
68
|
from IPython.Magic import Magic,magic2python
|
|
60
|
from IPython.usage import cmd_line_usage,interactive_usage
|
|
69
|
from IPython.usage import cmd_line_usage,interactive_usage
|
|
61
|
from IPython.Struct import Struct
|
|
70
|
from IPython.Struct import Struct
|
|
62
|
from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
|
|
71
|
from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
|
|
63
|
from IPython.FakeModule import FakeModule
|
|
72
|
from IPython.FakeModule import FakeModule
|
|
64
|
from IPython.background_jobs import BackgroundJobManager
|
|
73
|
from IPython.background_jobs import BackgroundJobManager
|
|
65
|
from IPython.PyColorize import Parser
|
|
74
|
from IPython.PyColorize import Parser
|
|
66
|
from IPython.genutils import *
|
|
75
|
from IPython.genutils import *
|
|
67
|
|
|
76
|
|
|
68
|
# Global pointer to the running
|
|
77
|
# Global pointer to the running
|
|
69
|
|
|
78
|
|
|
70
|
# store the builtin raw_input globally, and use this always, in case user code
|
|
79
|
# store the builtin raw_input globally, and use this always, in case user code
|
|
71
|
# overwrites it (like wx.py.PyShell does)
|
|
80
|
# overwrites it (like wx.py.PyShell does)
|
|
72
|
raw_input_original = raw_input
|
|
81
|
raw_input_original = raw_input
|
|
73
|
|
|
82
|
|
|
74
|
#****************************************************************************
|
|
83
|
#****************************************************************************
|
|
75
|
# Some utility function definitions
|
|
84
|
# Some utility function definitions
|
|
76
|
|
|
85
|
|
|
77
|
class Bunch: pass
|
|
|
|
|
78
|
|
|
|
|
|
79
|
def esc_quotes(strng):
|
|
86
|
def esc_quotes(strng):
|
|
80
|
"""Return the input string with single and double quotes escaped out"""
|
|
87
|
"""Return the input string with single and double quotes escaped out"""
|
|
81
|
|
|
88
|
|
|
82
|
return strng.replace('"','\\"').replace("'","\\'")
|
|
89
|
return strng.replace('"','\\"').replace("'","\\'")
|
|
83
|
|
|
90
|
|
|
84
|
def import_fail_info(mod_name,fns=None):
|
|
91
|
def import_fail_info(mod_name,fns=None):
|
|
85
|
"""Inform load failure for a module."""
|
|
92
|
"""Inform load failure for a module."""
|
|
86
|
|
|
93
|
|
|
87
|
if fns == None:
|
|
94
|
if fns == None:
|
|
88
|
warn("Loading of %s failed.\n" % (mod_name,))
|
|
95
|
warn("Loading of %s failed.\n" % (mod_name,))
|
|
89
|
else:
|
|
96
|
else:
|
|
90
|
warn("Loading of %s from %s failed.\n" % (fns,mod_name))
|
|
97
|
warn("Loading of %s from %s failed.\n" % (fns,mod_name))
|
|
91
|
|
|
98
|
|
|
92
|
def qw_lol(indata):
|
|
99
|
def qw_lol(indata):
|
|
93
|
"""qw_lol('a b') -> [['a','b']],
|
|
100
|
"""qw_lol('a b') -> [['a','b']],
|
|
94
|
otherwise it's just a call to qw().
|
|
101
|
otherwise it's just a call to qw().
|
|
95
|
|
|
102
|
|
|
96
|
We need this to make sure the modules_some keys *always* end up as a
|
|
103
|
We need this to make sure the modules_some keys *always* end up as a
|
|
97
|
list of lists."""
|
|
104
|
list of lists."""
|
|
98
|
|
|
105
|
|
|
99
|
if type(indata) in StringTypes:
|
|
106
|
if type(indata) in StringTypes:
|
|
100
|
return [qw(indata)]
|
|
107
|
return [qw(indata)]
|
|
101
|
else:
|
|
108
|
else:
|
|
102
|
return qw(indata)
|
|
109
|
return qw(indata)
|
|
103
|
|
|
110
|
|
|
104
|
def ipmagic(arg_s):
|
|
111
|
def ipmagic(arg_s):
|
|
105
|
"""Call a magic function by name.
|
|
112
|
"""Call a magic function by name.
|
|
106
|
|
|
113
|
|
|
107
|
Input: a string containing the name of the magic function to call and any
|
|
114
|
Input: a string containing the name of the magic function to call and any
|
|
108
|
additional arguments to be passed to the magic.
|
|
115
|
additional arguments to be passed to the magic.
|
|
109
|
|
|
116
|
|
|
110
|
ipmagic('name -opt foo bar') is equivalent to typing at the ipython
|
|
117
|
ipmagic('name -opt foo bar') is equivalent to typing at the ipython
|
|
111
|
prompt:
|
|
118
|
prompt:
|
|
112
|
|
|
119
|
|
|
113
|
In[1]: %name -opt foo bar
|
|
120
|
In[1]: %name -opt foo bar
|
|
114
|
|
|
121
|
|
|
115
|
To call a magic without arguments, simply use ipmagic('name').
|
|
122
|
To call a magic without arguments, simply use ipmagic('name').
|
|
116
|
|
|
123
|
|
|
117
|
This provides a proper Python function to call IPython's magics in any
|
|
124
|
This provides a proper Python function to call IPython's magics in any
|
|
118
|
valid Python code you can type at the interpreter, including loops and
|
|
125
|
valid Python code you can type at the interpreter, including loops and
|
|
119
|
compound statements. It is added by IPython to the Python builtin
|
|
126
|
compound statements. It is added by IPython to the Python builtin
|
|
120
|
namespace upon initialization."""
|
|
127
|
namespace upon initialization."""
|
|
121
|
|
|
128
|
|
|
122
|
args = arg_s.split(' ',1)
|
|
129
|
args = arg_s.split(' ',1)
|
|
123
|
magic_name = args[0]
|
|
130
|
magic_name = args[0]
|
|
124
|
if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
|
|
131
|
if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
|
|
125
|
magic_name = magic_name[1:]
|
|
132
|
magic_name = magic_name[1:]
|
|
126
|
try:
|
|
133
|
try:
|
|
127
|
magic_args = args[1]
|
|
134
|
magic_args = args[1]
|
|
128
|
except IndexError:
|
|
135
|
except IndexError:
|
|
129
|
magic_args = ''
|
|
136
|
magic_args = ''
|
|
130
|
fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
|
|
137
|
fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
|
|
131
|
if fn is None:
|
|
138
|
if fn is None:
|
|
132
|
error("Magic function `%s` not found." % magic_name)
|
|
139
|
error("Magic function `%s` not found." % magic_name)
|
|
133
|
else:
|
|
140
|
else:
|
|
134
|
magic_args = __IPYTHON__.var_expand(magic_args)
|
|
141
|
magic_args = __IPYTHON__.var_expand(magic_args)
|
|
135
|
return fn(magic_args)
|
|
142
|
return fn(magic_args)
|
|
136
|
|
|
143
|
|
|
137
|
def ipalias(arg_s):
|
|
144
|
def ipalias(arg_s):
|
|
138
|
"""Call an alias by name.
|
|
145
|
"""Call an alias by name.
|
|
139
|
|
|
146
|
|
|
140
|
Input: a string containing the name of the alias to call and any
|
|
147
|
Input: a string containing the name of the alias to call and any
|
|
141
|
additional arguments to be passed to the magic.
|
|
148
|
additional arguments to be passed to the magic.
|
|
142
|
|
|
149
|
|
|
143
|
ipalias('name -opt foo bar') is equivalent to typing at the ipython
|
|
150
|
ipalias('name -opt foo bar') is equivalent to typing at the ipython
|
|
144
|
prompt:
|
|
151
|
prompt:
|
|
145
|
|
|
152
|
|
|
146
|
In[1]: name -opt foo bar
|
|
153
|
In[1]: name -opt foo bar
|
|
147
|
|
|
154
|
|
|
148
|
To call an alias without arguments, simply use ipalias('name').
|
|
155
|
To call an alias without arguments, simply use ipalias('name').
|
|
149
|
|
|
156
|
|
|
150
|
This provides a proper Python function to call IPython's aliases in any
|
|
157
|
This provides a proper Python function to call IPython's aliases in any
|
|
151
|
valid Python code you can type at the interpreter, including loops and
|
|
158
|
valid Python code you can type at the interpreter, including loops and
|
|
152
|
compound statements. It is added by IPython to the Python builtin
|
|
159
|
compound statements. It is added by IPython to the Python builtin
|
|
153
|
namespace upon initialization."""
|
|
160
|
namespace upon initialization."""
|
|
154
|
|
|
161
|
|
|
155
|
args = arg_s.split(' ',1)
|
|
162
|
args = arg_s.split(' ',1)
|
|
156
|
alias_name = args[0]
|
|
163
|
alias_name = args[0]
|
|
157
|
try:
|
|
164
|
try:
|
|
158
|
alias_args = args[1]
|
|
165
|
alias_args = args[1]
|
|
159
|
except IndexError:
|
|
166
|
except IndexError:
|
|
160
|
alias_args = ''
|
|
167
|
alias_args = ''
|
|
161
|
if alias_name in __IPYTHON__.alias_table:
|
|
168
|
if alias_name in __IPYTHON__.alias_table:
|
|
162
|
__IPYTHON__.call_alias(alias_name,alias_args)
|
|
169
|
__IPYTHON__.call_alias(alias_name,alias_args)
|
|
163
|
else:
|
|
170
|
else:
|
|
164
|
error("Alias `%s` not found." % alias_name)
|
|
171
|
error("Alias `%s` not found." % alias_name)
|
|
165
|
|
|
172
|
|
|
166
|
#-----------------------------------------------------------------------------
|
|
173
|
def softspace(file, newvalue):
|
|
167
|
# Local use classes
|
|
174
|
"""Copied from code.py, to remove the dependency"""
|
|
168
|
try:
|
|
175
|
oldvalue = 0
|
|
169
|
from IPython import FlexCompleter
|
|
|
|
|
170
|
|
|
|
|
|
171
|
class MagicCompleter(FlexCompleter.Completer):
|
|
|
|
|
172
|
"""Extension of the completer class to work on %-prefixed lines."""
|
|
|
|
|
173
|
|
|
|
|
|
174
|
def __init__(self,shell,namespace=None,global_namespace=None,
|
|
|
|
|
175
|
omit__names=0,alias_table=None):
|
|
|
|
|
176
|
"""MagicCompleter() -> completer
|
|
|
|
|
177
|
|
|
|
|
|
178
|
Return a completer object suitable for use by the readline library
|
|
|
|
|
179
|
via readline.set_completer().
|
|
|
|
|
180
|
|
|
|
|
|
181
|
Inputs:
|
|
|
|
|
182
|
|
|
|
|
|
183
|
- shell: a pointer to the ipython shell itself. This is needed
|
|
|
|
|
184
|
because this completer knows about magic functions, and those can
|
|
|
|
|
185
|
only be accessed via the ipython instance.
|
|
|
|
|
186
|
|
|
|
|
|
187
|
- namespace: an optional dict where completions are performed.
|
|
|
|
|
188
|
|
|
|
|
|
189
|
- global_namespace: secondary optional dict for completions, to
|
|
|
|
|
190
|
handle cases (such as IPython embedded inside functions) where
|
|
|
|
|
191
|
both Python scopes are visible.
|
|
|
|
|
192
|
|
|
|
|
|
193
|
- The optional omit__names parameter sets the completer to omit the
|
|
|
|
|
194
|
'magic' names (__magicname__) for python objects unless the text
|
|
|
|
|
195
|
to be completed explicitly starts with one or more underscores.
|
|
|
|
|
196
|
|
|
|
|
|
197
|
- If alias_table is supplied, it should be a dictionary of aliases
|
|
|
|
|
198
|
to complete. """
|
|
|
|
|
199
|
|
|
|
|
|
200
|
FlexCompleter.Completer.__init__(self,namespace)
|
|
|
|
|
201
|
self.magic_prefix = shell.name+'.magic_'
|
|
|
|
|
202
|
self.magic_escape = shell.ESC_MAGIC
|
|
|
|
|
203
|
self.readline = FlexCompleter.readline
|
|
|
|
|
204
|
delims = self.readline.get_completer_delims()
|
|
|
|
|
205
|
delims = delims.replace(self.magic_escape,'')
|
|
|
|
|
206
|
self.readline.set_completer_delims(delims)
|
|
|
|
|
207
|
self.get_line_buffer = self.readline.get_line_buffer
|
|
|
|
|
208
|
self.omit__names = omit__names
|
|
|
|
|
209
|
self.merge_completions = shell.rc.readline_merge_completions
|
|
|
|
|
210
|
|
|
|
|
|
211
|
if alias_table is None:
|
|
|
|
|
212
|
alias_table = {}
|
|
|
|
|
213
|
self.alias_table = alias_table
|
|
|
|
|
214
|
# Regexp to split filenames with spaces in them
|
|
|
|
|
215
|
self.space_name_re = re.compile(r'([^\\] )')
|
|
|
|
|
216
|
# Hold a local ref. to glob.glob for speed
|
|
|
|
|
217
|
self.glob = glob.glob
|
|
|
|
|
218
|
# Special handling of backslashes needed in win32 platforms
|
|
|
|
|
219
|
if sys.platform == "win32":
|
|
|
|
|
220
|
self.clean_glob = self._clean_glob_win32
|
|
|
|
|
221
|
else:
|
|
|
|
|
222
|
self.clean_glob = self._clean_glob
|
|
|
|
|
223
|
self.matchers = [self.python_matches,
|
|
|
|
|
224
|
self.file_matches,
|
|
|
|
|
225
|
self.alias_matches,
|
|
|
|
|
226
|
self.python_func_kw_matches]
|
|
|
|
|
227
|
|
|
|
|
|
228
|
# Code contributed by Alex Schmolck, for ipython/emacs integration
|
|
|
|
|
229
|
def all_completions(self, text):
|
|
|
|
|
230
|
"""Return all possible completions for the benefit of emacs."""
|
|
|
|
|
231
|
|
|
|
|
|
232
|
completions = []
|
|
|
|
|
233
|
comp_append = completions.append
|
|
|
|
|
234
|
try:
|
|
|
|
|
235
|
for i in xrange(sys.maxint):
|
|
|
|
|
236
|
res = self.complete(text, i)
|
|
|
|
|
237
|
|
|
|
|
|
238
|
if not res: break
|
|
|
|
|
239
|
|
|
|
|
|
240
|
comp_append(res)
|
|
|
|
|
241
|
#XXX workaround for ``notDefined.<tab>``
|
|
|
|
|
242
|
except NameError:
|
|
|
|
|
243
|
pass
|
|
|
|
|
244
|
return completions
|
|
|
|
|
245
|
# /end Alex Schmolck code.
|
|
|
|
|
246
|
|
|
|
|
|
247
|
def _clean_glob(self,text):
|
|
|
|
|
248
|
return self.glob("%s*" % text)
|
|
|
|
|
249
|
|
|
|
|
|
250
|
def _clean_glob_win32(self,text):
|
|
|
|
|
251
|
return [f.replace("\\","/")
|
|
|
|
|
252
|
for f in self.glob("%s*" % text)]
|
|
|
|
|
253
|
|
|
|
|
|
254
|
def file_matches(self, text):
|
|
|
|
|
255
|
"""Match filneames, expanding ~USER type strings.
|
|
|
|
|
256
|
|
|
|
|
|
257
|
Most of the seemingly convoluted logic in this completer is an
|
|
|
|
|
258
|
attempt to handle filenames with spaces in them. And yet it's not
|
|
|
|
|
259
|
quite perfect, because Python's readline doesn't expose all of the
|
|
|
|
|
260
|
GNU readline details needed for this to be done correctly.
|
|
|
|
|
261
|
|
|
|
|
|
262
|
For a filename with a space in it, the printed completions will be
|
|
|
|
|
263
|
only the parts after what's already been typed (instead of the
|
|
|
|
|
264
|
full completions, as is normally done). I don't think with the
|
|
|
|
|
265
|
current (as of Python 2.3) Python readline it's possible to do
|
|
|
|
|
266
|
better."""
|
|
|
|
|
267
|
|
|
|
|
|
268
|
#print 'Completer->file_matches: <%s>' % text # dbg
|
|
|
|
|
269
|
|
|
|
|
|
270
|
# chars that require escaping with backslash - i.e. chars
|
|
|
|
|
271
|
# that readline treats incorrectly as delimiters, but we
|
|
|
|
|
272
|
# don't want to treat as delimiters in filename matching
|
|
|
|
|
273
|
# when escaped with backslash
|
|
|
|
|
274
|
|
|
|
|
|
275
|
protectables = ' ()[]{}'
|
|
|
|
|
276
|
|
|
|
|
|
277
|
def protect_filename(s):
|
|
|
|
|
278
|
return "".join([(ch in protectables and '\\' + ch or ch)
|
|
|
|
|
279
|
for ch in s])
|
|
|
|
|
280
|
|
|
|
|
|
281
|
lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
|
|
|
|
|
282
|
open_quotes = 0 # track strings with open quotes
|
|
|
|
|
283
|
try:
|
|
|
|
|
284
|
lsplit = shlex_split(lbuf)[-1]
|
|
|
|
|
285
|
except ValueError:
|
|
|
|
|
286
|
# typically an unmatched ", or backslash without escaped char.
|
|
|
|
|
287
|
if lbuf.count('"')==1:
|
|
|
|
|
288
|
open_quotes = 1
|
|
|
|
|
289
|
lsplit = lbuf.split('"')[-1]
|
|
|
|
|
290
|
elif lbuf.count("'")==1:
|
|
|
|
|
291
|
open_quotes = 1
|
|
|
|
|
292
|
lsplit = lbuf.split("'")[-1]
|
|
|
|
|
293
|
else:
|
|
|
|
|
294
|
return None
|
|
|
|
|
295
|
except IndexError:
|
|
|
|
|
296
|
# tab pressed on empty line
|
|
|
|
|
297
|
lsplit = ""
|
|
|
|
|
298
|
|
|
|
|
|
299
|
if lsplit != protect_filename(lsplit):
|
|
|
|
|
300
|
# if protectables are found, do matching on the whole escaped
|
|
|
|
|
301
|
# name
|
|
|
|
|
302
|
has_protectables = 1
|
|
|
|
|
303
|
text0,text = text,lsplit
|
|
|
|
|
304
|
else:
|
|
|
|
|
305
|
has_protectables = 0
|
|
|
|
|
306
|
text = os.path.expanduser(text)
|
|
|
|
|
307
|
|
|
|
|
|
308
|
if text == "":
|
|
|
|
|
309
|
return [protect_filename(f) for f in self.glob("*")]
|
|
|
|
|
310
|
|
|
|
|
|
311
|
m0 = self.clean_glob(text.replace('\\',''))
|
|
|
|
|
312
|
if has_protectables:
|
|
|
|
|
313
|
# If we had protectables, we need to revert our changes to the
|
|
|
|
|
314
|
# beginning of filename so that we don't double-write the part
|
|
|
|
|
315
|
# of the filename we have so far
|
|
|
|
|
316
|
len_lsplit = len(lsplit)
|
|
|
|
|
317
|
matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
|
|
|
|
|
318
|
else:
|
|
|
|
|
319
|
if open_quotes:
|
|
|
|
|
320
|
# if we have a string with an open quote, we don't need to
|
|
|
|
|
321
|
# protect the names at all (and we _shouldn't_, as it
|
|
|
|
|
322
|
# would cause bugs when the filesystem call is made).
|
|
|
|
|
323
|
matches = m0
|
|
|
|
|
324
|
else:
|
|
|
|
|
325
|
matches = [protect_filename(f) for f in m0]
|
|
|
|
|
326
|
if len(matches) == 1 and os.path.isdir(matches[0]):
|
|
|
|
|
327
|
# Takes care of links to directories also. Use '/'
|
|
|
|
|
328
|
# explicitly, even under Windows, so that name completions
|
|
|
|
|
329
|
# don't end up escaped.
|
|
|
|
|
330
|
matches[0] += '/'
|
|
|
|
|
331
|
return matches
|
|
|
|
|
332
|
|
|
|
|
|
333
|
def alias_matches(self, text):
|
|
|
|
|
334
|
"""Match internal system aliases"""
|
|
|
|
|
335
|
#print 'Completer->alias_matches:',text # dbg
|
|
|
|
|
336
|
text = os.path.expanduser(text)
|
|
|
|
|
337
|
aliases = self.alias_table.keys()
|
|
|
|
|
338
|
if text == "":
|
|
|
|
|
339
|
return aliases
|
|
|
|
|
340
|
else:
|
|
|
|
|
341
|
return [alias for alias in aliases if alias.startswith(text)]
|
|
|
|
|
342
|
|
|
|
|
|
343
|
def python_matches(self,text):
|
|
|
|
|
344
|
"""Match attributes or global python names"""
|
|
|
|
|
345
|
#print 'Completer->python_matches' # dbg
|
|
|
|
|
346
|
if "." in text:
|
|
|
|
|
347
|
try:
|
|
176
|
try:
|
|
348
|
matches = self.attr_matches(text)
|
|
177
|
oldvalue = file.softspace
|
|
349
|
if text.endswith('.') and self.omit__names:
|
|
|
|
|
350
|
if self.omit__names == 1:
|
|
|
|
|
351
|
# true if txt is _not_ a __ name, false otherwise:
|
|
|
|
|
352
|
no__name = (lambda txt:
|
|
|
|
|
353
|
re.match(r'.*\.__.*?__',txt) is None)
|
|
|
|
|
354
|
else:
|
|
|
|
|
355
|
# true if txt is _not_ a _ name, false otherwise:
|
|
|
|
|
356
|
no__name = (lambda txt:
|
|
|
|
|
357
|
re.match(r'.*\._.*?',txt) is None)
|
|
|
|
|
358
|
matches = filter(no__name, matches)
|
|
|
|
|
359
|
except NameError:
|
|
|
|
|
360
|
# catches <undefined attributes>.<tab>
|
|
|
|
|
361
|
matches = []
|
|
|
|
|
362
|
else:
|
|
|
|
|
363
|
matches = self.global_matches(text)
|
|
|
|
|
364
|
# this is so completion finds magics when automagic is on:
|
|
|
|
|
365
|
if matches == [] and not text.startswith(os.sep):
|
|
|
|
|
366
|
matches = self.attr_matches(self.magic_prefix+text)
|
|
|
|
|
367
|
return matches
|
|
|
|
|
368
|
|
|
|
|
|
369
|
def _default_arguments(self, obj):
|
|
|
|
|
370
|
"""Return the list of default arguments of obj if it is callable,
|
|
|
|
|
371
|
or empty list otherwise."""
|
|
|
|
|
372
|
|
|
|
|
|
373
|
if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
|
|
|
|
|
374
|
# for classes, check for __init__,__new__
|
|
|
|
|
375
|
if inspect.isclass(obj):
|
|
|
|
|
376
|
obj = (getattr(obj,'__init__',None) or
|
|
|
|
|
377
|
getattr(obj,'__new__',None))
|
|
|
|
|
378
|
# for all others, check if they are __call__able
|
|
|
|
|
379
|
elif hasattr(obj, '__call__'):
|
|
|
|
|
380
|
obj = obj.__call__
|
|
|
|
|
381
|
# XXX: is there a way to handle the builtins ?
|
|
|
|
|
382
|
try:
|
|
|
|
|
383
|
args,_,_1,defaults = inspect.getargspec(obj)
|
|
|
|
|
384
|
if defaults:
|
|
|
|
|
385
|
return args[-len(defaults):]
|
|
|
|
|
386
|
except TypeError: pass
|
|
|
|
|
387
|
return []
|
|
|
|
|
388
|
|
|
|
|
|
389
|
def python_func_kw_matches(self,text):
|
|
|
|
|
390
|
"""Match named parameters (kwargs) of the last open function"""
|
|
|
|
|
391
|
|
|
|
|
|
392
|
if "." in text: # a parameter cannot be dotted
|
|
|
|
|
393
|
return []
|
|
|
|
|
394
|
try: regexp = self.__funcParamsRegex
|
|
|
|
|
395
|
except AttributeError:
|
|
178
|
except AttributeError:
|
|
396
|
regexp = self.__funcParamsRegex = re.compile(r'''
|
|
179
|
pass
|
|
397
|
'.*?' | # single quoted strings or
|
|
|
|
|
398
|
".*?" | # double quoted strings or
|
|
|
|
|
399
|
\w+ | # identifier
|
|
|
|
|
400
|
\S # other characters
|
|
|
|
|
401
|
''', re.VERBOSE | re.DOTALL)
|
|
|
|
|
402
|
# 1. find the nearest identifier that comes before an unclosed
|
|
|
|
|
403
|
# parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
|
|
|
|
|
404
|
tokens = regexp.findall(self.get_line_buffer())
|
|
|
|
|
405
|
tokens.reverse()
|
|
|
|
|
406
|
iterTokens = iter(tokens); openPar = 0
|
|
|
|
|
407
|
for token in iterTokens:
|
|
|
|
|
408
|
if token == ')':
|
|
|
|
|
409
|
openPar -= 1
|
|
|
|
|
410
|
elif token == '(':
|
|
|
|
|
411
|
openPar += 1
|
|
|
|
|
412
|
if openPar > 0:
|
|
|
|
|
413
|
# found the last unclosed parenthesis
|
|
|
|
|
414
|
break
|
|
|
|
|
415
|
else:
|
|
|
|
|
416
|
return []
|
|
|
|
|
417
|
# 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
|
|
|
|
|
418
|
ids = []
|
|
|
|
|
419
|
isId = re.compile(r'\w+$').match
|
|
|
|
|
420
|
while True:
|
|
|
|
|
421
|
try:
|
|
|
|
|
422
|
ids.append(iterTokens.next())
|
|
|
|
|
423
|
if not isId(ids[-1]):
|
|
|
|
|
424
|
ids.pop(); break
|
|
|
|
|
425
|
if not iterTokens.next() == '.':
|
|
|
|
|
426
|
break
|
|
|
|
|
427
|
except StopIteration:
|
|
|
|
|
428
|
break
|
|
|
|
|
429
|
# lookup the candidate callable matches either using global_matches
|
|
|
|
|
430
|
# or attr_matches for dotted names
|
|
|
|
|
431
|
if len(ids) == 1:
|
|
|
|
|
432
|
callableMatches = self.global_matches(ids[0])
|
|
|
|
|
433
|
else:
|
|
|
|
|
434
|
callableMatches = self.attr_matches('.'.join(ids[::-1]))
|
|
|
|
|
435
|
argMatches = []
|
|
|
|
|
436
|
for callableMatch in callableMatches:
|
|
|
|
|
437
|
try: namedArgs = self._default_arguments(eval(callableMatch,
|
|
|
|
|
438
|
self.namespace))
|
|
|
|
|
439
|
except: continue
|
|
|
|
|
440
|
for namedArg in namedArgs:
|
|
|
|
|
441
|
if namedArg.startswith(text):
|
|
|
|
|
442
|
argMatches.append("%s=" %namedArg)
|
|
|
|
|
443
|
return argMatches
|
|
|
|
|
444
|
|
|
|
|
|
445
|
def complete(self, text, state):
|
|
|
|
|
446
|
"""Return the next possible completion for 'text'.
|
|
|
|
|
447
|
|
|
|
|
|
448
|
This is called successively with state == 0, 1, 2, ... until it
|
|
|
|
|
449
|
returns None. The completion should begin with 'text'. """
|
|
|
|
|
450
|
|
|
|
|
|
451
|
#print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
|
|
|
|
|
452
|
|
|
|
|
|
453
|
# if there is only a tab on a line with only whitespace, instead
|
|
|
|
|
454
|
# of the mostly useless 'do you want to see all million
|
|
|
|
|
455
|
# completions' message, just do the right thing and give the user
|
|
|
|
|
456
|
# his tab! Incidentally, this enables pasting of tabbed text from
|
|
|
|
|
457
|
# an editor (as long as autoindent is off).
|
|
|
|
|
458
|
if not self.get_line_buffer().strip():
|
|
|
|
|
459
|
self.readline.insert_text('\t')
|
|
|
|
|
460
|
return None
|
|
|
|
|
461
|
|
|
|
|
|
462
|
magic_escape = self.magic_escape
|
|
|
|
|
463
|
magic_prefix = self.magic_prefix
|
|
|
|
|
464
|
|
|
|
|
|
465
|
try:
|
|
180
|
try:
|
|
466
|
if text.startswith(magic_escape):
|
|
181
|
file.softspace = newvalue
|
|
467
|
text = text.replace(magic_escape,magic_prefix)
|
|
182
|
except (AttributeError, TypeError):
|
|
468
|
elif text.startswith('~'):
|
|
183
|
# "attribute-less object" or "read-only attributes"
|
|
469
|
text = os.path.expanduser(text)
|
|
184
|
pass
|
|
470
|
if state == 0:
|
|
185
|
return oldvalue
|
|
471
|
# Extend the list of completions with the results of each
|
|
|
|
|
472
|
# matcher, so we return results to the user from all
|
|
|
|
|
473
|
# namespaces.
|
|
|
|
|
474
|
if self.merge_completions:
|
|
|
|
|
475
|
self.matches = []
|
|
|
|
|
476
|
for matcher in self.matchers:
|
|
|
|
|
477
|
self.matches.extend(matcher(text))
|
|
|
|
|
478
|
else:
|
|
|
|
|
479
|
for matcher in self.matchers:
|
|
|
|
|
480
|
self.matches = matcher(text)
|
|
|
|
|
481
|
if self.matches:
|
|
|
|
|
482
|
break
|
|
|
|
|
483
|
|
|
186
|
|
|
484
|
try:
|
|
|
|
|
485
|
return self.matches[state].replace(magic_prefix,magic_escape)
|
|
|
|
|
486
|
except IndexError:
|
|
|
|
|
487
|
return None
|
|
|
|
|
488
|
except:
|
|
|
|
|
489
|
# If completion fails, don't annoy the user.
|
|
|
|
|
490
|
return None
|
|
|
|
|
491
|
|
|
187
|
|
|
492
|
except ImportError:
|
|
188
|
#****************************************************************************
|
|
493
|
pass # no readline support
|
|
189
|
# Local use exceptions
|
|
|
|
|
190
|
class SpaceInInput(exceptions.Exception): pass
|
|
494
|
|
|
191
|
|
|
495
|
except KeyError:
|
|
192
|
class IPythonExit(exceptions.Exception): pass
|
|
496
|
pass # Windows doesn't set TERM, it doesn't matter
|
|
|
|
|
497
|
|
|
193
|
|
|
|
|
|
194
|
#****************************************************************************
|
|
|
|
|
195
|
# Local use classes
|
|
|
|
|
196
|
class Bunch: pass
|
|
498
|
|
|
197
|
|
|
499
|
class InputList(UserList.UserList):
|
|
198
|
class InputList(list):
|
|
500
|
"""Class to store user input.
|
|
199
|
"""Class to store user input.
|
|
501
|
|
|
200
|
|
|
502
|
It's basically a list, but slices return a string instead of a list, thus
|
|
201
|
It's basically a list, but slices return a string instead of a list, thus
|
|
503
|
allowing things like (assuming 'In' is an instance):
|
|
202
|
allowing things like (assuming 'In' is an instance):
|
|
504
|
|
|
203
|
|
|
505
|
exec In[4:7]
|
|
204
|
exec In[4:7]
|
|
506
|
|
|
205
|
|
|
507
|
or
|
|
206
|
or
|
|
508
|
|
|
207
|
|
|
509
|
exec In[5:9] + In[14] + In[21:25]"""
|
|
208
|
exec In[5:9] + In[14] + In[21:25]"""
|
|
510
|
|
|
209
|
|
|
511
|
def __getslice__(self,i,j):
|
|
210
|
def __getslice__(self,i,j):
|
|
512
|
return ''.join(UserList.UserList.__getslice__(self,i,j))
|
|
211
|
return ''.join(list.__getslice__(self,i,j))
|
|
513
|
|
|
|
|
|
514
|
#****************************************************************************
|
|
|
|
|
515
|
# Local use exceptions
|
|
|
|
|
516
|
class SpaceInInput(exceptions.Exception):
|
|
|
|
|
517
|
pass
|
|
|
|
|
518
|
|
|
212
|
|
|
519
|
#****************************************************************************
|
|
213
|
#****************************************************************************
|
|
520
|
# Main IPython class
|
|
214
|
# Main IPython class
|
|
521
|
|
|
215
|
class InteractiveShell(Logger, Magic):
|
|
522
|
class InteractiveShell(code.InteractiveConsole, Logger, Magic):
|
|
|
|
|
523
|
"""An enhanced console for Python."""
|
|
216
|
"""An enhanced console for Python."""
|
|
524
|
|
|
217
|
|
|
525
|
def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
|
|
218
|
def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
|
|
526
|
user_ns = None,user_global_ns=None,banner2='',
|
|
219
|
user_ns = None,user_global_ns=None,banner2='',
|
|
527
|
custom_exceptions=((),None),embedded=False):
|
|
220
|
custom_exceptions=((),None),embedded=False):
|
|
528
|
|
|
221
|
|
|
529
|
# Put a reference to self in builtins so that any form of embedded or
|
|
222
|
# Put a reference to self in builtins so that any form of embedded or
|
|
530
|
# imported code can test for being inside IPython.
|
|
223
|
# imported code can test for being inside IPython.
|
|
531
|
__builtin__.__IPYTHON__ = self
|
|
224
|
__builtin__.__IPYTHON__ = self
|
|
532
|
|
|
225
|
|
|
533
|
# And load into builtins ipmagic/ipalias as well
|
|
226
|
# And load into builtins ipmagic/ipalias as well
|
|
534
|
__builtin__.ipmagic = ipmagic
|
|
227
|
__builtin__.ipmagic = ipmagic
|
|
535
|
__builtin__.ipalias = ipalias
|
|
228
|
__builtin__.ipalias = ipalias
|
|
536
|
|
|
229
|
|
|
537
|
# Add to __builtin__ other parts of IPython's public API
|
|
230
|
# Add to __builtin__ other parts of IPython's public API
|
|
538
|
__builtin__.ip_set_hook = self.set_hook
|
|
231
|
__builtin__.ip_set_hook = self.set_hook
|
|
539
|
|
|
232
|
|
|
540
|
# Keep in the builtins a flag for when IPython is active. We set it
|
|
233
|
# Keep in the builtins a flag for when IPython is active. We set it
|
|
541
|
# with setdefault so that multiple nested IPythons don't clobber one
|
|
234
|
# with setdefault so that multiple nested IPythons don't clobber one
|
|
542
|
# another. Each will increase its value by one upon being activated,
|
|
235
|
# another. Each will increase its value by one upon being activated,
|
|
543
|
# which also gives us a way to determine the nesting level.
|
|
236
|
# which also gives us a way to determine the nesting level.
|
|
544
|
__builtin__.__dict__.setdefault('__IPYTHON__active',0)
|
|
237
|
__builtin__.__dict__.setdefault('__IPYTHON__active',0)
|
|
545
|
|
|
238
|
|
|
546
|
# Inform the user of ipython's fast exit magics.
|
|
239
|
# Do the intuitively correct thing for quit/exit: we remove the
|
|
547
|
_exit = ' Use %Exit or %Quit to exit without confirmation.'
|
|
240
|
# builtins if they exist, and our own prefilter routine will handle
|
|
548
|
__builtin__.exit += _exit
|
|
241
|
# these special cases
|
|
549
|
__builtin__.quit += _exit
|
|
242
|
try:
|
|
|
|
|
243
|
del __builtin__.exit, __builtin__.quit
|
|
|
|
|
244
|
except AttributeError:
|
|
|
|
|
245
|
pass
|
|
550
|
|
|
246
|
|
|
551
|
# We need to know whether the instance is meant for embedding, since
|
|
247
|
# We need to know whether the instance is meant for embedding, since
|
|
552
|
# global/local namespaces need to be handled differently in that case
|
|
248
|
# global/local namespaces need to be handled differently in that case
|
|
553
|
self.embedded = embedded
|
|
249
|
self.embedded = embedded
|
|
554
|
|
|
250
|
|
|
555
|
# compiler command
|
|
251
|
# compiler command
|
|
556
|
self.compile = CommandCompiler()
|
|
252
|
self.compile = codeop.CommandCompiler()
|
|
557
|
|
|
253
|
|
|
558
|
# User input buffer
|
|
254
|
# User input buffer
|
|
559
|
self.buffer = []
|
|
255
|
self.buffer = []
|
|
560
|
|
|
256
|
|
|
561
|
# Default name given in compilation of code
|
|
257
|
# Default name given in compilation of code
|
|
562
|
self.filename = '<ipython console>'
|
|
258
|
self.filename = '<ipython console>'
|
|
563
|
|
|
259
|
|
|
564
|
# Create the namespace where the user will operate. user_ns is
|
|
260
|
# Create the namespace where the user will operate. user_ns is
|
|
565
|
# normally the only one used, and it is passed to the exec calls as
|
|
261
|
# normally the only one used, and it is passed to the exec calls as
|
|
566
|
# the locals argument. But we do carry a user_global_ns namespace
|
|
262
|
# the locals argument. But we do carry a user_global_ns namespace
|
|
567
|
# given as the exec 'globals' argument, This is useful in embedding
|
|
263
|
# given as the exec 'globals' argument, This is useful in embedding
|
|
568
|
# situations where the ipython shell opens in a context where the
|
|
264
|
# situations where the ipython shell opens in a context where the
|
|
569
|
# distinction between locals and globals is meaningful.
|
|
265
|
# distinction between locals and globals is meaningful.
|
|
570
|
|
|
266
|
|
|
571
|
# FIXME. For some strange reason, __builtins__ is showing up at user
|
|
267
|
# FIXME. For some strange reason, __builtins__ is showing up at user
|
|
572
|
# level as a dict instead of a module. This is a manual fix, but I
|
|
268
|
# level as a dict instead of a module. This is a manual fix, but I
|
|
573
|
# should really track down where the problem is coming from. Alex
|
|
269
|
# should really track down where the problem is coming from. Alex
|
|
574
|
# Schmolck reported this problem first.
|
|
270
|
# Schmolck reported this problem first.
|
|
575
|
|
|
271
|
|
|
576
|
# A useful post by Alex Martelli on this topic:
|
|
272
|
# A useful post by Alex Martelli on this topic:
|
|
577
|
# Re: inconsistent value from __builtins__
|
|
273
|
# Re: inconsistent value from __builtins__
|
|
578
|
# Von: Alex Martelli <aleaxit@yahoo.com>
|
|
274
|
# Von: Alex Martelli <aleaxit@yahoo.com>
|
|
579
|
# Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
|
|
275
|
# Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
|
|
580
|
# Gruppen: comp.lang.python
|
|
276
|
# Gruppen: comp.lang.python
|
|
581
|
# Referenzen: 1
|
|
277
|
# Referenzen: 1
|
|
582
|
|
|
278
|
|
|
583
|
# Michael Hohn <hohn@hooknose.lbl.gov> wrote:
|
|
279
|
# Michael Hohn <hohn@hooknose.lbl.gov> wrote:
|
|
584
|
# > >>> print type(builtin_check.get_global_binding('__builtins__'))
|
|
280
|
# > >>> print type(builtin_check.get_global_binding('__builtins__'))
|
|
585
|
# > <type 'dict'>
|
|
281
|
# > <type 'dict'>
|
|
586
|
# > >>> print type(__builtins__)
|
|
282
|
# > >>> print type(__builtins__)
|
|
587
|
# > <type 'module'>
|
|
283
|
# > <type 'module'>
|
|
588
|
# > Is this difference in return value intentional?
|
|
284
|
# > Is this difference in return value intentional?
|
|
589
|
|
|
285
|
|
|
590
|
# Well, it's documented that '__builtins__' can be either a dictionary
|
|
286
|
# Well, it's documented that '__builtins__' can be either a dictionary
|
|
591
|
# or a module, and it's been that way for a long time. Whether it's
|
|
287
|
# or a module, and it's been that way for a long time. Whether it's
|
|
592
|
# intentional (or sensible), I don't know. In any case, the idea is that
|
|
288
|
# intentional (or sensible), I don't know. In any case, the idea is
|
|
593
|
# if you need to access the built-in namespace directly, you should start
|
|
289
|
# that if you need to access the built-in namespace directly, you
|
|
594
|
# with "import __builtin__" (note, no 's') which will definitely give you
|
|
290
|
# should start with "import __builtin__" (note, no 's') which will
|
|
595
|
# a module. Yeah, it's somewhat confusing:-(.
|
|
291
|
# definitely give you a module. Yeah, it's somewhat confusing:-(.
|
|
596
|
|
|
292
|
|
|
597
|
if user_ns is None:
|
|
293
|
if user_ns is None:
|
|
598
|
# Set __name__ to __main__ to better match the behavior of the
|
|
294
|
# Set __name__ to __main__ to better match the behavior of the
|
|
599
|
# normal interpreter.
|
|
295
|
# normal interpreter.
|
|
600
|
user_ns = {'__name__' :'__main__',
|
|
296
|
user_ns = {'__name__' :'__main__',
|
|
601
|
'__builtins__' : __builtin__,
|
|
297
|
'__builtins__' : __builtin__,
|
|
602
|
}
|
|
298
|
}
|
|
603
|
|
|
299
|
|
|
604
|
if user_global_ns is None:
|
|
300
|
if user_global_ns is None:
|
|
605
|
user_global_ns = {}
|
|
301
|
user_global_ns = {}
|
|
606
|
|
|
302
|
|
|
607
|
# Assign namespaces
|
|
303
|
# Assign namespaces
|
|
608
|
# This is the namespace where all normal user variables live
|
|
304
|
# This is the namespace where all normal user variables live
|
|
609
|
self.user_ns = user_ns
|
|
305
|
self.user_ns = user_ns
|
|
610
|
# Embedded instances require a separate namespace for globals.
|
|
306
|
# Embedded instances require a separate namespace for globals.
|
|
611
|
# Normally this one is unused by non-embedded instances.
|
|
307
|
# Normally this one is unused by non-embedded instances.
|
|
612
|
self.user_global_ns = user_global_ns
|
|
308
|
self.user_global_ns = user_global_ns
|
|
613
|
# A namespace to keep track of internal data structures to prevent
|
|
309
|
# A namespace to keep track of internal data structures to prevent
|
|
614
|
# them from cluttering user-visible stuff. Will be updated later
|
|
310
|
# them from cluttering user-visible stuff. Will be updated later
|
|
615
|
self.internal_ns = {}
|
|
311
|
self.internal_ns = {}
|
|
616
|
|
|
312
|
|
|
617
|
# Namespace of system aliases. Each entry in the alias
|
|
313
|
# Namespace of system aliases. Each entry in the alias
|
|
618
|
# table must be a 2-tuple of the form (N,name), where N is the number
|
|
314
|
# table must be a 2-tuple of the form (N,name), where N is the number
|
|
619
|
# of positional arguments of the alias.
|
|
315
|
# of positional arguments of the alias.
|
|
620
|
self.alias_table = {}
|
|
316
|
self.alias_table = {}
|
|
621
|
|
|
317
|
|
|
622
|
# A table holding all the namespaces IPython deals with, so that
|
|
318
|
# A table holding all the namespaces IPython deals with, so that
|
|
623
|
# introspection facilities can search easily.
|
|
319
|
# introspection facilities can search easily.
|
|
624
|
self.ns_table = {'user':user_ns,
|
|
320
|
self.ns_table = {'user':user_ns,
|
|
625
|
'user_global':user_global_ns,
|
|
321
|
'user_global':user_global_ns,
|
|
626
|
'alias':self.alias_table,
|
|
322
|
'alias':self.alias_table,
|
|
627
|
'internal':self.internal_ns,
|
|
323
|
'internal':self.internal_ns,
|
|
628
|
'builtin':__builtin__.__dict__
|
|
324
|
'builtin':__builtin__.__dict__
|
|
629
|
}
|
|
325
|
}
|
|
630
|
|
|
326
|
|
|
631
|
# The user namespace MUST have a pointer to the shell itself.
|
|
327
|
# The user namespace MUST have a pointer to the shell itself.
|
|
632
|
self.user_ns[name] = self
|
|
328
|
self.user_ns[name] = self
|
|
633
|
|
|
329
|
|
|
634
|
# We need to insert into sys.modules something that looks like a
|
|
330
|
# We need to insert into sys.modules something that looks like a
|
|
635
|
# module but which accesses the IPython namespace, for shelve and
|
|
331
|
# module but which accesses the IPython namespace, for shelve and
|
|
636
|
# pickle to work interactively. Normally they rely on getting
|
|
332
|
# pickle to work interactively. Normally they rely on getting
|
|
637
|
# everything out of __main__, but for embedding purposes each IPython
|
|
333
|
# everything out of __main__, but for embedding purposes each IPython
|
|
638
|
# instance has its own private namespace, so we can't go shoving
|
|
334
|
# instance has its own private namespace, so we can't go shoving
|
|
639
|
# everything into __main__.
|
|
335
|
# everything into __main__.
|
|
640
|
|
|
336
|
|
|
641
|
# note, however, that we should only do this for non-embedded
|
|
337
|
# note, however, that we should only do this for non-embedded
|
|
642
|
# ipythons, which really mimic the __main__.__dict__ with their own
|
|
338
|
# ipythons, which really mimic the __main__.__dict__ with their own
|
|
643
|
# namespace. Embedded instances, on the other hand, should not do
|
|
339
|
# namespace. Embedded instances, on the other hand, should not do
|
|
644
|
# this because they need to manage the user local/global namespaces
|
|
340
|
# this because they need to manage the user local/global namespaces
|
|
645
|
# only, but they live within a 'normal' __main__ (meaning, they
|
|
341
|
# only, but they live within a 'normal' __main__ (meaning, they
|
|
646
|
# shouldn't overtake the execution environment of the script they're
|
|
342
|
# shouldn't overtake the execution environment of the script they're
|
|
647
|
# embedded in).
|
|
343
|
# embedded in).
|
|
648
|
|
|
344
|
|
|
649
|
if not embedded:
|
|
345
|
if not embedded:
|
|
650
|
try:
|
|
346
|
try:
|
|
651
|
main_name = self.user_ns['__name__']
|
|
347
|
main_name = self.user_ns['__name__']
|
|
652
|
except KeyError:
|
|
348
|
except KeyError:
|
|
653
|
raise KeyError,'user_ns dictionary MUST have a "__name__" key'
|
|
349
|
raise KeyError,'user_ns dictionary MUST have a "__name__" key'
|
|
654
|
else:
|
|
350
|
else:
|
|
655
|
#print "pickle hack in place" # dbg
|
|
351
|
#print "pickle hack in place" # dbg
|
|
656
|
sys.modules[main_name] = FakeModule(self.user_ns)
|
|
352
|
sys.modules[main_name] = FakeModule(self.user_ns)
|
|
657
|
|
|
353
|
|
|
658
|
# List of input with multi-line handling.
|
|
354
|
# List of input with multi-line handling.
|
|
659
|
# Fill its zero entry, user counter starts at 1
|
|
355
|
# Fill its zero entry, user counter starts at 1
|
|
660
|
self.input_hist = InputList(['\n'])
|
|
356
|
self.input_hist = InputList(['\n'])
|
|
661
|
|
|
357
|
|
|
662
|
# list of visited directories
|
|
358
|
# list of visited directories
|
|
663
|
try:
|
|
359
|
try:
|
|
664
|
self.dir_hist = [os.getcwd()]
|
|
360
|
self.dir_hist = [os.getcwd()]
|
|
665
|
except IOError, e:
|
|
361
|
except IOError, e:
|
|
666
|
self.dir_hist = []
|
|
362
|
self.dir_hist = []
|
|
667
|
|
|
363
|
|
|
668
|
# dict of output history
|
|
364
|
# dict of output history
|
|
669
|
self.output_hist = {}
|
|
365
|
self.output_hist = {}
|
|
670
|
|
|
366
|
|
|
671
|
# dict of things NOT to alias (keywords, builtins and some special magics)
|
|
367
|
# dict of things NOT to alias (keywords, builtins and some magics)
|
|
672
|
no_alias = {}
|
|
368
|
no_alias = {}
|
|
673
|
no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
|
|
369
|
no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
|
|
674
|
for key in keyword.kwlist + no_alias_magics:
|
|
370
|
for key in keyword.kwlist + no_alias_magics:
|
|
675
|
no_alias[key] = 1
|
|
371
|
no_alias[key] = 1
|
|
676
|
no_alias.update(__builtin__.__dict__)
|
|
372
|
no_alias.update(__builtin__.__dict__)
|
|
677
|
self.no_alias = no_alias
|
|
373
|
self.no_alias = no_alias
|
|
678
|
|
|
374
|
|
|
679
|
# make global variables for user access to these
|
|
375
|
# make global variables for user access to these
|
|
680
|
self.user_ns['_ih'] = self.input_hist
|
|
376
|
self.user_ns['_ih'] = self.input_hist
|
|
681
|
self.user_ns['_oh'] = self.output_hist
|
|
377
|
self.user_ns['_oh'] = self.output_hist
|
|
682
|
self.user_ns['_dh'] = self.dir_hist
|
|
378
|
self.user_ns['_dh'] = self.dir_hist
|
|
683
|
|
|
379
|
|
|
684
|
# user aliases to input and output histories
|
|
380
|
# user aliases to input and output histories
|
|
685
|
self.user_ns['In'] = self.input_hist
|
|
381
|
self.user_ns['In'] = self.input_hist
|
|
686
|
self.user_ns['Out'] = self.output_hist
|
|
382
|
self.user_ns['Out'] = self.output_hist
|
|
687
|
|
|
383
|
|
|
688
|
# Store the actual shell's name
|
|
384
|
# Store the actual shell's name
|
|
689
|
self.name = name
|
|
385
|
self.name = name
|
|
690
|
|
|
386
|
|
|
691
|
# Object variable to store code object waiting execution. This is
|
|
387
|
# Object variable to store code object waiting execution. This is
|
|
692
|
# used mainly by the multithreaded shells, but it can come in handy in
|
|
388
|
# used mainly by the multithreaded shells, but it can come in handy in
|
|
693
|
# other situations. No need to use a Queue here, since it's a single
|
|
389
|
# other situations. No need to use a Queue here, since it's a single
|
|
694
|
# item which gets cleared once run.
|
|
390
|
# item which gets cleared once run.
|
|
695
|
self.code_to_run = None
|
|
391
|
self.code_to_run = None
|
|
696
|
|
|
392
|
|
|
697
|
# Job manager (for jobs run as background threads)
|
|
393
|
# Job manager (for jobs run as background threads)
|
|
698
|
self.jobs = BackgroundJobManager()
|
|
394
|
self.jobs = BackgroundJobManager()
|
|
699
|
# Put the job manager into builtins so it's always there.
|
|
395
|
# Put the job manager into builtins so it's always there.
|
|
700
|
__builtin__.jobs = self.jobs
|
|
396
|
__builtin__.jobs = self.jobs
|
|
701
|
|
|
397
|
|
|
702
|
# escapes for automatic behavior on the command line
|
|
398
|
# escapes for automatic behavior on the command line
|
|
703
|
self.ESC_SHELL = '!'
|
|
399
|
self.ESC_SHELL = '!'
|
|
704
|
self.ESC_HELP = '?'
|
|
400
|
self.ESC_HELP = '?'
|
|
705
|
self.ESC_MAGIC = '%'
|
|
401
|
self.ESC_MAGIC = '%'
|
|
706
|
self.ESC_QUOTE = ','
|
|
402
|
self.ESC_QUOTE = ','
|
|
707
|
self.ESC_QUOTE2 = ';'
|
|
403
|
self.ESC_QUOTE2 = ';'
|
|
708
|
self.ESC_PAREN = '/'
|
|
404
|
self.ESC_PAREN = '/'
|
|
709
|
|
|
405
|
|
|
710
|
# And their associated handlers
|
|
406
|
# And their associated handlers
|
|
711
|
self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
|
|
407
|
self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
|
|
712
|
self.ESC_QUOTE:self.handle_auto,
|
|
408
|
self.ESC_QUOTE:self.handle_auto,
|
|
713
|
self.ESC_QUOTE2:self.handle_auto,
|
|
409
|
self.ESC_QUOTE2:self.handle_auto,
|
|
714
|
self.ESC_MAGIC:self.handle_magic,
|
|
410
|
self.ESC_MAGIC:self.handle_magic,
|
|
715
|
self.ESC_HELP:self.handle_help,
|
|
411
|
self.ESC_HELP:self.handle_help,
|
|
716
|
self.ESC_SHELL:self.handle_shell_escape,
|
|
412
|
self.ESC_SHELL:self.handle_shell_escape,
|
|
717
|
}
|
|
413
|
}
|
|
718
|
|
|
414
|
|
|
719
|
# class initializations
|
|
415
|
# class initializations
|
|
720
|
Logger.__init__(self,log_ns = self.user_ns)
|
|
416
|
Logger.__init__(self,log_ns = self.user_ns)
|
|
721
|
Magic.__init__(self,self)
|
|
417
|
Magic.__init__(self,self)
|
|
722
|
|
|
418
|
|
|
723
|
# an ugly hack to get a pointer to the shell, so I can start writing
|
|
419
|
# an ugly hack to get a pointer to the shell, so I can start writing
|
|
724
|
# magic code via this pointer instead of the current mixin salad.
|
|
420
|
# magic code via this pointer instead of the current mixin salad.
|
|
725
|
Magic.set_shell(self,self)
|
|
421
|
Magic.set_shell(self,self)
|
|
726
|
|
|
422
|
|
|
727
|
# Python source parser/formatter for syntax highlighting
|
|
423
|
# Python source parser/formatter for syntax highlighting
|
|
728
|
pyformat = Parser().format
|
|
424
|
pyformat = Parser().format
|
|
729
|
self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
|
|
425
|
self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
|
|
730
|
|
|
426
|
|
|
731
|
# hooks holds pointers used for user-side customizations
|
|
427
|
# hooks holds pointers used for user-side customizations
|
|
732
|
self.hooks = Struct()
|
|
428
|
self.hooks = Struct()
|
|
733
|
|
|
429
|
|
|
734
|
# Set all default hooks, defined in the IPython.hooks module.
|
|
430
|
# Set all default hooks, defined in the IPython.hooks module.
|
|
735
|
hooks = IPython.hooks
|
|
431
|
hooks = IPython.hooks
|
|
736
|
for hook_name in hooks.__all__:
|
|
432
|
for hook_name in hooks.__all__:
|
|
737
|
self.set_hook(hook_name,getattr(hooks,hook_name))
|
|
433
|
self.set_hook(hook_name,getattr(hooks,hook_name))
|
|
738
|
|
|
434
|
|
|
739
|
# Flag to mark unconditional exit
|
|
435
|
# Flag to mark unconditional exit
|
|
740
|
self.exit_now = False
|
|
436
|
self.exit_now = False
|
|
741
|
|
|
437
|
|
|
742
|
self.usage_min = """\
|
|
438
|
self.usage_min = """\
|
|
743
|
An enhanced console for Python.
|
|
439
|
An enhanced console for Python.
|
|
744
|
Some of its features are:
|
|
440
|
Some of its features are:
|
|
745
|
- Readline support if the readline library is present.
|
|
441
|
- Readline support if the readline library is present.
|
|
746
|
- Tab completion in the local namespace.
|
|
442
|
- Tab completion in the local namespace.
|
|
747
|
- Logging of input, see command-line options.
|
|
443
|
- Logging of input, see command-line options.
|
|
748
|
- System shell escape via ! , eg !ls.
|
|
444
|
- System shell escape via ! , eg !ls.
|
|
749
|
- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
|
|
445
|
- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
|
|
750
|
- Keeps track of locally defined variables via %who, %whos.
|
|
446
|
- Keeps track of locally defined variables via %who, %whos.
|
|
751
|
- Show object information with a ? eg ?x or x? (use ?? for more info).
|
|
447
|
- Show object information with a ? eg ?x or x? (use ?? for more info).
|
|
752
|
"""
|
|
448
|
"""
|
|
753
|
if usage: self.usage = usage
|
|
449
|
if usage: self.usage = usage
|
|
754
|
else: self.usage = self.usage_min
|
|
450
|
else: self.usage = self.usage_min
|
|
755
|
|
|
451
|
|
|
756
|
# Storage
|
|
452
|
# Storage
|
|
757
|
self.rc = rc # This will hold all configuration information
|
|
453
|
self.rc = rc # This will hold all configuration information
|
|
758
|
self.inputcache = []
|
|
454
|
self.inputcache = []
|
|
759
|
self._boundcache = []
|
|
455
|
self._boundcache = []
|
|
760
|
self.pager = 'less'
|
|
456
|
self.pager = 'less'
|
|
761
|
# temporary files used for various purposes. Deleted at exit.
|
|
457
|
# temporary files used for various purposes. Deleted at exit.
|
|
762
|
self.tempfiles = []
|
|
458
|
self.tempfiles = []
|
|
763
|
|
|
459
|
|
|
764
|
# Keep track of readline usage (later set by init_readline)
|
|
460
|
# Keep track of readline usage (later set by init_readline)
|
|
765
|
self.has_readline = 0
|
|
461
|
self.has_readline = False
|
|
766
|
|
|
462
|
|
|
767
|
# for pushd/popd management
|
|
463
|
# for pushd/popd management
|
|
768
|
try:
|
|
464
|
try:
|
|
769
|
self.home_dir = get_home_dir()
|
|
465
|
self.home_dir = get_home_dir()
|
|
770
|
except HomeDirError,msg:
|
|
466
|
except HomeDirError,msg:
|
|
771
|
fatal(msg)
|
|
467
|
fatal(msg)
|
|
772
|
|
|
468
|
|
|
773
|
self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
|
|
469
|
self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
|
|
774
|
|
|
470
|
|
|
775
|
# Functions to call the underlying shell.
|
|
471
|
# Functions to call the underlying shell.
|
|
776
|
|
|
472
|
|
|
777
|
# utility to expand user variables via Itpl
|
|
473
|
# utility to expand user variables via Itpl
|
|
778
|
self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
|
|
474
|
self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
|
|
779
|
self.user_ns))
|
|
475
|
self.user_ns))
|
|
780
|
# The first is similar to os.system, but it doesn't return a value,
|
|
476
|
# The first is similar to os.system, but it doesn't return a value,
|
|
781
|
# and it allows interpolation of variables in the user's namespace.
|
|
477
|
# and it allows interpolation of variables in the user's namespace.
|
|
782
|
self.system = lambda cmd: shell(self.var_expand(cmd),
|
|
478
|
self.system = lambda cmd: shell(self.var_expand(cmd),
|
|
783
|
header='IPython system call: ',
|
|
479
|
header='IPython system call: ',
|
|
784
|
verbose=self.rc.system_verbose)
|
|
480
|
verbose=self.rc.system_verbose)
|
|
785
|
# These are for getoutput and getoutputerror:
|
|
481
|
# These are for getoutput and getoutputerror:
|
|
786
|
self.getoutput = lambda cmd: \
|
|
482
|
self.getoutput = lambda cmd: \
|
|
787
|
getoutput(self.var_expand(cmd),
|
|
483
|
getoutput(self.var_expand(cmd),
|
|
788
|
header='IPython system call: ',
|
|
484
|
header='IPython system call: ',
|
|
789
|
verbose=self.rc.system_verbose)
|
|
485
|
verbose=self.rc.system_verbose)
|
|
790
|
self.getoutputerror = lambda cmd: \
|
|
486
|
self.getoutputerror = lambda cmd: \
|
|
791
|
getoutputerror(str(ItplNS(cmd.replace('#','\#'),
|
|
487
|
getoutputerror(str(ItplNS(cmd.replace('#','\#'),
|
|
792
|
self.user_ns)),
|
|
488
|
self.user_ns)),
|
|
793
|
header='IPython system call: ',
|
|
489
|
header='IPython system call: ',
|
|
794
|
verbose=self.rc.system_verbose)
|
|
490
|
verbose=self.rc.system_verbose)
|
|
795
|
|
|
491
|
|
|
796
|
# RegExp for splitting line contents into pre-char//first
|
|
492
|
# RegExp for splitting line contents into pre-char//first
|
|
797
|
# word-method//rest. For clarity, each group in on one line.
|
|
493
|
# word-method//rest. For clarity, each group in on one line.
|
|
798
|
|
|
494
|
|
|
799
|
# WARNING: update the regexp if the above escapes are changed, as they
|
|
495
|
# WARNING: update the regexp if the above escapes are changed, as they
|
|
800
|
# are hardwired in.
|
|
496
|
# are hardwired in.
|
|
801
|
|
|
497
|
|
|
802
|
# Don't get carried away with trying to make the autocalling catch too
|
|
498
|
# Don't get carried away with trying to make the autocalling catch too
|
|
803
|
# much: it's better to be conservative rather than to trigger hidden
|
|
499
|
# much: it's better to be conservative rather than to trigger hidden
|
|
804
|
# evals() somewhere and end up causing side effects.
|
|
500
|
# evals() somewhere and end up causing side effects.
|
|
805
|
|
|
501
|
|
|
806
|
self.line_split = re.compile(r'^([\s*,;/])'
|
|
502
|
self.line_split = re.compile(r'^([\s*,;/])'
|
|
807
|
r'([\?\w\.]+\w*\s*)'
|
|
503
|
r'([\?\w\.]+\w*\s*)'
|
|
808
|
r'(\(?.*$)')
|
|
504
|
r'(\(?.*$)')
|
|
809
|
|
|
505
|
|
|
810
|
# Original re, keep around for a while in case changes break something
|
|
506
|
# Original re, keep around for a while in case changes break something
|
|
811
|
#self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
|
|
507
|
#self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
|
|
812
|
# r'(\s*[\?\w\.]+\w*\s*)'
|
|
508
|
# r'(\s*[\?\w\.]+\w*\s*)'
|
|
813
|
# r'(\(?.*$)')
|
|
509
|
# r'(\(?.*$)')
|
|
814
|
|
|
510
|
|
|
815
|
# RegExp to identify potential function names
|
|
511
|
# RegExp to identify potential function names
|
|
816
|
self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
|
|
512
|
self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
|
|
817
|
# RegExp to exclude strings with this start from autocalling
|
|
513
|
# RegExp to exclude strings with this start from autocalling
|
|
818
|
self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
|
|
514
|
self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
|
|
|
|
|
515
|
|
|
819
|
# try to catch also methods for stuff in lists/tuples/dicts: off
|
|
516
|
# try to catch also methods for stuff in lists/tuples/dicts: off
|
|
820
|
# (experimental). For this to work, the line_split regexp would need
|
|
517
|
# (experimental). For this to work, the line_split regexp would need
|
|
821
|
# to be modified so it wouldn't break things at '['. That line is
|
|
518
|
# to be modified so it wouldn't break things at '['. That line is
|
|
822
|
# nasty enough that I shouldn't change it until I can test it _well_.
|
|
519
|
# nasty enough that I shouldn't change it until I can test it _well_.
|
|
823
|
#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
|
|
520
|
#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
|
|
824
|
|
|
521
|
|
|
825
|
# keep track of where we started running (mainly for crash post-mortem)
|
|
522
|
# keep track of where we started running (mainly for crash post-mortem)
|
|
826
|
self.starting_dir = os.getcwd()
|
|
523
|
self.starting_dir = os.getcwd()
|
|
827
|
|
|
524
|
|
|
828
|
# Attributes for Logger mixin class, make defaults here
|
|
525
|
# Attributes for Logger mixin class, make defaults here
|
|
829
|
self._dolog = 0
|
|
526
|
self._dolog = False
|
|
830
|
self.LOG = ''
|
|
527
|
self.LOG = ''
|
|
831
|
self.LOGDEF = '.InteractiveShell.log'
|
|
528
|
self.LOGDEF = '.InteractiveShell.log'
|
|
832
|
self.LOGMODE = 'over'
|
|
529
|
self.LOGMODE = 'over'
|
|
833
|
self.LOGHEAD = Itpl(
|
|
530
|
self.LOGHEAD = Itpl(
|
|
834
|
"""#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
|
|
531
|
"""#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
|
|
835
|
#log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
|
|
532
|
#log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
|
|
836
|
#log# opts = $self.rc.opts
|
|
533
|
#log# opts = $self.rc.opts
|
|
837
|
#log# args = $self.rc.args
|
|
534
|
#log# args = $self.rc.args
|
|
838
|
#log# It is safe to make manual edits below here.
|
|
535
|
#log# It is safe to make manual edits below here.
|
|
839
|
#log#-----------------------------------------------------------------------
|
|
536
|
#log#-----------------------------------------------------------------------
|
|
840
|
""")
|
|
537
|
""")
|
|
841
|
# Various switches which can be set
|
|
538
|
# Various switches which can be set
|
|
842
|
self.CACHELENGTH = 5000 # this is cheap, it's just text
|
|
539
|
self.CACHELENGTH = 5000 # this is cheap, it's just text
|
|
843
|
self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
|
|
540
|
self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
|
|
844
|
self.banner2 = banner2
|
|
541
|
self.banner2 = banner2
|
|
845
|
|
|
542
|
|
|
846
|
# TraceBack handlers:
|
|
543
|
# TraceBack handlers:
|
|
847
|
# Need two, one for syntax errors and one for other exceptions.
|
|
544
|
# Need two, one for syntax errors and one for other exceptions.
|
|
848
|
self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
|
|
545
|
self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
|
|
849
|
# This one is initialized with an offset, meaning we always want to
|
|
546
|
# This one is initialized with an offset, meaning we always want to
|
|
850
|
# remove the topmost item in the traceback, which is our own internal
|
|
547
|
# remove the topmost item in the traceback, which is our own internal
|
|
851
|
# code. Valid modes: ['Plain','Context','Verbose']
|
|
548
|
# code. Valid modes: ['Plain','Context','Verbose']
|
|
852
|
self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
|
|
549
|
self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
|
|
853
|
color_scheme='NoColor',
|
|
550
|
color_scheme='NoColor',
|
|
854
|
tb_offset = 1)
|
|
551
|
tb_offset = 1)
|
|
855
|
# and add any custom exception handlers the user may have specified
|
|
552
|
# and add any custom exception handlers the user may have specified
|
|
856
|
self.set_custom_exc(*custom_exceptions)
|
|
553
|
self.set_custom_exc(*custom_exceptions)
|
|
857
|
|
|
554
|
|
|
858
|
# Object inspector
|
|
555
|
# Object inspector
|
|
859
|
ins_colors = OInspect.InspectColors
|
|
556
|
ins_colors = OInspect.InspectColors
|
|
860
|
code_colors = PyColorize.ANSICodeColors
|
|
557
|
code_colors = PyColorize.ANSICodeColors
|
|
861
|
self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
|
|
558
|
self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
|
|
862
|
self.autoindent = 0
|
|
559
|
self.autoindent = False
|
|
863
|
|
|
560
|
|
|
864
|
# Make some aliases automatically
|
|
561
|
# Make some aliases automatically
|
|
865
|
# Prepare list of shell aliases to auto-define
|
|
562
|
# Prepare list of shell aliases to auto-define
|
|
866
|
if os.name == 'posix':
|
|
563
|
if os.name == 'posix':
|
|
867
|
auto_alias = ('mkdir mkdir', 'rmdir rmdir',
|
|
564
|
auto_alias = ('mkdir mkdir', 'rmdir rmdir',
|
|
868
|
'mv mv -i','rm rm -i','cp cp -i',
|
|
565
|
'mv mv -i','rm rm -i','cp cp -i',
|
|
869
|
'cat cat','less less','clear clear',
|
|
566
|
'cat cat','less less','clear clear',
|
|
870
|
# a better ls
|
|
567
|
# a better ls
|
|
871
|
'ls ls -F',
|
|
568
|
'ls ls -F',
|
|
872
|
# long ls
|
|
569
|
# long ls
|
|
873
|
'll ls -lF',
|
|
570
|
'll ls -lF',
|
|
874
|
# color ls
|
|
571
|
# color ls
|
|
875
|
'lc ls -F -o --color',
|
|
572
|
'lc ls -F -o --color',
|
|
876
|
# ls normal files only
|
|
573
|
# ls normal files only
|
|
877
|
'lf ls -F -o --color %l | grep ^-',
|
|
574
|
'lf ls -F -o --color %l | grep ^-',
|
|
878
|
# ls symbolic links
|
|
575
|
# ls symbolic links
|
|
879
|
'lk ls -F -o --color %l | grep ^l',
|
|
576
|
'lk ls -F -o --color %l | grep ^l',
|
|
880
|
# directories or links to directories,
|
|
577
|
# directories or links to directories,
|
|
881
|
'ldir ls -F -o --color %l | grep /$',
|
|
578
|
'ldir ls -F -o --color %l | grep /$',
|
|
882
|
# things which are executable
|
|
579
|
# things which are executable
|
|
883
|
'lx ls -F -o --color %l | grep ^-..x',
|
|
580
|
'lx ls -F -o --color %l | grep ^-..x',
|
|
884
|
)
|
|
581
|
)
|
|
885
|
elif os.name in ['nt','dos']:
|
|
582
|
elif os.name in ['nt','dos']:
|
|
886
|
auto_alias = ('dir dir /on', 'ls dir /on',
|
|
583
|
auto_alias = ('dir dir /on', 'ls dir /on',
|
|
887
|
'ddir dir /ad /on', 'ldir dir /ad /on',
|
|
584
|
'ddir dir /ad /on', 'ldir dir /ad /on',
|
|
888
|
'mkdir mkdir','rmdir rmdir','echo echo',
|
|
585
|
'mkdir mkdir','rmdir rmdir','echo echo',
|
|
889
|
'ren ren','cls cls','copy copy')
|
|
586
|
'ren ren','cls cls','copy copy')
|
|
890
|
else:
|
|
587
|
else:
|
|
891
|
auto_alias = ()
|
|
588
|
auto_alias = ()
|
|
892
|
self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
|
|
589
|
self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
|
|
893
|
# Call the actual (public) initializer
|
|
590
|
# Call the actual (public) initializer
|
|
894
|
self.init_auto_alias()
|
|
591
|
self.init_auto_alias()
|
|
895
|
# end __init__
|
|
592
|
# end __init__
|
|
896
|
|
|
593
|
|
|
897
|
def set_hook(self,name,hook):
|
|
594
|
def set_hook(self,name,hook):
|
|
898
|
"""set_hook(name,hook) -> sets an internal IPython hook.
|
|
595
|
"""set_hook(name,hook) -> sets an internal IPython hook.
|
|
899
|
|
|
596
|
|
|
900
|
IPython exposes some of its internal API as user-modifiable hooks. By
|
|
597
|
IPython exposes some of its internal API as user-modifiable hooks. By
|
|
901
|
resetting one of these hooks, you can modify IPython's behavior to
|
|
598
|
resetting one of these hooks, you can modify IPython's behavior to
|
|
902
|
call at runtime your own routines."""
|
|
599
|
call at runtime your own routines."""
|
|
903
|
|
|
600
|
|
|
904
|
# At some point in the future, this should validate the hook before it
|
|
601
|
# At some point in the future, this should validate the hook before it
|
|
905
|
# accepts it. Probably at least check that the hook takes the number
|
|
602
|
# accepts it. Probably at least check that the hook takes the number
|
|
906
|
# of args it's supposed to.
|
|
603
|
# of args it's supposed to.
|
|
907
|
setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
|
|
604
|
setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
|
|
908
|
|
|
605
|
|
|
909
|
def set_custom_exc(self,exc_tuple,handler):
|
|
606
|
def set_custom_exc(self,exc_tuple,handler):
|
|
910
|
"""set_custom_exc(exc_tuple,handler)
|
|
607
|
"""set_custom_exc(exc_tuple,handler)
|
|
911
|
|
|
608
|
|
|
912
|
Set a custom exception handler, which will be called if any of the
|
|
609
|
Set a custom exception handler, which will be called if any of the
|
|
913
|
exceptions in exc_tuple occur in the mainloop (specifically, in the
|
|
610
|
exceptions in exc_tuple occur in the mainloop (specifically, in the
|
|
914
|
runcode() method.
|
|
611
|
runcode() method.
|
|
915
|
|
|
612
|
|
|
916
|
Inputs:
|
|
613
|
Inputs:
|
|
917
|
|
|
614
|
|
|
918
|
- exc_tuple: a *tuple* of valid exceptions to call the defined
|
|
615
|
- exc_tuple: a *tuple* of valid exceptions to call the defined
|
|
919
|
handler for. It is very important that you use a tuple, and NOT A
|
|
616
|
handler for. It is very important that you use a tuple, and NOT A
|
|
920
|
LIST here, because of the way Python's except statement works. If
|
|
617
|
LIST here, because of the way Python's except statement works. If
|
|
921
|
you only want to trap a single exception, use a singleton tuple:
|
|
618
|
you only want to trap a single exception, use a singleton tuple:
|
|
922
|
|
|
619
|
|
|
923
|
exc_tuple == (MyCustomException,)
|
|
620
|
exc_tuple == (MyCustomException,)
|
|
924
|
|
|
621
|
|
|
925
|
- handler: this must be defined as a function with the following
|
|
622
|
- handler: this must be defined as a function with the following
|
|
926
|
basic interface: def my_handler(self,etype,value,tb).
|
|
623
|
basic interface: def my_handler(self,etype,value,tb).
|
|
927
|
|
|
624
|
|
|
928
|
This will be made into an instance method (via new.instancemethod)
|
|
625
|
This will be made into an instance method (via new.instancemethod)
|
|
929
|
of IPython itself, and it will be called if any of the exceptions
|
|
626
|
of IPython itself, and it will be called if any of the exceptions
|
|
930
|
listed in the exc_tuple are caught. If the handler is None, an
|
|
627
|
listed in the exc_tuple are caught. If the handler is None, an
|
|
931
|
internal basic one is used, which just prints basic info.
|
|
628
|
internal basic one is used, which just prints basic info.
|
|
932
|
|
|
629
|
|
|
933
|
WARNING: by putting in your own exception handler into IPython's main
|
|
630
|
WARNING: by putting in your own exception handler into IPython's main
|
|
934
|
execution loop, you run a very good chance of nasty crashes. This
|
|
631
|
execution loop, you run a very good chance of nasty crashes. This
|
|
935
|
facility should only be used if you really know what you are doing."""
|
|
632
|
facility should only be used if you really know what you are doing."""
|
|
936
|
|
|
633
|
|
|
937
|
assert type(exc_tuple)==type(()) , \
|
|
634
|
assert type(exc_tuple)==type(()) , \
|
|
938
|
"The custom exceptions must be given AS A TUPLE."
|
|
635
|
"The custom exceptions must be given AS A TUPLE."
|
|
939
|
|
|
636
|
|
|
940
|
def dummy_handler(self,etype,value,tb):
|
|
637
|
def dummy_handler(self,etype,value,tb):
|
|
941
|
print '*** Simple custom exception handler ***'
|
|
638
|
print '*** Simple custom exception handler ***'
|
|
942
|
print 'Exception type :',etype
|
|
639
|
print 'Exception type :',etype
|
|
943
|
print 'Exception value:',value
|
|
640
|
print 'Exception value:',value
|
|
944
|
print 'Traceback :',tb
|
|
641
|
print 'Traceback :',tb
|
|
945
|
print 'Source code :','\n'.join(self.buffer)
|
|
642
|
print 'Source code :','\n'.join(self.buffer)
|
|
946
|
|
|
643
|
|
|
947
|
if handler is None: handler = dummy_handler
|
|
644
|
if handler is None: handler = dummy_handler
|
|
948
|
|
|
645
|
|
|
949
|
self.CustomTB = new.instancemethod(handler,self,self.__class__)
|
|
646
|
self.CustomTB = new.instancemethod(handler,self,self.__class__)
|
|
950
|
self.custom_exceptions = exc_tuple
|
|
647
|
self.custom_exceptions = exc_tuple
|
|
951
|
|
|
648
|
|
|
952
|
def set_custom_completer(self,completer,pos=0):
|
|
649
|
def set_custom_completer(self,completer,pos=0):
|
|
953
|
"""set_custom_completer(completer,pos=0)
|
|
650
|
"""set_custom_completer(completer,pos=0)
|
|
954
|
|
|
651
|
|
|
955
|
Adds a new custom completer function.
|
|
652
|
Adds a new custom completer function.
|
|
956
|
|
|
653
|
|
|
957
|
The position argument (defaults to 0) is the index in the completers
|
|
654
|
The position argument (defaults to 0) is the index in the completers
|
|
958
|
list where you want the completer to be inserted."""
|
|
655
|
list where you want the completer to be inserted."""
|
|
959
|
|
|
656
|
|
|
960
|
newcomp = new.instancemethod(completer,self.Completer,
|
|
657
|
newcomp = new.instancemethod(completer,self.Completer,
|
|
961
|
self.Completer.__class__)
|
|
658
|
self.Completer.__class__)
|
|
962
|
self.Completer.matchers.insert(pos,newcomp)
|
|
659
|
self.Completer.matchers.insert(pos,newcomp)
|
|
963
|
|
|
660
|
|
|
964
|
def complete(self,text):
|
|
661
|
def complete(self,text):
|
|
965
|
"""Return a sorted list of all possible completions on text.
|
|
662
|
"""Return a sorted list of all possible completions on text.
|
|
966
|
|
|
663
|
|
|
967
|
Inputs:
|
|
664
|
Inputs:
|
|
968
|
|
|
665
|
|
|
969
|
- text: a string of text to be completed on.
|
|
666
|
- text: a string of text to be completed on.
|
|
970
|
|
|
667
|
|
|
971
|
This is a wrapper around the completion mechanism, similar to what
|
|
668
|
This is a wrapper around the completion mechanism, similar to what
|
|
972
|
readline does at the command line when the TAB key is hit. By
|
|
669
|
readline does at the command line when the TAB key is hit. By
|
|
973
|
exposing it as a method, it can be used by other non-readline
|
|
670
|
exposing it as a method, it can be used by other non-readline
|
|
974
|
environments (such as GUIs) for text completion.
|
|
671
|
environments (such as GUIs) for text completion.
|
|
975
|
|
|
672
|
|
|
976
|
Simple usage example:
|
|
673
|
Simple usage example:
|
|
977
|
|
|
674
|
|
|
978
|
In [1]: x = 'hello'
|
|
675
|
In [1]: x = 'hello'
|
|
979
|
|
|
676
|
|
|
980
|
In [2]: __IP.complete('x.l')
|
|
677
|
In [2]: __IP.complete('x.l')
|
|
981
|
Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
|
|
678
|
Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
|
|
982
|
|
|
679
|
|
|
983
|
complete = self.Completer.complete
|
|
680
|
complete = self.Completer.complete
|
|
984
|
state = 0
|
|
681
|
state = 0
|
|
985
|
# use a dict so we get unique keys, since ipyhton's multiple
|
|
682
|
# use a dict so we get unique keys, since ipyhton's multiple
|
|
986
|
# completers can return duplicates.
|
|
683
|
# completers can return duplicates.
|
|
987
|
comps = {}
|
|
684
|
comps = {}
|
|
988
|
while True:
|
|
685
|
while True:
|
|
989
|
newcomp = complete(text,state)
|
|
686
|
newcomp = complete(text,state)
|
|
990
|
if newcomp is None:
|
|
687
|
if newcomp is None:
|
|
991
|
break
|
|
688
|
break
|
|
992
|
comps[newcomp] = 1
|
|
689
|
comps[newcomp] = 1
|
|
993
|
state += 1
|
|
690
|
state += 1
|
|
994
|
outcomps = comps.keys()
|
|
691
|
outcomps = comps.keys()
|
|
995
|
outcomps.sort()
|
|
692
|
outcomps.sort()
|
|
996
|
return outcomps
|
|
693
|
return outcomps
|
|
997
|
|
|
694
|
|
|
998
|
def set_completer_frame(self, frame):
|
|
695
|
def set_completer_frame(self, frame):
|
|
999
|
if frame:
|
|
696
|
if frame:
|
|
1000
|
self.Completer.namespace = frame.f_locals
|
|
697
|
self.Completer.namespace = frame.f_locals
|
|
1001
|
self.Completer.global_namespace = frame.f_globals
|
|
698
|
self.Completer.global_namespace = frame.f_globals
|
|
1002
|
else:
|
|
699
|
else:
|
|
1003
|
self.Completer.namespace = self.user_ns
|
|
700
|
self.Completer.namespace = self.user_ns
|
|
1004
|
self.Completer.global_namespace = self.user_global_ns
|
|
701
|
self.Completer.global_namespace = self.user_global_ns
|
|
1005
|
|
|
702
|
|
|
1006
|
def post_config_initialization(self):
|
|
703
|
def post_config_initialization(self):
|
|
1007
|
"""Post configuration init method
|
|
704
|
"""Post configuration init method
|
|
1008
|
|
|
705
|
|
|
1009
|
This is called after the configuration files have been processed to
|
|
706
|
This is called after the configuration files have been processed to
|
|
1010
|
'finalize' the initialization."""
|
|
707
|
'finalize' the initialization."""
|
|
1011
|
|
|
708
|
|
|
1012
|
rc = self.rc
|
|
709
|
rc = self.rc
|
|
1013
|
|
|
710
|
|
|
1014
|
# Load readline proper
|
|
711
|
# Load readline proper
|
|
1015
|
if rc.readline:
|
|
712
|
if rc.readline:
|
|
1016
|
self.init_readline()
|
|
713
|
self.init_readline()
|
|
1017
|
|
|
714
|
|
|
1018
|
# Set user colors (don't do it in the constructor above so that it doesn't
|
|
715
|
# Set user colors (don't do it in the constructor above so that it
|
|
1019
|
# crash if colors option is invalid)
|
|
716
|
# doesn't crash if colors option is invalid)
|
|
1020
|
self.magic_colors(rc.colors)
|
|
717
|
self.magic_colors(rc.colors)
|
|
1021
|
|
|
718
|
|
|
1022
|
# Load user aliases
|
|
719
|
# Load user aliases
|
|
1023
|
for alias in rc.alias:
|
|
720
|
for alias in rc.alias:
|
|
1024
|
self.magic_alias(alias)
|
|
721
|
self.magic_alias(alias)
|
|
1025
|
|
|
722
|
|
|
1026
|
# dynamic data that survives through sessions
|
|
723
|
# dynamic data that survives through sessions
|
|
1027
|
# XXX make the filename a config option?
|
|
724
|
# XXX make the filename a config option?
|
|
1028
|
persist_base = 'persist'
|
|
725
|
persist_base = 'persist'
|
|
1029
|
if rc.profile:
|
|
726
|
if rc.profile:
|
|
1030
|
persist_base += '_%s' % rc.profile
|
|
727
|
persist_base += '_%s' % rc.profile
|
|
1031
|
self.persist_fname = os.path.join(rc.ipythondir,persist_base)
|
|
728
|
self.persist_fname = os.path.join(rc.ipythondir,persist_base)
|
|
1032
|
|
|
729
|
|
|
1033
|
try:
|
|
730
|
try:
|
|
1034
|
self.persist = pickle.load(file(self.persist_fname))
|
|
731
|
self.persist = pickle.load(file(self.persist_fname))
|
|
1035
|
except:
|
|
732
|
except:
|
|
1036
|
self.persist = {}
|
|
733
|
self.persist = {}
|
|
1037
|
|
|
734
|
|
|
1038
|
def init_auto_alias(self):
|
|
735
|
def init_auto_alias(self):
|
|
1039
|
"""Define some aliases automatically.
|
|
736
|
"""Define some aliases automatically.
|
|
1040
|
|
|
737
|
|
|
1041
|
These are ALL parameter-less aliases"""
|
|
738
|
These are ALL parameter-less aliases"""
|
|
1042
|
for alias,cmd in self.auto_alias:
|
|
739
|
for alias,cmd in self.auto_alias:
|
|
1043
|
self.alias_table[alias] = (0,cmd)
|
|
740
|
self.alias_table[alias] = (0,cmd)
|
|
1044
|
|
|
741
|
|
|
1045
|
def alias_table_validate(self,verbose=0):
|
|
742
|
def alias_table_validate(self,verbose=0):
|
|
1046
|
"""Update information about the alias table.
|
|
743
|
"""Update information about the alias table.
|
|
1047
|
|
|
744
|
|
|
1048
|
In particular, make sure no Python keywords/builtins are in it."""
|
|
745
|
In particular, make sure no Python keywords/builtins are in it."""
|
|
1049
|
|
|
746
|
|
|
1050
|
no_alias = self.no_alias
|
|
747
|
no_alias = self.no_alias
|
|
1051
|
for k in self.alias_table.keys():
|
|
748
|
for k in self.alias_table.keys():
|
|
1052
|
if k in no_alias:
|
|
749
|
if k in no_alias:
|
|
1053
|
del self.alias_table[k]
|
|
750
|
del self.alias_table[k]
|
|
1054
|
if verbose:
|
|
751
|
if verbose:
|
|
1055
|
print ("Deleting alias <%s>, it's a Python "
|
|
752
|
print ("Deleting alias <%s>, it's a Python "
|
|
1056
|
"keyword or builtin." % k)
|
|
753
|
"keyword or builtin." % k)
|
|
1057
|
|
|
754
|
|
|
1058
|
def set_autoindent(self,value=None):
|
|
755
|
def set_autoindent(self,value=None):
|
|
1059
|
"""Set the autoindent flag, checking for readline support.
|
|
756
|
"""Set the autoindent flag, checking for readline support.
|
|
1060
|
|
|
757
|
|
|
1061
|
If called with no arguments, it acts as a toggle."""
|
|
758
|
If called with no arguments, it acts as a toggle."""
|
|
1062
|
|
|
759
|
|
|
1063
|
if not self.has_readline:
|
|
760
|
if not self.has_readline:
|
|
1064
|
if os.name == 'posix':
|
|
761
|
if os.name == 'posix':
|
|
1065
|
warn("The auto-indent feature requires the readline library")
|
|
762
|
warn("The auto-indent feature requires the readline library")
|
|
1066
|
self.autoindent = 0
|
|
763
|
self.autoindent = 0
|
|
1067
|
return
|
|
764
|
return
|
|
1068
|
if value is None:
|
|
765
|
if value is None:
|
|
1069
|
self.autoindent = not self.autoindent
|
|
766
|
self.autoindent = not self.autoindent
|
|
1070
|
else:
|
|
767
|
else:
|
|
1071
|
self.autoindent = value
|
|
768
|
self.autoindent = value
|
|
1072
|
|
|
769
|
|
|
1073
|
def rc_set_toggle(self,rc_field,value=None):
|
|
770
|
def rc_set_toggle(self,rc_field,value=None):
|
|
1074
|
"""Set or toggle a field in IPython's rc config. structure.
|
|
771
|
"""Set or toggle a field in IPython's rc config. structure.
|
|
1075
|
|
|
772
|
|
|
1076
|
If called with no arguments, it acts as a toggle.
|
|
773
|
If called with no arguments, it acts as a toggle.
|
|
1077
|
|
|
774
|
|
|
1078
|
If called with a non-existent field, the resulting AttributeError
|
|
775
|
If called with a non-existent field, the resulting AttributeError
|
|
1079
|
exception will propagate out."""
|
|
776
|
exception will propagate out."""
|
|
1080
|
|
|
777
|
|
|
1081
|
rc_val = getattr(self.rc,rc_field)
|
|
778
|
rc_val = getattr(self.rc,rc_field)
|
|
1082
|
if value is None:
|
|
779
|
if value is None:
|
|
1083
|
value = not rc_val
|
|
780
|
value = not rc_val
|
|
1084
|
setattr(self.rc,rc_field,value)
|
|
781
|
setattr(self.rc,rc_field,value)
|
|
1085
|
|
|
782
|
|
|
1086
|
def user_setup(self,ipythondir,rc_suffix,mode='install'):
|
|
783
|
def user_setup(self,ipythondir,rc_suffix,mode='install'):
|
|
1087
|
"""Install the user configuration directory.
|
|
784
|
"""Install the user configuration directory.
|
|
1088
|
|
|
785
|
|
|
1089
|
Can be called when running for the first time or to upgrade the user's
|
|
786
|
Can be called when running for the first time or to upgrade the user's
|
|
1090
|
.ipython/ directory with the mode parameter. Valid modes are 'install'
|
|
787
|
.ipython/ directory with the mode parameter. Valid modes are 'install'
|
|
1091
|
and 'upgrade'."""
|
|
788
|
and 'upgrade'."""
|
|
1092
|
|
|
789
|
|
|
1093
|
def wait():
|
|
790
|
def wait():
|
|
1094
|
try:
|
|
791
|
try:
|
|
1095
|
raw_input("Please press <RETURN> to start IPython.")
|
|
792
|
raw_input("Please press <RETURN> to start IPython.")
|
|
1096
|
except EOFError:
|
|
793
|
except EOFError:
|
|
1097
|
print >> Term.cout
|
|
794
|
print >> Term.cout
|
|
1098
|
print '*'*70
|
|
795
|
print '*'*70
|
|
1099
|
|
|
796
|
|
|
1100
|
cwd = os.getcwd() # remember where we started
|
|
797
|
cwd = os.getcwd() # remember where we started
|
|
1101
|
glb = glob.glob
|
|
798
|
glb = glob.glob
|
|
1102
|
print '*'*70
|
|
799
|
print '*'*70
|
|
1103
|
if mode == 'install':
|
|
800
|
if mode == 'install':
|
|
1104
|
print \
|
|
801
|
print \
|
|
1105
|
"""Welcome to IPython. I will try to create a personal configuration directory
|
|
802
|
"""Welcome to IPython. I will try to create a personal configuration directory
|
|
1106
|
where you can customize many aspects of IPython's functionality in:\n"""
|
|
803
|
where you can customize many aspects of IPython's functionality in:\n"""
|
|
1107
|
else:
|
|
804
|
else:
|
|
1108
|
print 'I am going to upgrade your configuration in:'
|
|
805
|
print 'I am going to upgrade your configuration in:'
|
|
1109
|
|
|
806
|
|
|
1110
|
print ipythondir
|
|
807
|
print ipythondir
|
|
1111
|
|
|
808
|
|
|
1112
|
rcdirend = os.path.join('IPython','UserConfig')
|
|
809
|
rcdirend = os.path.join('IPython','UserConfig')
|
|
1113
|
cfg = lambda d: os.path.join(d,rcdirend)
|
|
810
|
cfg = lambda d: os.path.join(d,rcdirend)
|
|
1114
|
try:
|
|
811
|
try:
|
|
1115
|
rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
|
|
812
|
rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
|
|
1116
|
except IOError:
|
|
813
|
except IOError:
|
|
1117
|
warning = """
|
|
814
|
warning = """
|
|
1118
|
Installation error. IPython's directory was not found.
|
|
815
|
Installation error. IPython's directory was not found.
|
|
1119
|
|
|
816
|
|
|
1120
|
Check the following:
|
|
817
|
Check the following:
|
|
1121
|
|
|
818
|
|
|
1122
|
The ipython/IPython directory should be in a directory belonging to your
|
|
819
|
The ipython/IPython directory should be in a directory belonging to your
|
|
1123
|
PYTHONPATH environment variable (that is, it should be in a directory
|
|
820
|
PYTHONPATH environment variable (that is, it should be in a directory
|
|
1124
|
belonging to sys.path). You can copy it explicitly there or just link to it.
|
|
821
|
belonging to sys.path). You can copy it explicitly there or just link to it.
|
|
1125
|
|
|
822
|
|
|
1126
|
IPython will proceed with builtin defaults.
|
|
823
|
IPython will proceed with builtin defaults.
|
|
1127
|
"""
|
|
824
|
"""
|
|
1128
|
warn(warning)
|
|
825
|
warn(warning)
|
|
1129
|
wait()
|
|
826
|
wait()
|
|
1130
|
return
|
|
827
|
return
|
|
1131
|
|
|
828
|
|
|
1132
|
if mode == 'install':
|
|
829
|
if mode == 'install':
|
|
1133
|
try:
|
|
830
|
try:
|
|
1134
|
shutil.copytree(rcdir,ipythondir)
|
|
831
|
shutil.copytree(rcdir,ipythondir)
|
|
1135
|
os.chdir(ipythondir)
|
|
832
|
os.chdir(ipythondir)
|
|
1136
|
rc_files = glb("ipythonrc*")
|
|
833
|
rc_files = glb("ipythonrc*")
|
|
1137
|
for rc_file in rc_files:
|
|
834
|
for rc_file in rc_files:
|
|
1138
|
os.rename(rc_file,rc_file+rc_suffix)
|
|
835
|
os.rename(rc_file,rc_file+rc_suffix)
|
|
1139
|
except:
|
|
836
|
except:
|
|
1140
|
warning = """
|
|
837
|
warning = """
|
|
1141
|
|
|
838
|
|
|
1142
|
There was a problem with the installation:
|
|
839
|
There was a problem with the installation:
|
|
1143
|
%s
|
|
840
|
%s
|
|
1144
|
Try to correct it or contact the developers if you think it's a bug.
|
|
841
|
Try to correct it or contact the developers if you think it's a bug.
|
|
1145
|
IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
|
|
842
|
IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
|
|
1146
|
warn(warning)
|
|
843
|
warn(warning)
|
|
1147
|
wait()
|
|
844
|
wait()
|
|
1148
|
return
|
|
845
|
return
|
|
1149
|
|
|
846
|
|
|
1150
|
elif mode == 'upgrade':
|
|
847
|
elif mode == 'upgrade':
|
|
1151
|
try:
|
|
848
|
try:
|
|
1152
|
os.chdir(ipythondir)
|
|
849
|
os.chdir(ipythondir)
|
|
1153
|
except:
|
|
850
|
except:
|
|
1154
|
print """
|
|
851
|
print """
|
|
1155
|
Can not upgrade: changing to directory %s failed. Details:
|
|
852
|
Can not upgrade: changing to directory %s failed. Details:
|
|
1156
|
%s
|
|
853
|
%s
|
|
1157
|
""" % (ipythondir,sys.exc_info()[1])
|
|
854
|
""" % (ipythondir,sys.exc_info()[1])
|
|
1158
|
wait()
|
|
855
|
wait()
|
|
1159
|
return
|
|
856
|
return
|
|
1160
|
else:
|
|
857
|
else:
|
|
1161
|
sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
|
|
858
|
sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
|
|
1162
|
for new_full_path in sources:
|
|
859
|
for new_full_path in sources:
|
|
1163
|
new_filename = os.path.basename(new_full_path)
|
|
860
|
new_filename = os.path.basename(new_full_path)
|
|
1164
|
if new_filename.startswith('ipythonrc'):
|
|
861
|
if new_filename.startswith('ipythonrc'):
|
|
1165
|
new_filename = new_filename + rc_suffix
|
|
862
|
new_filename = new_filename + rc_suffix
|
|
1166
|
# The config directory should only contain files, skip any
|
|
863
|
# The config directory should only contain files, skip any
|
|
1167
|
# directories which may be there (like CVS)
|
|
864
|
# directories which may be there (like CVS)
|
|
1168
|
if os.path.isdir(new_full_path):
|
|
865
|
if os.path.isdir(new_full_path):
|
|
1169
|
continue
|
|
866
|
continue
|
|
1170
|
if os.path.exists(new_filename):
|
|
867
|
if os.path.exists(new_filename):
|
|
1171
|
old_file = new_filename+'.old'
|
|
868
|
old_file = new_filename+'.old'
|
|
1172
|
if os.path.exists(old_file):
|
|
869
|
if os.path.exists(old_file):
|
|
1173
|
os.remove(old_file)
|
|
870
|
os.remove(old_file)
|
|
1174
|
os.rename(new_filename,old_file)
|
|
871
|
os.rename(new_filename,old_file)
|
|
1175
|
shutil.copy(new_full_path,new_filename)
|
|
872
|
shutil.copy(new_full_path,new_filename)
|
|
1176
|
else:
|
|
873
|
else:
|
|
1177
|
raise ValueError,'unrecognized mode for install:',`mode`
|
|
874
|
raise ValueError,'unrecognized mode for install:',`mode`
|
|
1178
|
|
|
875
|
|
|
1179
|
# Fix line-endings to those native to each platform in the config
|
|
876
|
# Fix line-endings to those native to each platform in the config
|
|
1180
|
# directory.
|
|
877
|
# directory.
|
|
1181
|
try:
|
|
878
|
try:
|
|
1182
|
os.chdir(ipythondir)
|
|
879
|
os.chdir(ipythondir)
|
|
1183
|
except:
|
|
880
|
except:
|
|
1184
|
print """
|
|
881
|
print """
|
|
1185
|
Problem: changing to directory %s failed.
|
|
882
|
Problem: changing to directory %s failed.
|
|
1186
|
Details:
|
|
883
|
Details:
|
|
1187
|
%s
|
|
884
|
%s
|
|
1188
|
|
|
885
|
|
|
1189
|
Some configuration files may have incorrect line endings. This should not
|
|
886
|
Some configuration files may have incorrect line endings. This should not
|
|
1190
|
cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
|
|
887
|
cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
|
|
1191
|
wait()
|
|
888
|
wait()
|
|
1192
|
else:
|
|
889
|
else:
|
|
1193
|
for fname in glb('ipythonrc*'):
|
|
890
|
for fname in glb('ipythonrc*'):
|
|
1194
|
try:
|
|
891
|
try:
|
|
1195
|
native_line_ends(fname,backup=0)
|
|
892
|
native_line_ends(fname,backup=0)
|
|
1196
|
except IOError:
|
|
893
|
except IOError:
|
|
1197
|
pass
|
|
894
|
pass
|
|
1198
|
|
|
895
|
|
|
1199
|
if mode == 'install':
|
|
896
|
if mode == 'install':
|
|
1200
|
print """
|
|
897
|
print """
|
|
1201
|
Successful installation!
|
|
898
|
Successful installation!
|
|
1202
|
|
|
899
|
|
|
1203
|
Please read the sections 'Initial Configuration' and 'Quick Tips' in the
|
|
900
|
Please read the sections 'Initial Configuration' and 'Quick Tips' in the
|
|
1204
|
IPython manual (there are both HTML and PDF versions supplied with the
|
|
901
|
IPython manual (there are both HTML and PDF versions supplied with the
|
|
1205
|
distribution) to make sure that your system environment is properly configured
|
|
902
|
distribution) to make sure that your system environment is properly configured
|
|
1206
|
to take advantage of IPython's features."""
|
|
903
|
to take advantage of IPython's features."""
|
|
1207
|
else:
|
|
904
|
else:
|
|
1208
|
print """
|
|
905
|
print """
|
|
1209
|
Successful upgrade!
|
|
906
|
Successful upgrade!
|
|
1210
|
|
|
907
|
|
|
1211
|
All files in your directory:
|
|
908
|
All files in your directory:
|
|
1212
|
%(ipythondir)s
|
|
909
|
%(ipythondir)s
|
|
1213
|
which would have been overwritten by the upgrade were backed up with a .old
|
|
910
|
which would have been overwritten by the upgrade were backed up with a .old
|
|
1214
|
extension. If you had made particular customizations in those files you may
|
|
911
|
extension. If you had made particular customizations in those files you may
|
|
1215
|
want to merge them back into the new files.""" % locals()
|
|
912
|
want to merge them back into the new files.""" % locals()
|
|
1216
|
wait()
|
|
913
|
wait()
|
|
1217
|
os.chdir(cwd)
|
|
914
|
os.chdir(cwd)
|
|
1218
|
# end user_setup()
|
|
915
|
# end user_setup()
|
|
1219
|
|
|
916
|
|
|
1220
|
def atexit_operations(self):
|
|
917
|
def atexit_operations(self):
|
|
1221
|
"""This will be executed at the time of exit.
|
|
918
|
"""This will be executed at the time of exit.
|
|
1222
|
|
|
919
|
|
|
1223
|
Saving of persistent data should be performed here. """
|
|
920
|
Saving of persistent data should be performed here. """
|
|
1224
|
|
|
921
|
|
|
1225
|
# input history
|
|
922
|
# input history
|
|
1226
|
self.savehist()
|
|
923
|
self.savehist()
|
|
1227
|
|
|
924
|
|
|
1228
|
# Cleanup all tempfiles left around
|
|
925
|
# Cleanup all tempfiles left around
|
|
1229
|
for tfile in self.tempfiles:
|
|
926
|
for tfile in self.tempfiles:
|
|
1230
|
try:
|
|
927
|
try:
|
|
1231
|
os.unlink(tfile)
|
|
928
|
os.unlink(tfile)
|
|
1232
|
except OSError:
|
|
929
|
except OSError:
|
|
1233
|
pass
|
|
930
|
pass
|
|
1234
|
|
|
931
|
|
|
1235
|
# save the "persistent data" catch-all dictionary
|
|
932
|
# save the "persistent data" catch-all dictionary
|
|
1236
|
try:
|
|
933
|
try:
|
|
1237
|
pickle.dump(self.persist, open(self.persist_fname,"w"))
|
|
934
|
pickle.dump(self.persist, open(self.persist_fname,"w"))
|
|
1238
|
except:
|
|
935
|
except:
|
|
1239
|
print "*** ERROR *** persistent data saving failed."
|
|
936
|
print "*** ERROR *** persistent data saving failed."
|
|
1240
|
|
|
937
|
|
|
1241
|
def savehist(self):
|
|
938
|
def savehist(self):
|
|
1242
|
"""Save input history to a file (via readline library)."""
|
|
939
|
"""Save input history to a file (via readline library)."""
|
|
1243
|
try:
|
|
940
|
try:
|
|
1244
|
self.readline.write_history_file(self.histfile)
|
|
941
|
self.readline.write_history_file(self.histfile)
|
|
1245
|
except:
|
|
942
|
except:
|
|
1246
|
print 'Unable to save IPython command history to file: ' + \
|
|
943
|
print 'Unable to save IPython command history to file: ' + \
|
|
1247
|
`self.histfile`
|
|
944
|
`self.histfile`
|
|
1248
|
|
|
945
|
|
|
1249
|
def pre_readline(self):
|
|
946
|
def pre_readline(self):
|
|
1250
|
"""readline hook to be used at the start of each line.
|
|
947
|
"""readline hook to be used at the start of each line.
|
|
1251
|
|
|
948
|
|
|
1252
|
Currently it handles auto-indent only."""
|
|
949
|
Currently it handles auto-indent only."""
|
|
1253
|
|
|
950
|
|
|
1254
|
self.readline.insert_text(' '* self.readline_indent)
|
|
951
|
self.readline.insert_text(' '* self.readline_indent)
|
|
1255
|
|
|
952
|
|
|
1256
|
def init_readline(self):
|
|
953
|
def init_readline(self):
|
|
1257
|
"""Command history completion/saving/reloading."""
|
|
954
|
"""Command history completion/saving/reloading."""
|
|
1258
|
try:
|
|
955
|
try:
|
|
1259
|
import readline
|
|
956
|
import readline
|
|
1260
|
self.Completer = MagicCompleter(self,
|
|
957
|
except ImportError:
|
|
1261
|
self.user_ns,
|
|
|
|
|
1262
|
self.user_global_ns,
|
|
|
|
|
1263
|
self.rc.readline_omit__names,
|
|
|
|
|
1264
|
self.alias_table)
|
|
|
|
|
1265
|
except ImportError,NameError:
|
|
|
|
|
1266
|
# If FlexCompleter failed to import, MagicCompleter won't be
|
|
|
|
|
1267
|
# defined. This can happen because of a problem with readline
|
|
|
|
|
1268
|
self.has_readline = 0
|
|
958
|
self.has_readline = 0
|
|
|
|
|
959
|
self.readline = None
|
|
1269
|
# no point in bugging windows users with this every time:
|
|
960
|
# no point in bugging windows users with this every time:
|
|
1270
|
if os.name == 'posix':
|
|
961
|
if os.name == 'posix':
|
|
1271
|
warn('Readline services not available on this platform.')
|
|
962
|
warn('Readline services not available on this platform.')
|
|
1272
|
else:
|
|
963
|
else:
|
|
1273
|
import atexit
|
|
964
|
import atexit
|
|
|
|
|
965
|
from IPython.completer import IPCompleter
|
|
|
|
|
966
|
self.Completer = IPCompleter(self,
|
|
|
|
|
967
|
self.user_ns,
|
|
|
|
|
968
|
self.user_global_ns,
|
|
|
|
|
969
|
self.rc.readline_omit__names,
|
|
|
|
|
970
|
self.alias_table)
|
|
1274
|
|
|
971
|
|
|
1275
|
# Platform-specific configuration
|
|
972
|
# Platform-specific configuration
|
|
1276
|
if os.name == 'nt':
|
|
973
|
if os.name == 'nt':
|
|
1277
|
# readline under Windows modifies the default exit behavior
|
|
|
|
|
1278
|
# from being Ctrl-Z/Return to the Unix Ctrl-D one.
|
|
|
|
|
1279
|
__builtin__.exit = __builtin__.quit = \
|
|
|
|
|
1280
|
('Use Ctrl-D (i.e. EOF) to exit. '
|
|
|
|
|
1281
|
'Use %Exit or %Quit to exit without confirmation.')
|
|
|
|
|
1282
|
self.readline_startup_hook = readline.set_pre_input_hook
|
|
974
|
self.readline_startup_hook = readline.set_pre_input_hook
|
|
1283
|
else:
|
|
975
|
else:
|
|
1284
|
self.readline_startup_hook = readline.set_startup_hook
|
|
976
|
self.readline_startup_hook = readline.set_startup_hook
|
|
1285
|
|
|
977
|
|
|
1286
|
# Load user's initrc file (readline config)
|
|
978
|
# Load user's initrc file (readline config)
|
|
1287
|
inputrc_name = os.environ.get('INPUTRC')
|
|
979
|
inputrc_name = os.environ.get('INPUTRC')
|
|
1288
|
if inputrc_name is None:
|
|
980
|
if inputrc_name is None:
|
|
1289
|
home_dir = get_home_dir()
|
|
981
|
home_dir = get_home_dir()
|
|
1290
|
if home_dir is not None:
|
|
982
|
if home_dir is not None:
|
|
1291
|
inputrc_name = os.path.join(home_dir,'.inputrc')
|
|
983
|
inputrc_name = os.path.join(home_dir,'.inputrc')
|
|
1292
|
if os.path.isfile(inputrc_name):
|
|
984
|
if os.path.isfile(inputrc_name):
|
|
1293
|
try:
|
|
985
|
try:
|
|
1294
|
readline.read_init_file(inputrc_name)
|
|
986
|
readline.read_init_file(inputrc_name)
|
|
1295
|
except:
|
|
987
|
except:
|
|
1296
|
warn('Problems reading readline initialization file <%s>'
|
|
988
|
warn('Problems reading readline initialization file <%s>'
|
|
1297
|
% inputrc_name)
|
|
989
|
% inputrc_name)
|
|
1298
|
|
|
990
|
|
|
1299
|
self.has_readline = 1
|
|
991
|
self.has_readline = 1
|
|
1300
|
self.readline = readline
|
|
992
|
self.readline = readline
|
|
1301
|
self.readline_indent = 0 # for auto-indenting via readline
|
|
993
|
self.readline_indent = 0 # for auto-indenting via readline
|
|
1302
|
# save this in sys so embedded copies can restore it properly
|
|
994
|
# save this in sys so embedded copies can restore it properly
|
|
1303
|
sys.ipcompleter = self.Completer.complete
|
|
995
|
sys.ipcompleter = self.Completer.complete
|
|
1304
|
readline.set_completer(self.Completer.complete)
|
|
996
|
readline.set_completer(self.Completer.complete)
|
|
1305
|
|
|
997
|
|
|
1306
|
# Configure readline according to user's prefs
|
|
998
|
# Configure readline according to user's prefs
|
|
1307
|
for rlcommand in self.rc.readline_parse_and_bind:
|
|
999
|
for rlcommand in self.rc.readline_parse_and_bind:
|
|
1308
|
readline.parse_and_bind(rlcommand)
|
|
1000
|
readline.parse_and_bind(rlcommand)
|
|
1309
|
|
|
1001
|
|
|
1310
|
# remove some chars from the delimiters list
|
|
1002
|
# remove some chars from the delimiters list
|
|
1311
|
delims = readline.get_completer_delims()
|
|
1003
|
delims = readline.get_completer_delims()
|
|
1312
|
delims = delims.translate(string._idmap,
|
|
1004
|
delims = delims.translate(string._idmap,
|
|
1313
|
self.rc.readline_remove_delims)
|
|
1005
|
self.rc.readline_remove_delims)
|
|
1314
|
readline.set_completer_delims(delims)
|
|
1006
|
readline.set_completer_delims(delims)
|
|
1315
|
# otherwise we end up with a monster history after a while:
|
|
1007
|
# otherwise we end up with a monster history after a while:
|
|
1316
|
readline.set_history_length(1000)
|
|
1008
|
readline.set_history_length(1000)
|
|
1317
|
try:
|
|
1009
|
try:
|
|
1318
|
#print '*** Reading readline history' # dbg
|
|
1010
|
#print '*** Reading readline history' # dbg
|
|
1319
|
readline.read_history_file(self.histfile)
|
|
1011
|
readline.read_history_file(self.histfile)
|
|
1320
|
except IOError:
|
|
1012
|
except IOError:
|
|
1321
|
pass # It doesn't exist yet.
|
|
1013
|
pass # It doesn't exist yet.
|
|
1322
|
|
|
1014
|
|
|
1323
|
atexit.register(self.atexit_operations)
|
|
1015
|
atexit.register(self.atexit_operations)
|
|
1324
|
del atexit
|
|
1016
|
del atexit
|
|
1325
|
|
|
1017
|
|
|
1326
|
# Configure auto-indent for all platforms
|
|
1018
|
# Configure auto-indent for all platforms
|
|
1327
|
self.set_autoindent(self.rc.autoindent)
|
|
1019
|
self.set_autoindent(self.rc.autoindent)
|
|
1328
|
|
|
1020
|
|
|
1329
|
def showsyntaxerror(self, filename=None):
|
|
1021
|
def showsyntaxerror(self, filename=None):
|
|
1330
|
"""Display the syntax error that just occurred.
|
|
1022
|
"""Display the syntax error that just occurred.
|
|
1331
|
|
|
1023
|
|
|
1332
|
This doesn't display a stack trace because there isn't one.
|
|
1024
|
This doesn't display a stack trace because there isn't one.
|
|
1333
|
|
|
1025
|
|
|
1334
|
If a filename is given, it is stuffed in the exception instead
|
|
1026
|
If a filename is given, it is stuffed in the exception instead
|
|
1335
|
of what was there before (because Python's parser always uses
|
|
1027
|
of what was there before (because Python's parser always uses
|
|
1336
|
"<string>" when reading from a string).
|
|
1028
|
"<string>" when reading from a string).
|
|
1337
|
"""
|
|
1029
|
"""
|
|
1338
|
type, value, sys.last_traceback = sys.exc_info()
|
|
1030
|
type, value, sys.last_traceback = sys.exc_info()
|
|
1339
|
sys.last_type = type
|
|
1031
|
sys.last_type = type
|
|
1340
|
sys.last_value = value
|
|
1032
|
sys.last_value = value
|
|
1341
|
if filename and type is SyntaxError:
|
|
1033
|
if filename and type is SyntaxError:
|
|
1342
|
# Work hard to stuff the correct filename in the exception
|
|
1034
|
# Work hard to stuff the correct filename in the exception
|
|
1343
|
try:
|
|
1035
|
try:
|
|
1344
|
msg, (dummy_filename, lineno, offset, line) = value
|
|
1036
|
msg, (dummy_filename, lineno, offset, line) = value
|
|
1345
|
except:
|
|
1037
|
except:
|
|
1346
|
# Not the format we expect; leave it alone
|
|
1038
|
# Not the format we expect; leave it alone
|
|
1347
|
pass
|
|
1039
|
pass
|
|
1348
|
else:
|
|
1040
|
else:
|
|
1349
|
# Stuff in the right filename
|
|
1041
|
# Stuff in the right filename
|
|
1350
|
try:
|
|
1042
|
try:
|
|
1351
|
# Assume SyntaxError is a class exception
|
|
1043
|
# Assume SyntaxError is a class exception
|
|
1352
|
value = SyntaxError(msg, (filename, lineno, offset, line))
|
|
1044
|
value = SyntaxError(msg, (filename, lineno, offset, line))
|
|
1353
|
except:
|
|
1045
|
except:
|
|
1354
|
# If that failed, assume SyntaxError is a string
|
|
1046
|
# If that failed, assume SyntaxError is a string
|
|
1355
|
value = msg, (filename, lineno, offset, line)
|
|
1047
|
value = msg, (filename, lineno, offset, line)
|
|
1356
|
self.SyntaxTB(type,value,[])
|
|
1048
|
self.SyntaxTB(type,value,[])
|
|
1357
|
|
|
1049
|
|
|
1358
|
def debugger(self):
|
|
1050
|
def debugger(self):
|
|
1359
|
"""Call the pdb debugger."""
|
|
1051
|
"""Call the pdb debugger."""
|
|
1360
|
|
|
1052
|
|
|
1361
|
if not self.rc.pdb:
|
|
1053
|
if not self.rc.pdb:
|
|
1362
|
return
|
|
1054
|
return
|
|
1363
|
pdb.pm()
|
|
1055
|
pdb.pm()
|
|
1364
|
|
|
1056
|
|
|
1365
|
def showtraceback(self,exc_tuple = None,filename=None):
|
|
1057
|
def showtraceback(self,exc_tuple = None,filename=None):
|
|
1366
|
"""Display the exception that just occurred."""
|
|
1058
|
"""Display the exception that just occurred."""
|
|
1367
|
|
|
1059
|
|
|
1368
|
# Though this won't be called by syntax errors in the input line,
|
|
1060
|
# Though this won't be called by syntax errors in the input line,
|
|
1369
|
# there may be SyntaxError cases whith imported code.
|
|
1061
|
# there may be SyntaxError cases whith imported code.
|
|
1370
|
if exc_tuple is None:
|
|
1062
|
if exc_tuple is None:
|
|
1371
|
type, value, tb = sys.exc_info()
|
|
1063
|
type, value, tb = sys.exc_info()
|
|
1372
|
else:
|
|
1064
|
else:
|
|
1373
|
type, value, tb = exc_tuple
|
|
1065
|
type, value, tb = exc_tuple
|
|
1374
|
if type is SyntaxError:
|
|
1066
|
if type is SyntaxError:
|
|
1375
|
self.showsyntaxerror(filename)
|
|
1067
|
self.showsyntaxerror(filename)
|
|
1376
|
else:
|
|
1068
|
else:
|
|
1377
|
sys.last_type = type
|
|
1069
|
sys.last_type = type
|
|
1378
|
sys.last_value = value
|
|
1070
|
sys.last_value = value
|
|
1379
|
sys.last_traceback = tb
|
|
1071
|
sys.last_traceback = tb
|
|
1380
|
self.InteractiveTB()
|
|
1072
|
self.InteractiveTB()
|
|
1381
|
if self.InteractiveTB.call_pdb and self.has_readline:
|
|
1073
|
if self.InteractiveTB.call_pdb and self.has_readline:
|
|
1382
|
# pdb mucks up readline, fix it back
|
|
1074
|
# pdb mucks up readline, fix it back
|
|
1383
|
self.readline.set_completer(self.Completer.complete)
|
|
1075
|
self.readline.set_completer(self.Completer.complete)
|
|
1384
|
|
|
1076
|
|
|
1385
|
def update_cache(self, line):
|
|
1077
|
def update_cache(self, line):
|
|
1386
|
"""puts line into cache"""
|
|
1078
|
"""puts line into cache"""
|
|
1387
|
self.inputcache.insert(0, line) # This copies the cache every time ... :-(
|
|
1079
|
self.inputcache.insert(0, line) # This copies the cache every time ... :-(
|
|
1388
|
if len(self.inputcache) >= self.CACHELENGTH:
|
|
1080
|
if len(self.inputcache) >= self.CACHELENGTH:
|
|
1389
|
self.inputcache.pop() # This not :-)
|
|
1081
|
self.inputcache.pop() # This doesn't :-)
|
|
1390
|
|
|
1082
|
|
|
1391
|
def mainloop(self,banner=None):
|
|
1083
|
def mainloop(self,banner=None):
|
|
1392
|
"""Creates the local namespace and starts the mainloop.
|
|
1084
|
"""Creates the local namespace and starts the mainloop.
|
|
1393
|
|
|
1085
|
|
|
1394
|
If an optional banner argument is given, it will override the
|
|
1086
|
If an optional banner argument is given, it will override the
|
|
1395
|
internally created default banner."""
|
|
1087
|
internally created default banner."""
|
|
1396
|
|
|
1088
|
|
|
1397
|
if self.rc.c: # Emulate Python's -c option
|
|
1089
|
if self.rc.c: # Emulate Python's -c option
|
|
1398
|
self.exec_init_cmd()
|
|
1090
|
self.exec_init_cmd()
|
|
1399
|
if banner is None:
|
|
1091
|
if banner is None:
|
|
1400
|
if self.rc.banner:
|
|
1092
|
if self.rc.banner:
|
|
1401
|
banner = self.BANNER+self.banner2
|
|
1093
|
banner = self.BANNER+self.banner2
|
|
1402
|
else:
|
|
1094
|
else:
|
|
1403
|
banner = ''
|
|
1095
|
banner = ''
|
|
1404
|
self.interact(banner)
|
|
1096
|
self.interact(banner)
|
|
1405
|
|
|
1097
|
|
|
1406
|
def exec_init_cmd(self):
|
|
1098
|
def exec_init_cmd(self):
|
|
1407
|
"""Execute a command given at the command line.
|
|
1099
|
"""Execute a command given at the command line.
|
|
1408
|
|
|
1100
|
|
|
1409
|
This emulates Python's -c option."""
|
|
1101
|
This emulates Python's -c option."""
|
|
1410
|
|
|
1102
|
|
|
1411
|
sys.argv = ['-c']
|
|
1103
|
sys.argv = ['-c']
|
|
1412
|
self.push(self.rc.c)
|
|
1104
|
self.push(self.rc.c)
|
|
1413
|
|
|
1105
|
|
|
1414
|
def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
|
|
1106
|
def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
|
|
1415
|
"""Embeds IPython into a running python program.
|
|
1107
|
"""Embeds IPython into a running python program.
|
|
1416
|
|
|
1108
|
|
|
1417
|
Input:
|
|
1109
|
Input:
|
|
1418
|
|
|
1110
|
|
|
1419
|
- header: An optional header message can be specified.
|
|
1111
|
- header: An optional header message can be specified.
|
|
1420
|
|
|
1112
|
|
|
1421
|
- local_ns, global_ns: working namespaces. If given as None, the
|
|
1113
|
- local_ns, global_ns: working namespaces. If given as None, the
|
|
1422
|
IPython-initialized one is updated with __main__.__dict__, so that
|
|
1114
|
IPython-initialized one is updated with __main__.__dict__, so that
|
|
1423
|
program variables become visible but user-specific configuration
|
|
1115
|
program variables become visible but user-specific configuration
|
|
1424
|
remains possible.
|
|
1116
|
remains possible.
|
|
1425
|
|
|
1117
|
|
|
1426
|
- stack_depth: specifies how many levels in the stack to go to
|
|
1118
|
- stack_depth: specifies how many levels in the stack to go to
|
|
1427
|
looking for namespaces (when local_ns and global_ns are None). This
|
|
1119
|
looking for namespaces (when local_ns and global_ns are None). This
|
|
1428
|
allows an intermediate caller to make sure that this function gets
|
|
1120
|
allows an intermediate caller to make sure that this function gets
|
|
1429
|
the namespace from the intended level in the stack. By default (0)
|
|
1121
|
the namespace from the intended level in the stack. By default (0)
|
|
1430
|
it will get its locals and globals from the immediate caller.
|
|
1122
|
it will get its locals and globals from the immediate caller.
|
|
1431
|
|
|
1123
|
|
|
1432
|
Warning: it's possible to use this in a program which is being run by
|
|
1124
|
Warning: it's possible to use this in a program which is being run by
|
|
1433
|
IPython itself (via %run), but some funny things will happen (a few
|
|
1125
|
IPython itself (via %run), but some funny things will happen (a few
|
|
1434
|
globals get overwritten). In the future this will be cleaned up, as
|
|
1126
|
globals get overwritten). In the future this will be cleaned up, as
|
|
1435
|
there is no fundamental reason why it can't work perfectly."""
|
|
1127
|
there is no fundamental reason why it can't work perfectly."""
|
|
1436
|
|
|
1128
|
|
|
1437
|
# Get locals and globals from caller
|
|
1129
|
# Get locals and globals from caller
|
|
1438
|
if local_ns is None or global_ns is None:
|
|
1130
|
if local_ns is None or global_ns is None:
|
|
1439
|
call_frame = sys._getframe(stack_depth).f_back
|
|
1131
|
call_frame = sys._getframe(stack_depth).f_back
|
|
1440
|
|
|
1132
|
|
|
1441
|
if local_ns is None:
|
|
1133
|
if local_ns is None:
|
|
1442
|
local_ns = call_frame.f_locals
|
|
1134
|
local_ns = call_frame.f_locals
|
|
1443
|
if global_ns is None:
|
|
1135
|
if global_ns is None:
|
|
1444
|
global_ns = call_frame.f_globals
|
|
1136
|
global_ns = call_frame.f_globals
|
|
1445
|
|
|
1137
|
|
|
1446
|
# Update namespaces and fire up interpreter
|
|
1138
|
# Update namespaces and fire up interpreter
|
|
1447
|
self.user_ns = local_ns
|
|
1139
|
self.user_ns = local_ns
|
|
1448
|
self.user_global_ns = global_ns
|
|
1140
|
self.user_global_ns = global_ns
|
|
1449
|
|
|
1141
|
|
|
1450
|
# Patch for global embedding to make sure that things don't overwrite
|
|
1142
|
# Patch for global embedding to make sure that things don't overwrite
|
|
1451
|
# user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
|
|
1143
|
# user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
|
|
1452
|
# FIXME. Test this a bit more carefully (the if.. is new)
|
|
1144
|
# FIXME. Test this a bit more carefully (the if.. is new)
|
|
1453
|
if local_ns is None and global_ns is None:
|
|
1145
|
if local_ns is None and global_ns is None:
|
|
1454
|
self.user_global_ns.update(__main__.__dict__)
|
|
1146
|
self.user_global_ns.update(__main__.__dict__)
|
|
1455
|
|
|
1147
|
|
|
1456
|
# make sure the tab-completer has the correct frame information, so it
|
|
1148
|
# make sure the tab-completer has the correct frame information, so it
|
|
1457
|
# actually completes using the frame's locals/globals
|
|
1149
|
# actually completes using the frame's locals/globals
|
|
1458
|
self.set_completer_frame(call_frame)
|
|
1150
|
self.set_completer_frame(call_frame)
|
|
1459
|
|
|
1151
|
|
|
1460
|
self.interact(header)
|
|
1152
|
self.interact(header)
|
|
1461
|
|
|
1153
|
|
|
1462
|
def interact(self, banner=None):
|
|
1154
|
def interact(self, banner=None):
|
|
1463
|
"""Closely emulate the interactive Python console.
|
|
1155
|
"""Closely emulate the interactive Python console.
|
|
1464
|
|
|
1156
|
|
|
1465
|
The optional banner argument specify the banner to print
|
|
1157
|
The optional banner argument specify the banner to print
|
|
1466
|
before the first interaction; by default it prints a banner
|
|
1158
|
before the first interaction; by default it prints a banner
|
|
1467
|
similar to the one printed by the real Python interpreter,
|
|
1159
|
similar to the one printed by the real Python interpreter,
|
|
1468
|
followed by the current class name in parentheses (so as not
|
|
1160
|
followed by the current class name in parentheses (so as not
|
|
1469
|
to confuse this with the real interpreter -- since it's so
|
|
1161
|
to confuse this with the real interpreter -- since it's so
|
|
1470
|
close!).
|
|
1162
|
close!).
|
|
1471
|
|
|
1163
|
|
|
1472
|
"""
|
|
1164
|
"""
|
|
1473
|
cprt = 'Type "copyright", "credits" or "license" for more information.'
|
|
1165
|
cprt = 'Type "copyright", "credits" or "license" for more information.'
|
|
1474
|
if banner is None:
|
|
1166
|
if banner is None:
|
|
1475
|
self.write("Python %s on %s\n%s\n(%s)\n" %
|
|
1167
|
self.write("Python %s on %s\n%s\n(%s)\n" %
|
|
1476
|
(sys.version, sys.platform, cprt,
|
|
1168
|
(sys.version, sys.platform, cprt,
|
|
1477
|
self.__class__.__name__))
|
|
1169
|
self.__class__.__name__))
|
|
1478
|
else:
|
|
1170
|
else:
|
|
1479
|
self.write(banner)
|
|
1171
|
self.write(banner)
|
|
1480
|
|
|
1172
|
|
|
1481
|
more = 0
|
|
1173
|
more = 0
|
|
1482
|
|
|
1174
|
|
|
1483
|
# Mark activity in the builtins
|
|
1175
|
# Mark activity in the builtins
|
|
1484
|
__builtin__.__dict__['__IPYTHON__active'] += 1
|
|
1176
|
__builtin__.__dict__['__IPYTHON__active'] += 1
|
|
1485
|
|
|
1177
|
|
|
1486
|
# compiled regexps for autoindent management
|
|
1178
|
# compiled regexps for autoindent management
|
|
1487
|
ini_spaces_re = re.compile(r'^(\s+)')
|
|
1179
|
ini_spaces_re = re.compile(r'^(\s+)')
|
|
1488
|
dedent_re = re.compile(r'^\s+raise|^\s+return')
|
|
1180
|
dedent_re = re.compile(r'^\s+raise|^\s+return')
|
|
1489
|
|
|
1181
|
|
|
1490
|
# exit_now is set by a call to %Exit or %Quit
|
|
1182
|
# exit_now is set by a call to %Exit or %Quit
|
|
1491
|
while not self.exit_now:
|
|
1183
|
while not self.exit_now:
|
|
1492
|
try:
|
|
1184
|
try:
|
|
1493
|
if more:
|
|
1185
|
if more:
|
|
1494
|
prompt = self.outputcache.prompt2
|
|
1186
|
prompt = self.outputcache.prompt2
|
|
1495
|
if self.autoindent:
|
|
1187
|
if self.autoindent:
|
|
1496
|
self.readline_startup_hook(self.pre_readline)
|
|
1188
|
self.readline_startup_hook(self.pre_readline)
|
|
1497
|
else:
|
|
1189
|
else:
|
|
1498
|
prompt = self.outputcache.prompt1
|
|
1190
|
prompt = self.outputcache.prompt1
|
|
1499
|
try:
|
|
1191
|
try:
|
|
1500
|
line = self.raw_input(prompt,more)
|
|
1192
|
line = self.raw_input(prompt,more)
|
|
1501
|
if self.autoindent:
|
|
1193
|
if self.autoindent:
|
|
1502
|
self.readline_startup_hook(None)
|
|
1194
|
self.readline_startup_hook(None)
|
|
1503
|
except EOFError:
|
|
1195
|
except EOFError:
|
|
1504
|
if self.autoindent:
|
|
1196
|
if self.autoindent:
|
|
1505
|
self.readline_startup_hook(None)
|
|
1197
|
self.readline_startup_hook(None)
|
|
1506
|
self.write("\n")
|
|
1198
|
self.write("\n")
|
|
1507
|
if self.rc.confirm_exit:
|
|
1199
|
self.exit()
|
|
1508
|
if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
|
|
1200
|
except IPythonExit:
|
|
1509
|
break
|
|
1201
|
self.exit()
|
|
1510
|
else:
|
|
|
|
|
1511
|
break
|
|
|
|
|
1512
|
else:
|
|
1202
|
else:
|
|
1513
|
more = self.push(line)
|
|
1203
|
more = self.push(line)
|
|
1514
|
# Auto-indent management
|
|
1204
|
# Auto-indent management
|
|
1515
|
if self.autoindent:
|
|
1205
|
if self.autoindent:
|
|
1516
|
if line:
|
|
1206
|
if line:
|
|
1517
|
ini_spaces = ini_spaces_re.match(line)
|
|
1207
|
ini_spaces = ini_spaces_re.match(line)
|
|
1518
|
if ini_spaces:
|
|
1208
|
if ini_spaces:
|
|
1519
|
nspaces = ini_spaces.end()
|
|
1209
|
nspaces = ini_spaces.end()
|
|
1520
|
else:
|
|
1210
|
else:
|
|
1521
|
nspaces = 0
|
|
1211
|
nspaces = 0
|
|
1522
|
self.readline_indent = nspaces
|
|
1212
|
self.readline_indent = nspaces
|
|
1523
|
|
|
1213
|
|
|
1524
|
if line[-1] == ':':
|
|
1214
|
if line[-1] == ':':
|
|
1525
|
self.readline_indent += 4
|
|
1215
|
self.readline_indent += 4
|
|
1526
|
elif dedent_re.match(line):
|
|
1216
|
elif dedent_re.match(line):
|
|
1527
|
self.readline_indent -= 4
|
|
1217
|
self.readline_indent -= 4
|
|
1528
|
else:
|
|
1218
|
else:
|
|
1529
|
self.readline_indent = 0
|
|
1219
|
self.readline_indent = 0
|
|
1530
|
|
|
1220
|
|
|
1531
|
except KeyboardInterrupt:
|
|
1221
|
except KeyboardInterrupt:
|
|
1532
|
self.write("\nKeyboardInterrupt\n")
|
|
1222
|
self.write("\nKeyboardInterrupt\n")
|
|
1533
|
self.resetbuffer()
|
|
1223
|
self.resetbuffer()
|
|
1534
|
more = 0
|
|
1224
|
more = 0
|
|
1535
|
# keep cache in sync with the prompt counter:
|
|
1225
|
# keep cache in sync with the prompt counter:
|
|
1536
|
self.outputcache.prompt_count -= 1
|
|
1226
|
self.outputcache.prompt_count -= 1
|
|
1537
|
|
|
1227
|
|
|
1538
|
if self.autoindent:
|
|
1228
|
if self.autoindent:
|
|
1539
|
self.readline_indent = 0
|
|
1229
|
self.readline_indent = 0
|
|
1540
|
|
|
1230
|
|
|
1541
|
except bdb.BdbQuit:
|
|
1231
|
except bdb.BdbQuit:
|
|
1542
|
warn("The Python debugger has exited with a BdbQuit exception.\n"
|
|
1232
|
warn("The Python debugger has exited with a BdbQuit exception.\n"
|
|
1543
|
"Because of how pdb handles the stack, it is impossible\n"
|
|
1233
|
"Because of how pdb handles the stack, it is impossible\n"
|
|
1544
|
"for IPython to properly format this particular exception.\n"
|
|
1234
|
"for IPython to properly format this particular exception.\n"
|
|
1545
|
"IPython will resume normal operation.")
|
|
1235
|
"IPython will resume normal operation.")
|
|
1546
|
|
|
1236
|
|
|
1547
|
# We are off again...
|
|
1237
|
# We are off again...
|
|
1548
|
__builtin__.__dict__['__IPYTHON__active'] -= 1
|
|
1238
|
__builtin__.__dict__['__IPYTHON__active'] -= 1
|
|
1549
|
|
|
1239
|
|
|
1550
|
def excepthook(self, type, value, tb):
|
|
1240
|
def excepthook(self, type, value, tb):
|
|
1551
|
"""One more defense for GUI apps that call sys.excepthook.
|
|
1241
|
"""One more defense for GUI apps that call sys.excepthook.
|
|
1552
|
|
|
1242
|
|
|
1553
|
GUI frameworks like wxPython trap exceptions and call
|
|
1243
|
GUI frameworks like wxPython trap exceptions and call
|
|
1554
|
sys.excepthook themselves. I guess this is a feature that
|
|
1244
|
sys.excepthook themselves. I guess this is a feature that
|
|
1555
|
enables them to keep running after exceptions that would
|
|
1245
|
enables them to keep running after exceptions that would
|
|
1556
|
otherwise kill their mainloop. This is a bother for IPython
|
|
1246
|
otherwise kill their mainloop. This is a bother for IPython
|
|
1557
|
which excepts to catch all of the program exceptions with a try:
|
|
1247
|
which excepts to catch all of the program exceptions with a try:
|
|
1558
|
except: statement.
|
|
1248
|
except: statement.
|
|
1559
|
|
|
1249
|
|
|
1560
|
Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
|
|
1250
|
Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
|
|
1561
|
any app directly invokes sys.excepthook, it will look to the user like
|
|
1251
|
any app directly invokes sys.excepthook, it will look to the user like
|
|
1562
|
IPython crashed. In order to work around this, we can disable the
|
|
1252
|
IPython crashed. In order to work around this, we can disable the
|
|
1563
|
CrashHandler and replace it with this excepthook instead, which prints a
|
|
1253
|
CrashHandler and replace it with this excepthook instead, which prints a
|
|
1564
|
regular traceback using our InteractiveTB. In this fashion, apps which
|
|
1254
|
regular traceback using our InteractiveTB. In this fashion, apps which
|
|
1565
|
call sys.excepthook will generate a regular-looking exception from
|
|
1255
|
call sys.excepthook will generate a regular-looking exception from
|
|
1566
|
IPython, and the CrashHandler will only be triggered by real IPython
|
|
1256
|
IPython, and the CrashHandler will only be triggered by real IPython
|
|
1567
|
crashes.
|
|
1257
|
crashes.
|
|
1568
|
|
|
1258
|
|
|
1569
|
This hook should be used sparingly, only in places which are not likely
|
|
1259
|
This hook should be used sparingly, only in places which are not likely
|
|
1570
|
to be true IPython errors.
|
|
1260
|
to be true IPython errors.
|
|
1571
|
"""
|
|
1261
|
"""
|
|
1572
|
|
|
1262
|
|
|
1573
|
self.InteractiveTB(type, value, tb, tb_offset=0)
|
|
1263
|
self.InteractiveTB(type, value, tb, tb_offset=0)
|
|
1574
|
if self.InteractiveTB.call_pdb and self.has_readline:
|
|
1264
|
if self.InteractiveTB.call_pdb and self.has_readline:
|
|
1575
|
self.readline.set_completer(self.Completer.complete)
|
|
1265
|
self.readline.set_completer(self.Completer.complete)
|
|
1576
|
|
|
1266
|
|
|
1577
|
def call_alias(self,alias,rest=''):
|
|
1267
|
def call_alias(self,alias,rest=''):
|
|
1578
|
"""Call an alias given its name and the rest of the line.
|
|
1268
|
"""Call an alias given its name and the rest of the line.
|
|
1579
|
|
|
1269
|
|
|
1580
|
This function MUST be given a proper alias, because it doesn't make
|
|
1270
|
This function MUST be given a proper alias, because it doesn't make
|
|
1581
|
any checks when looking up into the alias table. The caller is
|
|
1271
|
any checks when looking up into the alias table. The caller is
|
|
1582
|
responsible for invoking it only with a valid alias."""
|
|
1272
|
responsible for invoking it only with a valid alias."""
|
|
1583
|
|
|
1273
|
|
|
1584
|
#print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
|
|
1274
|
#print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
|
|
1585
|
nargs,cmd = self.alias_table[alias]
|
|
1275
|
nargs,cmd = self.alias_table[alias]
|
|
1586
|
# Expand the %l special to be the user's input line
|
|
1276
|
# Expand the %l special to be the user's input line
|
|
1587
|
if cmd.find('%l') >= 0:
|
|
1277
|
if cmd.find('%l') >= 0:
|
|
1588
|
cmd = cmd.replace('%l',rest)
|
|
1278
|
cmd = cmd.replace('%l',rest)
|
|
1589
|
rest = ''
|
|
1279
|
rest = ''
|
|
1590
|
if nargs==0:
|
|
1280
|
if nargs==0:
|
|
1591
|
# Simple, argument-less aliases
|
|
1281
|
# Simple, argument-less aliases
|
|
1592
|
cmd = '%s %s' % (cmd,rest)
|
|
1282
|
cmd = '%s %s' % (cmd,rest)
|
|
1593
|
else:
|
|
1283
|
else:
|
|
1594
|
# Handle aliases with positional arguments
|
|
1284
|
# Handle aliases with positional arguments
|
|
1595
|
args = rest.split(None,nargs)
|
|
1285
|
args = rest.split(None,nargs)
|
|
1596
|
if len(args)< nargs:
|
|
1286
|
if len(args)< nargs:
|
|
1597
|
error('Alias <%s> requires %s arguments, %s given.' %
|
|
1287
|
error('Alias <%s> requires %s arguments, %s given.' %
|
|
1598
|
(alias,nargs,len(args)))
|
|
1288
|
(alias,nargs,len(args)))
|
|
1599
|
return
|
|
1289
|
return
|
|
1600
|
cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
|
|
1290
|
cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
|
|
1601
|
# Now call the macro, evaluating in the user's namespace
|
|
1291
|
# Now call the macro, evaluating in the user's namespace
|
|
1602
|
try:
|
|
1292
|
try:
|
|
1603
|
self.system(cmd)
|
|
1293
|
self.system(cmd)
|
|
1604
|
except:
|
|
1294
|
except:
|
|
1605
|
self.showtraceback()
|
|
1295
|
self.showtraceback()
|
|
1606
|
|
|
1296
|
|
|
1607
|
def runlines(self,lines):
|
|
1297
|
def runlines(self,lines):
|
|
1608
|
"""Run a string of one or more lines of source.
|
|
1298
|
"""Run a string of one or more lines of source.
|
|
1609
|
|
|
1299
|
|
|
1610
|
This method is capable of running a string containing multiple source
|
|
1300
|
This method is capable of running a string containing multiple source
|
|
1611
|
lines, as if they had been entered at the IPython prompt. Since it
|
|
1301
|
lines, as if they had been entered at the IPython prompt. Since it
|
|
1612
|
exposes IPython's processing machinery, the given strings can contain
|
|
1302
|
exposes IPython's processing machinery, the given strings can contain
|
|
1613
|
magic calls (%magic), special shell access (!cmd), etc."""
|
|
1303
|
magic calls (%magic), special shell access (!cmd), etc."""
|
|
1614
|
|
|
1304
|
|
|
1615
|
# We must start with a clean buffer, in case this is run from an
|
|
1305
|
# We must start with a clean buffer, in case this is run from an
|
|
1616
|
# interactive IPython session (via a magic, for example).
|
|
1306
|
# interactive IPython session (via a magic, for example).
|
|
1617
|
self.resetbuffer()
|
|
1307
|
self.resetbuffer()
|
|
1618
|
lines = lines.split('\n')
|
|
1308
|
lines = lines.split('\n')
|
|
1619
|
more = 0
|
|
1309
|
more = 0
|
|
1620
|
for line in lines:
|
|
1310
|
for line in lines:
|
|
1621
|
# skip blank lines so we don't mess up the prompt counter, but do
|
|
1311
|
# skip blank lines so we don't mess up the prompt counter, but do
|
|
1622
|
# NOT skip even a blank line if we are in a code block (more is
|
|
1312
|
# NOT skip even a blank line if we are in a code block (more is
|
|
1623
|
# true)
|
|
1313
|
# true)
|
|
1624
|
if line or more:
|
|
1314
|
if line or more:
|
|
1625
|
more = self.push((self.prefilter(line,more)))
|
|
1315
|
more = self.push((self.prefilter(line,more)))
|
|
1626
|
# IPython's runsource returns None if there was an error
|
|
1316
|
# IPython's runsource returns None if there was an error
|
|
1627
|
# compiling the code. This allows us to stop processing right
|
|
1317
|
# compiling the code. This allows us to stop processing right
|
|
1628
|
# away, so the user gets the error message at the right place.
|
|
1318
|
# away, so the user gets the error message at the right place.
|
|
1629
|
if more is None:
|
|
1319
|
if more is None:
|
|
1630
|
break
|
|
1320
|
break
|
|
1631
|
# final newline in case the input didn't have it, so that the code
|
|
1321
|
# final newline in case the input didn't have it, so that the code
|
|
1632
|
# actually does get executed
|
|
1322
|
# actually does get executed
|
|
1633
|
if more:
|
|
1323
|
if more:
|
|
1634
|
self.push('\n')
|
|
1324
|
self.push('\n')
|
|
1635
|
|
|
1325
|
|
|
1636
|
def runsource(self, source, filename="<input>", symbol="single"):
|
|
1326
|
def runsource(self, source, filename="<input>", symbol="single"):
|
|
1637
|
"""Compile and run some source in the interpreter.
|
|
1327
|
"""Compile and run some source in the interpreter.
|
|
1638
|
|
|
1328
|
|
|
1639
|
Arguments are as for compile_command().
|
|
1329
|
Arguments are as for compile_command().
|
|
1640
|
|
|
1330
|
|
|
1641
|
One several things can happen:
|
|
1331
|
One several things can happen:
|
|
1642
|
|
|
1332
|
|
|
1643
|
1) The input is incorrect; compile_command() raised an
|
|
1333
|
1) The input is incorrect; compile_command() raised an
|
|
1644
|
exception (SyntaxError or OverflowError). A syntax traceback
|
|
1334
|
exception (SyntaxError or OverflowError). A syntax traceback
|
|
1645
|
will be printed by calling the showsyntaxerror() method.
|
|
1335
|
will be printed by calling the showsyntaxerror() method.
|
|
1646
|
|
|
1336
|
|
|
1647
|
2) The input is incomplete, and more input is required;
|
|
1337
|
2) The input is incomplete, and more input is required;
|
|
1648
|
compile_command() returned None. Nothing happens.
|
|
1338
|
compile_command() returned None. Nothing happens.
|
|
1649
|
|
|
1339
|
|
|
1650
|
3) The input is complete; compile_command() returned a code
|
|
1340
|
3) The input is complete; compile_command() returned a code
|
|
1651
|
object. The code is executed by calling self.runcode() (which
|
|
1341
|
object. The code is executed by calling self.runcode() (which
|
|
1652
|
also handles run-time exceptions, except for SystemExit).
|
|
1342
|
also handles run-time exceptions, except for SystemExit).
|
|
1653
|
|
|
1343
|
|
|
1654
|
The return value is:
|
|
1344
|
The return value is:
|
|
1655
|
|
|
1345
|
|
|
1656
|
- True in case 2
|
|
1346
|
- True in case 2
|
|
1657
|
|
|
1347
|
|
|
1658
|
- False in the other cases, unless an exception is raised, where
|
|
1348
|
- False in the other cases, unless an exception is raised, where
|
|
1659
|
None is returned instead. This can be used by external callers to
|
|
1349
|
None is returned instead. This can be used by external callers to
|
|
1660
|
know whether to continue feeding input or not.
|
|
1350
|
know whether to continue feeding input or not.
|
|
1661
|
|
|
1351
|
|
|
1662
|
The return value can be used to decide whether to use sys.ps1 or
|
|
1352
|
The return value can be used to decide whether to use sys.ps1 or
|
|
1663
|
sys.ps2 to prompt the next line."""
|
|
1353
|
sys.ps2 to prompt the next line."""
|
|
1664
|
|
|
1354
|
|
|
1665
|
try:
|
|
1355
|
try:
|
|
1666
|
code = self.compile(source, filename, symbol)
|
|
1356
|
code = self.compile(source, filename, symbol)
|
|
1667
|
except (OverflowError, SyntaxError, ValueError):
|
|
1357
|
except (OverflowError, SyntaxError, ValueError):
|
|
1668
|
# Case 1
|
|
1358
|
# Case 1
|
|
1669
|
self.showsyntaxerror(filename)
|
|
1359
|
self.showsyntaxerror(filename)
|
|
1670
|
return None
|
|
1360
|
return None
|
|
1671
|
|
|
1361
|
|
|
1672
|
if code is None:
|
|
1362
|
if code is None:
|
|
1673
|
# Case 2
|
|
1363
|
# Case 2
|
|
1674
|
return True
|
|
1364
|
return True
|
|
1675
|
|
|
1365
|
|
|
1676
|
# Case 3
|
|
1366
|
# Case 3
|
|
1677
|
# We store the code object so that threaded shells and
|
|
1367
|
# We store the code object so that threaded shells and
|
|
1678
|
# custom exception handlers can access all this info if needed.
|
|
1368
|
# custom exception handlers can access all this info if needed.
|
|
1679
|
# The source corresponding to this can be obtained from the
|
|
1369
|
# The source corresponding to this can be obtained from the
|
|
1680
|
# buffer attribute as '\n'.join(self.buffer).
|
|
1370
|
# buffer attribute as '\n'.join(self.buffer).
|
|
1681
|
self.code_to_run = code
|
|
1371
|
self.code_to_run = code
|
|
1682
|
# now actually execute the code object
|
|
1372
|
# now actually execute the code object
|
|
1683
|
if self.runcode(code) == 0:
|
|
1373
|
if self.runcode(code) == 0:
|
|
1684
|
return False
|
|
1374
|
return False
|
|
1685
|
else:
|
|
1375
|
else:
|
|
1686
|
return None
|
|
1376
|
return None
|
|
1687
|
|
|
1377
|
|
|
1688
|
def runcode(self,code_obj):
|
|
1378
|
def runcode(self,code_obj):
|
|
1689
|
"""Execute a code object.
|
|
1379
|
"""Execute a code object.
|
|
1690
|
|
|
1380
|
|
|
1691
|
When an exception occurs, self.showtraceback() is called to display a
|
|
1381
|
When an exception occurs, self.showtraceback() is called to display a
|
|
1692
|
traceback.
|
|
1382
|
traceback.
|
|
1693
|
|
|
1383
|
|
|
1694
|
Return value: a flag indicating whether the code to be run completed
|
|
1384
|
Return value: a flag indicating whether the code to be run completed
|
|
1695
|
successfully:
|
|
1385
|
successfully:
|
|
1696
|
|
|
1386
|
|
|
1697
|
- 0: successful execution.
|
|
1387
|
- 0: successful execution.
|
|
1698
|
- 1: an error occurred.
|
|
1388
|
- 1: an error occurred.
|
|
1699
|
"""
|
|
1389
|
"""
|
|
1700
|
|
|
1390
|
|
|
1701
|
# Set our own excepthook in case the user code tries to call it
|
|
1391
|
# Set our own excepthook in case the user code tries to call it
|
|
1702
|
# directly, so that the IPython crash handler doesn't get triggered
|
|
1392
|
# directly, so that the IPython crash handler doesn't get triggered
|
|
1703
|
old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
|
|
1393
|
old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
|
|
1704
|
outflag = 1 # happens in more places, so it's easier as default
|
|
1394
|
outflag = 1 # happens in more places, so it's easier as default
|
|
1705
|
try:
|
|
1395
|
try:
|
|
1706
|
try:
|
|
1396
|
try:
|
|
1707
|
# Embedded instances require separate global/local namespaces
|
|
1397
|
# Embedded instances require separate global/local namespaces
|
|
1708
|
# so they can see both the surrounding (local) namespace and
|
|
1398
|
# so they can see both the surrounding (local) namespace and
|
|
1709
|
# the module-level globals when called inside another function.
|
|
1399
|
# the module-level globals when called inside another function.
|
|
1710
|
if self.embedded:
|
|
1400
|
if self.embedded:
|
|
1711
|
exec code_obj in self.user_global_ns, self.user_ns
|
|
1401
|
exec code_obj in self.user_global_ns, self.user_ns
|
|
1712
|
# Normal (non-embedded) instances should only have a single
|
|
1402
|
# Normal (non-embedded) instances should only have a single
|
|
1713
|
# namespace for user code execution, otherwise functions won't
|
|
1403
|
# namespace for user code execution, otherwise functions won't
|
|
1714
|
# see interactive top-level globals.
|
|
1404
|
# see interactive top-level globals.
|
|
1715
|
else:
|
|
1405
|
else:
|
|
1716
|
exec code_obj in self.user_ns
|
|
1406
|
exec code_obj in self.user_ns
|
|
1717
|
finally:
|
|
1407
|
finally:
|
|
1718
|
# Reset our crash handler in place
|
|
1408
|
# Reset our crash handler in place
|
|
1719
|
sys.excepthook = old_excepthook
|
|
1409
|
sys.excepthook = old_excepthook
|
|
1720
|
except SystemExit:
|
|
1410
|
except SystemExit:
|
|
1721
|
self.resetbuffer()
|
|
1411
|
self.resetbuffer()
|
|
1722
|
self.showtraceback()
|
|
1412
|
self.showtraceback()
|
|
1723
|
warn( __builtin__.exit,level=1)
|
|
1413
|
warn("Type exit or quit to exit IPython "
|
|
|
|
|
1414
|
"(%Exit or %Quit do so unconditionally).",level=1)
|
|
1724
|
except self.custom_exceptions:
|
|
1415
|
except self.custom_exceptions:
|
|
1725
|
etype,value,tb = sys.exc_info()
|
|
1416
|
etype,value,tb = sys.exc_info()
|
|
1726
|
self.CustomTB(etype,value,tb)
|
|
1417
|
self.CustomTB(etype,value,tb)
|
|
1727
|
except:
|
|
1418
|
except:
|
|
1728
|
self.showtraceback()
|
|
1419
|
self.showtraceback()
|
|
1729
|
else:
|
|
1420
|
else:
|
|
1730
|
outflag = 0
|
|
1421
|
outflag = 0
|
|
1731
|
if code.softspace(sys.stdout, 0):
|
|
1422
|
if softspace(sys.stdout, 0):
|
|
1732
|
print
|
|
1423
|
print
|
|
1733
|
# Flush out code object which has been run (and source)
|
|
1424
|
# Flush out code object which has been run (and source)
|
|
1734
|
self.code_to_run = None
|
|
1425
|
self.code_to_run = None
|
|
1735
|
return outflag
|
|
1426
|
return outflag
|
|
1736
|
|
|
1427
|
|
|
|
|
|
1428
|
def push(self, line):
|
|
|
|
|
1429
|
"""Push a line to the interpreter.
|
|
|
|
|
1430
|
|
|
|
|
|
1431
|
The line should not have a trailing newline; it may have
|
|
|
|
|
1432
|
internal newlines. The line is appended to a buffer and the
|
|
|
|
|
1433
|
interpreter's runsource() method is called with the
|
|
|
|
|
1434
|
concatenated contents of the buffer as source. If this
|
|
|
|
|
1435
|
indicates that the command was executed or invalid, the buffer
|
|
|
|
|
1436
|
is reset; otherwise, the command is incomplete, and the buffer
|
|
|
|
|
1437
|
is left as it was after the line was appended. The return
|
|
|
|
|
1438
|
value is 1 if more input is required, 0 if the line was dealt
|
|
|
|
|
1439
|
with in some way (this is the same as runsource()).
|
|
|
|
|
1440
|
|
|
|
|
|
1441
|
"""
|
|
|
|
|
1442
|
self.buffer.append(line)
|
|
|
|
|
1443
|
source = "\n".join(self.buffer)
|
|
|
|
|
1444
|
more = self.runsource(source, self.filename)
|
|
|
|
|
1445
|
if not more:
|
|
|
|
|
1446
|
self.resetbuffer()
|
|
|
|
|
1447
|
return more
|
|
|
|
|
1448
|
|
|
|
|
|
1449
|
def resetbuffer(self):
|
|
|
|
|
1450
|
"""Reset the input buffer."""
|
|
|
|
|
1451
|
self.buffer[:] = []
|
|
|
|
|
1452
|
|
|
1737
|
def raw_input(self,prompt='',continue_prompt=False):
|
|
1453
|
def raw_input(self,prompt='',continue_prompt=False):
|
|
1738
|
"""Write a prompt and read a line.
|
|
1454
|
"""Write a prompt and read a line.
|
|
1739
|
|
|
1455
|
|
|
1740
|
The returned line does not include the trailing newline.
|
|
1456
|
The returned line does not include the trailing newline.
|
|
1741
|
When the user enters the EOF key sequence, EOFError is raised.
|
|
1457
|
When the user enters the EOF key sequence, EOFError is raised.
|
|
1742
|
|
|
1458
|
|
|
1743
|
Optional inputs:
|
|
1459
|
Optional inputs:
|
|
1744
|
|
|
1460
|
|
|
1745
|
- prompt(''): a string to be printed to prompt the user.
|
|
1461
|
- prompt(''): a string to be printed to prompt the user.
|
|
1746
|
|
|
1462
|
|
|
1747
|
- continue_prompt(False): whether this line is the first one or a
|
|
1463
|
- continue_prompt(False): whether this line is the first one or a
|
|
1748
|
continuation in a sequence of inputs.
|
|
1464
|
continuation in a sequence of inputs.
|
|
1749
|
"""
|
|
1465
|
"""
|
|
1750
|
|
|
1466
|
|
|
1751
|
line = raw_input_original(prompt)
|
|
1467
|
line = raw_input_original(prompt)
|
|
1752
|
# Try to be reasonably smart about not re-indenting pasted input more
|
|
1468
|
# Try to be reasonably smart about not re-indenting pasted input more
|
|
1753
|
# than necessary. We do this by trimming out the auto-indent initial
|
|
1469
|
# than necessary. We do this by trimming out the auto-indent initial
|
|
1754
|
# spaces, if the user's actual input started itself with whitespace.
|
|
1470
|
# spaces, if the user's actual input started itself with whitespace.
|
|
1755
|
if self.autoindent:
|
|
1471
|
if self.autoindent:
|
|
1756
|
line2 = line[self.readline_indent:]
|
|
1472
|
line2 = line[self.readline_indent:]
|
|
1757
|
if line2[0:1] in (' ','\t'):
|
|
1473
|
if line2[0:1] in (' ','\t'):
|
|
1758
|
line = line2
|
|
1474
|
line = line2
|
|
1759
|
return self.prefilter(line,continue_prompt)
|
|
1475
|
return self.prefilter(line,continue_prompt)
|
|
1760
|
|
|
1476
|
|
|
1761
|
def split_user_input(self,line):
|
|
1477
|
def split_user_input(self,line):
|
|
1762
|
"""Split user input into pre-char, function part and rest."""
|
|
1478
|
"""Split user input into pre-char, function part and rest."""
|
|
1763
|
|
|
1479
|
|
|
1764
|
lsplit = self.line_split.match(line)
|
|
1480
|
lsplit = self.line_split.match(line)
|
|
1765
|
if lsplit is None: # no regexp match returns None
|
|
1481
|
if lsplit is None: # no regexp match returns None
|
|
1766
|
try:
|
|
1482
|
try:
|
|
1767
|
iFun,theRest = line.split(None,1)
|
|
1483
|
iFun,theRest = line.split(None,1)
|
|
1768
|
except ValueError:
|
|
1484
|
except ValueError:
|
|
1769
|
iFun,theRest = line,''
|
|
1485
|
iFun,theRest = line,''
|
|
1770
|
pre = re.match('^(\s*)(.*)',line).groups()[0]
|
|
1486
|
pre = re.match('^(\s*)(.*)',line).groups()[0]
|
|
1771
|
else:
|
|
1487
|
else:
|
|
1772
|
pre,iFun,theRest = lsplit.groups()
|
|
1488
|
pre,iFun,theRest = lsplit.groups()
|
|
1773
|
|
|
1489
|
|
|
1774
|
#print 'line:<%s>' % line # dbg
|
|
1490
|
#print 'line:<%s>' % line # dbg
|
|
1775
|
#print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
|
|
1491
|
#print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
|
|
1776
|
return pre,iFun.strip(),theRest
|
|
1492
|
return pre,iFun.strip(),theRest
|
|
1777
|
|
|
1493
|
|
|
1778
|
def _prefilter(self, line, continue_prompt):
|
|
1494
|
def _prefilter(self, line, continue_prompt):
|
|
1779
|
"""Calls different preprocessors, depending on the form of line."""
|
|
1495
|
"""Calls different preprocessors, depending on the form of line."""
|
|
1780
|
|
|
1496
|
|
|
1781
|
# All handlers *must* return a value, even if it's blank ('').
|
|
1497
|
# All handlers *must* return a value, even if it's blank ('').
|
|
1782
|
|
|
1498
|
|
|
1783
|
# Lines are NOT logged here. Handlers should process the line as
|
|
1499
|
# Lines are NOT logged here. Handlers should process the line as
|
|
1784
|
# needed, update the cache AND log it (so that the input cache array
|
|
1500
|
# needed, update the cache AND log it (so that the input cache array
|
|
1785
|
# stays synced).
|
|
1501
|
# stays synced).
|
|
1786
|
|
|
1502
|
|
|
1787
|
# This function is _very_ delicate, and since it's also the one which
|
|
1503
|
# This function is _very_ delicate, and since it's also the one which
|
|
1788
|
# determines IPython's response to user input, it must be as efficient
|
|
1504
|
# determines IPython's response to user input, it must be as efficient
|
|
1789
|
# as possible. For this reason it has _many_ returns in it, trying
|
|
1505
|
# as possible. For this reason it has _many_ returns in it, trying
|
|
1790
|
# always to exit as quickly as it can figure out what it needs to do.
|
|
1506
|
# always to exit as quickly as it can figure out what it needs to do.
|
|
1791
|
|
|
1507
|
|
|
1792
|
# This function is the main responsible for maintaining IPython's
|
|
1508
|
# This function is the main responsible for maintaining IPython's
|
|
1793
|
# behavior respectful of Python's semantics. So be _very_ careful if
|
|
1509
|
# behavior respectful of Python's semantics. So be _very_ careful if
|
|
1794
|
# making changes to anything here.
|
|
1510
|
# making changes to anything here.
|
|
1795
|
|
|
1511
|
|
|
1796
|
#.....................................................................
|
|
1512
|
#.....................................................................
|
|
1797
|
# Code begins
|
|
1513
|
# Code begins
|
|
1798
|
|
|
1514
|
|
|
1799
|
#if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
|
|
1515
|
#if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
|
|
1800
|
|
|
1516
|
|
|
1801
|
# save the line away in case we crash, so the post-mortem handler can
|
|
1517
|
# save the line away in case we crash, so the post-mortem handler can
|
|
1802
|
# record it
|
|
1518
|
# record it
|
|
1803
|
self._last_input_line = line
|
|
1519
|
self._last_input_line = line
|
|
1804
|
|
|
1520
|
|
|
1805
|
#print '***line: <%s>' % line # dbg
|
|
1521
|
#print '***line: <%s>' % line # dbg
|
|
1806
|
|
|
1522
|
|
|
1807
|
# the input history needs to track even empty lines
|
|
1523
|
# the input history needs to track even empty lines
|
|
1808
|
if not line.strip():
|
|
1524
|
if not line.strip():
|
|
1809
|
if not continue_prompt:
|
|
1525
|
if not continue_prompt:
|
|
1810
|
self.outputcache.prompt_count -= 1
|
|
1526
|
self.outputcache.prompt_count -= 1
|
|
1811
|
return self.handle_normal('',continue_prompt)
|
|
1527
|
return self.handle_normal('',continue_prompt)
|
|
1812
|
|
|
1528
|
|
|
1813
|
# print '***cont',continue_prompt # dbg
|
|
1529
|
# print '***cont',continue_prompt # dbg
|
|
1814
|
# special handlers are only allowed for single line statements
|
|
1530
|
# special handlers are only allowed for single line statements
|
|
1815
|
if continue_prompt and not self.rc.multi_line_specials:
|
|
1531
|
if continue_prompt and not self.rc.multi_line_specials:
|
|
1816
|
return self.handle_normal(line,continue_prompt)
|
|
1532
|
return self.handle_normal(line,continue_prompt)
|
|
1817
|
|
|
1533
|
|
|
1818
|
# For the rest, we need the structure of the input
|
|
1534
|
# For the rest, we need the structure of the input
|
|
1819
|
pre,iFun,theRest = self.split_user_input(line)
|
|
1535
|
pre,iFun,theRest = self.split_user_input(line)
|
|
1820
|
#print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
|
|
1536
|
#print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
|
|
1821
|
|
|
1537
|
|
|
1822
|
# First check for explicit escapes in the last/first character
|
|
1538
|
# First check for explicit escapes in the last/first character
|
|
1823
|
handler = None
|
|
1539
|
handler = None
|
|
1824
|
if line[-1] == self.ESC_HELP:
|
|
1540
|
if line[-1] == self.ESC_HELP:
|
|
1825
|
handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
|
|
1541
|
handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
|
|
1826
|
if handler is None:
|
|
1542
|
if handler is None:
|
|
1827
|
# look at the first character of iFun, NOT of line, so we skip
|
|
1543
|
# look at the first character of iFun, NOT of line, so we skip
|
|
1828
|
# leading whitespace in multiline input
|
|
1544
|
# leading whitespace in multiline input
|
|
1829
|
handler = self.esc_handlers.get(iFun[0:1])
|
|
1545
|
handler = self.esc_handlers.get(iFun[0:1])
|
|
1830
|
if handler is not None:
|
|
1546
|
if handler is not None:
|
|
1831
|
return handler(line,continue_prompt,pre,iFun,theRest)
|
|
1547
|
return handler(line,continue_prompt,pre,iFun,theRest)
|
|
1832
|
# Emacs ipython-mode tags certain input lines
|
|
1548
|
# Emacs ipython-mode tags certain input lines
|
|
1833
|
if line.endswith('# PYTHON-MODE'):
|
|
1549
|
if line.endswith('# PYTHON-MODE'):
|
|
1834
|
return self.handle_emacs(line,continue_prompt)
|
|
1550
|
return self.handle_emacs(line,continue_prompt)
|
|
1835
|
|
|
1551
|
|
|
1836
|
# Next, check if we can automatically execute this thing
|
|
1552
|
# Next, check if we can automatically execute this thing
|
|
1837
|
|
|
1553
|
|
|
1838
|
# Allow ! in multi-line statements if multi_line_specials is on:
|
|
1554
|
# Allow ! in multi-line statements if multi_line_specials is on:
|
|
1839
|
if continue_prompt and self.rc.multi_line_specials and \
|
|
1555
|
if continue_prompt and self.rc.multi_line_specials and \
|
|
1840
|
iFun.startswith(self.ESC_SHELL):
|
|
1556
|
iFun.startswith(self.ESC_SHELL):
|
|
1841
|
return self.handle_shell_escape(line,continue_prompt,
|
|
1557
|
return self.handle_shell_escape(line,continue_prompt,
|
|
1842
|
pre=pre,iFun=iFun,
|
|
1558
|
pre=pre,iFun=iFun,
|
|
1843
|
theRest=theRest)
|
|
1559
|
theRest=theRest)
|
|
1844
|
|
|
1560
|
|
|
1845
|
# Let's try to find if the input line is a magic fn
|
|
1561
|
# Let's try to find if the input line is a magic fn
|
|
1846
|
oinfo = None
|
|
1562
|
oinfo = None
|
|
1847
|
if hasattr(self,'magic_'+iFun):
|
|
1563
|
if hasattr(self,'magic_'+iFun):
|
|
1848
|
oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
|
|
1564
|
oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
|
|
1849
|
if oinfo['ismagic']:
|
|
1565
|
if oinfo['ismagic']:
|
|
1850
|
# Be careful not to call magics when a variable assignment is
|
|
1566
|
# Be careful not to call magics when a variable assignment is
|
|
1851
|
# being made (ls='hi', for example)
|
|
1567
|
# being made (ls='hi', for example)
|
|
1852
|
if self.rc.automagic and \
|
|
1568
|
if self.rc.automagic and \
|
|
1853
|
(len(theRest)==0 or theRest[0] not in '!=()<>,') and \
|
|
1569
|
(len(theRest)==0 or theRest[0] not in '!=()<>,') and \
|
|
1854
|
(self.rc.multi_line_specials or not continue_prompt):
|
|
1570
|
(self.rc.multi_line_specials or not continue_prompt):
|
|
1855
|
return self.handle_magic(line,continue_prompt,
|
|
1571
|
return self.handle_magic(line,continue_prompt,
|
|
1856
|
pre,iFun,theRest)
|
|
1572
|
pre,iFun,theRest)
|
|
1857
|
else:
|
|
1573
|
else:
|
|
1858
|
return self.handle_normal(line,continue_prompt)
|
|
1574
|
return self.handle_normal(line,continue_prompt)
|
|
1859
|
|
|
1575
|
|
|
1860
|
# If the rest of the line begins with an (in)equality, assginment or
|
|
1576
|
# If the rest of the line begins with an (in)equality, assginment or
|
|
1861
|
# function call, we should not call _ofind but simply execute it.
|
|
1577
|
# function call, we should not call _ofind but simply execute it.
|
|
1862
|
# This avoids spurious geattr() accesses on objects upon assignment.
|
|
1578
|
# This avoids spurious geattr() accesses on objects upon assignment.
|
|
1863
|
#
|
|
1579
|
#
|
|
1864
|
# It also allows users to assign to either alias or magic names true
|
|
1580
|
# It also allows users to assign to either alias or magic names true
|
|
1865
|
# python variables (the magic/alias systems always take second seat to
|
|
1581
|
# python variables (the magic/alias systems always take second seat to
|
|
1866
|
# true python code).
|
|
1582
|
# true python code).
|
|
1867
|
if theRest and theRest[0] in '!=()':
|
|
1583
|
if theRest and theRest[0] in '!=()':
|
|
1868
|
return self.handle_normal(line,continue_prompt)
|
|
1584
|
return self.handle_normal(line,continue_prompt)
|
|
1869
|
|
|
1585
|
|
|
1870
|
if oinfo is None:
|
|
1586
|
if oinfo is None:
|
|
1871
|
oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
|
|
1587
|
oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
|
|
1872
|
|
|
1588
|
|
|
1873
|
if not oinfo['found']:
|
|
1589
|
if not oinfo['found']:
|
|
|
|
|
1590
|
if iFun in ('quit','exit'):
|
|
|
|
|
1591
|
raise IPythonExit
|
|
1874
|
return self.handle_normal(line,continue_prompt)
|
|
1592
|
return self.handle_normal(line,continue_prompt)
|
|
1875
|
else:
|
|
1593
|
else:
|
|
1876
|
#print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
|
|
1594
|
#print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
|
|
1877
|
if oinfo['isalias']:
|
|
1595
|
if oinfo['isalias']:
|
|
1878
|
return self.handle_alias(line,continue_prompt,
|
|
1596
|
return self.handle_alias(line,continue_prompt,
|
|
1879
|
pre,iFun,theRest)
|
|
1597
|
pre,iFun,theRest)
|
|
1880
|
|
|
1598
|
|
|
1881
|
if self.rc.autocall and \
|
|
1599
|
if self.rc.autocall and \
|
|
1882
|
not self.re_exclude_auto.match(theRest) and \
|
|
1600
|
not self.re_exclude_auto.match(theRest) and \
|
|
1883
|
self.re_fun_name.match(iFun) and \
|
|
1601
|
self.re_fun_name.match(iFun) and \
|
|
1884
|
callable(oinfo['obj']) :
|
|
1602
|
callable(oinfo['obj']) :
|
|
1885
|
#print 'going auto' # dbg
|
|
1603
|
#print 'going auto' # dbg
|
|
1886
|
return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
|
|
1604
|
return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
|
|
1887
|
else:
|
|
1605
|
else:
|
|
1888
|
#print 'was callable?', callable(oinfo['obj']) # dbg
|
|
1606
|
#print 'was callable?', callable(oinfo['obj']) # dbg
|
|
1889
|
return self.handle_normal(line,continue_prompt)
|
|
1607
|
return self.handle_normal(line,continue_prompt)
|
|
1890
|
|
|
1608
|
|
|
1891
|
# If we get here, we have a normal Python line. Log and return.
|
|
1609
|
# If we get here, we have a normal Python line. Log and return.
|
|
1892
|
return self.handle_normal(line,continue_prompt)
|
|
1610
|
return self.handle_normal(line,continue_prompt)
|
|
1893
|
|
|
1611
|
|
|
1894
|
def _prefilter_dumb(self, line, continue_prompt):
|
|
1612
|
def _prefilter_dumb(self, line, continue_prompt):
|
|
1895
|
"""simple prefilter function, for debugging"""
|
|
1613
|
"""simple prefilter function, for debugging"""
|
|
1896
|
return self.handle_normal(line,continue_prompt)
|
|
1614
|
return self.handle_normal(line,continue_prompt)
|
|
1897
|
|
|
1615
|
|
|
1898
|
# Set the default prefilter() function (this can be user-overridden)
|
|
1616
|
# Set the default prefilter() function (this can be user-overridden)
|
|
1899
|
prefilter = _prefilter
|
|
1617
|
prefilter = _prefilter
|
|
1900
|
|
|
1618
|
|
|
1901
|
def handle_normal(self,line,continue_prompt=None,
|
|
1619
|
def handle_normal(self,line,continue_prompt=None,
|
|
1902
|
pre=None,iFun=None,theRest=None):
|
|
1620
|
pre=None,iFun=None,theRest=None):
|
|
1903
|
"""Handle normal input lines. Use as a template for handlers."""
|
|
1621
|
"""Handle normal input lines. Use as a template for handlers."""
|
|
1904
|
|
|
1622
|
|
|
1905
|
self.log(line,continue_prompt)
|
|
1623
|
self.log(line,continue_prompt)
|
|
1906
|
self.update_cache(line)
|
|
1624
|
self.update_cache(line)
|
|
1907
|
return line
|
|
1625
|
return line
|
|
1908
|
|
|
1626
|
|
|
1909
|
def handle_alias(self,line,continue_prompt=None,
|
|
1627
|
def handle_alias(self,line,continue_prompt=None,
|
|
1910
|
pre=None,iFun=None,theRest=None):
|
|
1628
|
pre=None,iFun=None,theRest=None):
|
|
1911
|
"""Handle alias input lines. """
|
|
1629
|
"""Handle alias input lines. """
|
|
1912
|
|
|
1630
|
|
|
1913
|
theRest = esc_quotes(theRest)
|
|
1631
|
theRest = esc_quotes(theRest)
|
|
1914
|
line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
|
|
1632
|
line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
|
|
1915
|
self.log(line_out,continue_prompt)
|
|
1633
|
self.log(line_out,continue_prompt)
|
|
1916
|
self.update_cache(line_out)
|
|
1634
|
self.update_cache(line_out)
|
|
1917
|
return line_out
|
|
1635
|
return line_out
|
|
1918
|
|
|
1636
|
|
|
1919
|
def handle_shell_escape(self, line, continue_prompt=None,
|
|
1637
|
def handle_shell_escape(self, line, continue_prompt=None,
|
|
1920
|
pre=None,iFun=None,theRest=None):
|
|
1638
|
pre=None,iFun=None,theRest=None):
|
|
1921
|
"""Execute the line in a shell, empty return value"""
|
|
1639
|
"""Execute the line in a shell, empty return value"""
|
|
1922
|
|
|
1640
|
|
|
1923
|
#print 'line in :', `line` # dbg
|
|
1641
|
#print 'line in :', `line` # dbg
|
|
1924
|
# Example of a special handler. Others follow a similar pattern.
|
|
1642
|
# Example of a special handler. Others follow a similar pattern.
|
|
1925
|
if continue_prompt: # multi-line statements
|
|
1643
|
if continue_prompt: # multi-line statements
|
|
1926
|
if iFun.startswith('!!'):
|
|
1644
|
if iFun.startswith('!!'):
|
|
1927
|
print 'SyntaxError: !! is not allowed in multiline statements'
|
|
1645
|
print 'SyntaxError: !! is not allowed in multiline statements'
|
|
1928
|
return pre
|
|
1646
|
return pre
|
|
1929
|
else:
|
|
1647
|
else:
|
|
1930
|
cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
|
|
1648
|
cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
|
|
1931
|
line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
|
|
1649
|
line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
|
|
1932
|
#line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
|
|
1650
|
#line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
|
|
1933
|
else: # single-line input
|
|
1651
|
else: # single-line input
|
|
1934
|
if line.startswith('!!'):
|
|
1652
|
if line.startswith('!!'):
|
|
1935
|
# rewrite iFun/theRest to properly hold the call to %sx and
|
|
1653
|
# rewrite iFun/theRest to properly hold the call to %sx and
|
|
1936
|
# the actual command to be executed, so handle_magic can work
|
|
1654
|
# the actual command to be executed, so handle_magic can work
|
|
1937
|
# correctly
|
|
1655
|
# correctly
|
|
1938
|
theRest = '%s %s' % (iFun[2:],theRest)
|
|
1656
|
theRest = '%s %s' % (iFun[2:],theRest)
|
|
1939
|
iFun = 'sx'
|
|
1657
|
iFun = 'sx'
|
|
1940
|
return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
|
|
1658
|
return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
|
|
1941
|
continue_prompt,pre,iFun,theRest)
|
|
1659
|
continue_prompt,pre,iFun,theRest)
|
|
1942
|
else:
|
|
1660
|
else:
|
|
1943
|
cmd = esc_quotes(line[1:])
|
|
1661
|
cmd = esc_quotes(line[1:])
|
|
1944
|
line_out = '%s.system("%s")' % (self.name,cmd)
|
|
1662
|
line_out = '%s.system("%s")' % (self.name,cmd)
|
|
1945
|
#line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
|
|
1663
|
#line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
|
|
1946
|
# update cache/log and return
|
|
1664
|
# update cache/log and return
|
|
1947
|
self.log(line_out,continue_prompt)
|
|
1665
|
self.log(line_out,continue_prompt)
|
|
1948
|
self.update_cache(line_out) # readline cache gets normal line
|
|
1666
|
self.update_cache(line_out) # readline cache gets normal line
|
|
1949
|
#print 'line out r:', `line_out` # dbg
|
|
1667
|
#print 'line out r:', `line_out` # dbg
|
|
1950
|
#print 'line out s:', line_out # dbg
|
|
1668
|
#print 'line out s:', line_out # dbg
|
|
1951
|
return line_out
|
|
1669
|
return line_out
|
|
1952
|
|
|
1670
|
|
|
1953
|
def handle_magic(self, line, continue_prompt=None,
|
|
1671
|
def handle_magic(self, line, continue_prompt=None,
|
|
1954
|
pre=None,iFun=None,theRest=None):
|
|
1672
|
pre=None,iFun=None,theRest=None):
|
|
1955
|
"""Execute magic functions.
|
|
1673
|
"""Execute magic functions.
|
|
1956
|
|
|
1674
|
|
|
1957
|
Also log them with a prepended # so the log is clean Python."""
|
|
1675
|
Also log them with a prepended # so the log is clean Python."""
|
|
1958
|
|
|
1676
|
|
|
1959
|
cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
|
|
1677
|
cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
|
|
1960
|
self.log(cmd,continue_prompt)
|
|
1678
|
self.log(cmd,continue_prompt)
|
|
1961
|
self.update_cache(line)
|
|
1679
|
self.update_cache(line)
|
|
1962
|
#print 'in handle_magic, cmd=<%s>' % cmd # dbg
|
|
1680
|
#print 'in handle_magic, cmd=<%s>' % cmd # dbg
|
|
1963
|
return cmd
|
|
1681
|
return cmd
|
|
1964
|
|
|
1682
|
|
|
1965
|
def handle_auto(self, line, continue_prompt=None,
|
|
1683
|
def handle_auto(self, line, continue_prompt=None,
|
|
1966
|
pre=None,iFun=None,theRest=None):
|
|
1684
|
pre=None,iFun=None,theRest=None):
|
|
1967
|
"""Hande lines which can be auto-executed, quoting if requested."""
|
|
1685
|
"""Hande lines which can be auto-executed, quoting if requested."""
|
|
1968
|
|
|
1686
|
|
|
1969
|
#print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
|
|
1687
|
#print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
|
|
1970
|
|
|
1688
|
|
|
1971
|
# This should only be active for single-line input!
|
|
1689
|
# This should only be active for single-line input!
|
|
1972
|
if continue_prompt:
|
|
1690
|
if continue_prompt:
|
|
1973
|
return line
|
|
1691
|
return line
|
|
1974
|
|
|
1692
|
|
|
1975
|
if pre == self.ESC_QUOTE:
|
|
1693
|
if pre == self.ESC_QUOTE:
|
|
1976
|
# Auto-quote splitting on whitespace
|
|
1694
|
# Auto-quote splitting on whitespace
|
|
1977
|
newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
|
|
1695
|
newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
|
|
1978
|
elif pre == self.ESC_QUOTE2:
|
|
1696
|
elif pre == self.ESC_QUOTE2:
|
|
1979
|
# Auto-quote whole string
|
|
1697
|
# Auto-quote whole string
|
|
1980
|
newcmd = '%s("%s")' % (iFun,theRest)
|
|
1698
|
newcmd = '%s("%s")' % (iFun,theRest)
|
|
1981
|
else:
|
|
1699
|
else:
|
|
1982
|
# Auto-paren
|
|
1700
|
# Auto-paren
|
|
1983
|
if theRest[0:1] in ('=','['):
|
|
1701
|
if theRest[0:1] in ('=','['):
|
|
1984
|
# Don't autocall in these cases. They can be either
|
|
1702
|
# Don't autocall in these cases. They can be either
|
|
1985
|
# rebindings of an existing callable's name, or item access
|
|
1703
|
# rebindings of an existing callable's name, or item access
|
|
1986
|
# for an object which is BOTH callable and implements
|
|
1704
|
# for an object which is BOTH callable and implements
|
|
1987
|
# __getitem__.
|
|
1705
|
# __getitem__.
|
|
1988
|
return '%s %s' % (iFun,theRest)
|
|
1706
|
return '%s %s' % (iFun,theRest)
|
|
1989
|
if theRest.endswith(';'):
|
|
1707
|
if theRest.endswith(';'):
|
|
1990
|
newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
|
|
1708
|
newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
|
|
1991
|
else:
|
|
1709
|
else:
|
|
1992
|
newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
|
|
1710
|
newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
|
|
1993
|
|
|
1711
|
|
|
1994
|
print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
|
|
1712
|
print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
|
|
1995
|
# log what is now valid Python, not the actual user input (without the
|
|
1713
|
# log what is now valid Python, not the actual user input (without the
|
|
1996
|
# final newline)
|
|
1714
|
# final newline)
|
|
1997
|
self.log(newcmd,continue_prompt)
|
|
1715
|
self.log(newcmd,continue_prompt)
|
|
1998
|
return newcmd
|
|
1716
|
return newcmd
|
|
1999
|
|
|
1717
|
|
|
2000
|
def handle_help(self, line, continue_prompt=None,
|
|
1718
|
def handle_help(self, line, continue_prompt=None,
|
|
2001
|
pre=None,iFun=None,theRest=None):
|
|
1719
|
pre=None,iFun=None,theRest=None):
|
|
2002
|
"""Try to get some help for the object.
|
|
1720
|
"""Try to get some help for the object.
|
|
2003
|
|
|
1721
|
|
|
2004
|
obj? or ?obj -> basic information.
|
|
1722
|
obj? or ?obj -> basic information.
|
|
2005
|
obj?? or ??obj -> more details.
|
|
1723
|
obj?? or ??obj -> more details.
|
|
2006
|
"""
|
|
1724
|
"""
|
|
2007
|
|
|
1725
|
|
|
2008
|
# We need to make sure that we don't process lines which would be
|
|
1726
|
# We need to make sure that we don't process lines which would be
|
|
2009
|
# otherwise valid python, such as "x=1 # what?"
|
|
1727
|
# otherwise valid python, such as "x=1 # what?"
|
|
2010
|
try:
|
|
1728
|
try:
|
|
2011
|
code.compile_command(line)
|
|
1729
|
codeop.compile_command(line)
|
|
2012
|
except SyntaxError:
|
|
1730
|
except SyntaxError:
|
|
2013
|
# We should only handle as help stuff which is NOT valid syntax
|
|
1731
|
# We should only handle as help stuff which is NOT valid syntax
|
|
2014
|
if line[0]==self.ESC_HELP:
|
|
1732
|
if line[0]==self.ESC_HELP:
|
|
2015
|
line = line[1:]
|
|
1733
|
line = line[1:]
|
|
2016
|
elif line[-1]==self.ESC_HELP:
|
|
1734
|
elif line[-1]==self.ESC_HELP:
|
|
2017
|
line = line[:-1]
|
|
1735
|
line = line[:-1]
|
|
2018
|
self.log('#?'+line)
|
|
1736
|
self.log('#?'+line)
|
|
2019
|
self.update_cache(line)
|
|
1737
|
self.update_cache(line)
|
|
2020
|
if line:
|
|
1738
|
if line:
|
|
2021
|
self.magic_pinfo(line)
|
|
1739
|
self.magic_pinfo(line)
|
|
2022
|
else:
|
|
1740
|
else:
|
|
2023
|
page(self.usage,screen_lines=self.rc.screen_length)
|
|
1741
|
page(self.usage,screen_lines=self.rc.screen_length)
|
|
2024
|
return '' # Empty string is needed here!
|
|
1742
|
return '' # Empty string is needed here!
|
|
2025
|
except:
|
|
1743
|
except:
|
|
2026
|
# Pass any other exceptions through to the normal handler
|
|
1744
|
# Pass any other exceptions through to the normal handler
|
|
2027
|
return self.handle_normal(line,continue_prompt)
|
|
1745
|
return self.handle_normal(line,continue_prompt)
|
|
2028
|
else:
|
|
1746
|
else:
|
|
2029
|
# If the code compiles ok, we should handle it normally
|
|
1747
|
# If the code compiles ok, we should handle it normally
|
|
2030
|
return self.handle_normal(line,continue_prompt)
|
|
1748
|
return self.handle_normal(line,continue_prompt)
|
|
2031
|
|
|
1749
|
|
|
2032
|
def handle_emacs(self,line,continue_prompt=None,
|
|
1750
|
def handle_emacs(self,line,continue_prompt=None,
|
|
2033
|
pre=None,iFun=None,theRest=None):
|
|
1751
|
pre=None,iFun=None,theRest=None):
|
|
2034
|
"""Handle input lines marked by python-mode."""
|
|
1752
|
"""Handle input lines marked by python-mode."""
|
|
2035
|
|
|
1753
|
|
|
2036
|
# Currently, nothing is done. Later more functionality can be added
|
|
1754
|
# Currently, nothing is done. Later more functionality can be added
|
|
2037
|
# here if needed.
|
|
1755
|
# here if needed.
|
|
2038
|
|
|
1756
|
|
|
2039
|
# The input cache shouldn't be updated
|
|
1757
|
# The input cache shouldn't be updated
|
|
2040
|
|
|
1758
|
|
|
2041
|
return line
|
|
1759
|
return line
|
|
2042
|
|
|
1760
|
|
|
2043
|
def write(self,data):
|
|
1761
|
def write(self,data):
|
|
2044
|
"""Write a string to the default output"""
|
|
1762
|
"""Write a string to the default output"""
|
|
2045
|
Term.cout.write(data)
|
|
1763
|
Term.cout.write(data)
|
|
2046
|
|
|
1764
|
|
|
2047
|
def write_err(self,data):
|
|
1765
|
def write_err(self,data):
|
|
2048
|
"""Write a string to the default error output"""
|
|
1766
|
"""Write a string to the default error output"""
|
|
2049
|
Term.cerr.write(data)
|
|
1767
|
Term.cerr.write(data)
|
|
2050
|
|
|
1768
|
|
|
|
|
|
1769
|
def exit(self):
|
|
|
|
|
1770
|
"""Handle interactive exit.
|
|
|
|
|
1771
|
|
|
|
|
|
1772
|
This method sets the exit_now attribute."""
|
|
|
|
|
1773
|
|
|
|
|
|
1774
|
if self.rc.confirm_exit:
|
|
|
|
|
1775
|
if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
|
|
|
|
|
1776
|
self.exit_now = True
|
|
|
|
|
1777
|
else:
|
|
|
|
|
1778
|
self.exit_now = True
|
|
|
|
|
1779
|
return self.exit_now
|
|
|
|
|
1780
|
|
|
2051
|
def safe_execfile(self,fname,*where,**kw):
|
|
1781
|
def safe_execfile(self,fname,*where,**kw):
|
|
2052
|
fname = os.path.expanduser(fname)
|
|
1782
|
fname = os.path.expanduser(fname)
|
|
2053
|
|
|
1783
|
|
|
2054
|
# find things also in current directory
|
|
1784
|
# find things also in current directory
|
|
2055
|
dname = os.path.dirname(fname)
|
|
1785
|
dname = os.path.dirname(fname)
|
|
2056
|
if not sys.path.count(dname):
|
|
1786
|
if not sys.path.count(dname):
|
|
2057
|
sys.path.append(dname)
|
|
1787
|
sys.path.append(dname)
|
|
2058
|
|
|
1788
|
|
|
2059
|
try:
|
|
1789
|
try:
|
|
2060
|
xfile = open(fname)
|
|
1790
|
xfile = open(fname)
|
|
2061
|
except:
|
|
1791
|
except:
|
|
2062
|
print >> Term.cerr, \
|
|
1792
|
print >> Term.cerr, \
|
|
2063
|
'Could not open file <%s> for safe execution.' % fname
|
|
1793
|
'Could not open file <%s> for safe execution.' % fname
|
|
2064
|
return None
|
|
1794
|
return None
|
|
2065
|
|
|
1795
|
|
|
2066
|
kw.setdefault('islog',0)
|
|
1796
|
kw.setdefault('islog',0)
|
|
2067
|
kw.setdefault('quiet',1)
|
|
1797
|
kw.setdefault('quiet',1)
|
|
2068
|
kw.setdefault('exit_ignore',0)
|
|
1798
|
kw.setdefault('exit_ignore',0)
|
|
2069
|
first = xfile.readline()
|
|
1799
|
first = xfile.readline()
|
|
2070
|
_LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
|
|
1800
|
_LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
|
|
2071
|
xfile.close()
|
|
1801
|
xfile.close()
|
|
2072
|
# line by line execution
|
|
1802
|
# line by line execution
|
|
2073
|
if first.startswith(_LOGHEAD) or kw['islog']:
|
|
1803
|
if first.startswith(_LOGHEAD) or kw['islog']:
|
|
2074
|
print 'Loading log file <%s> one line at a time...' % fname
|
|
1804
|
print 'Loading log file <%s> one line at a time...' % fname
|
|
2075
|
if kw['quiet']:
|
|
1805
|
if kw['quiet']:
|
|
2076
|
stdout_save = sys.stdout
|
|
1806
|
stdout_save = sys.stdout
|
|
2077
|
sys.stdout = StringIO.StringIO()
|
|
1807
|
sys.stdout = StringIO.StringIO()
|
|
2078
|
try:
|
|
1808
|
try:
|
|
2079
|
globs,locs = where[0:2]
|
|
1809
|
globs,locs = where[0:2]
|
|
2080
|
except:
|
|
1810
|
except:
|
|
2081
|
try:
|
|
1811
|
try:
|
|
2082
|
globs = locs = where[0]
|
|
1812
|
globs = locs = where[0]
|
|
2083
|
except:
|
|
1813
|
except:
|
|
2084
|
globs = locs = globals()
|
|
1814
|
globs = locs = globals()
|
|
2085
|
badblocks = []
|
|
1815
|
badblocks = []
|
|
2086
|
|
|
1816
|
|
|
2087
|
# we also need to identify indented blocks of code when replaying
|
|
1817
|
# we also need to identify indented blocks of code when replaying
|
|
2088
|
# logs and put them together before passing them to an exec
|
|
1818
|
# logs and put them together before passing them to an exec
|
|
2089
|
# statement. This takes a bit of regexp and look-ahead work in the
|
|
1819
|
# statement. This takes a bit of regexp and look-ahead work in the
|
|
2090
|
# file. It's easiest if we swallow the whole thing in memory
|
|
1820
|
# file. It's easiest if we swallow the whole thing in memory
|
|
2091
|
# first, and manually walk through the lines list moving the
|
|
1821
|
# first, and manually walk through the lines list moving the
|
|
2092
|
# counter ourselves.
|
|
1822
|
# counter ourselves.
|
|
2093
|
indent_re = re.compile('\s+\S')
|
|
1823
|
indent_re = re.compile('\s+\S')
|
|
2094
|
xfile = open(fname)
|
|
1824
|
xfile = open(fname)
|
|
2095
|
filelines = xfile.readlines()
|
|
1825
|
filelines = xfile.readlines()
|
|
2096
|
xfile.close()
|
|
1826
|
xfile.close()
|
|
2097
|
nlines = len(filelines)
|
|
1827
|
nlines = len(filelines)
|
|
2098
|
lnum = 0
|
|
1828
|
lnum = 0
|
|
2099
|
while lnum < nlines:
|
|
1829
|
while lnum < nlines:
|
|
2100
|
line = filelines[lnum]
|
|
1830
|
line = filelines[lnum]
|
|
2101
|
lnum += 1
|
|
1831
|
lnum += 1
|
|
2102
|
# don't re-insert logger status info into cache
|
|
1832
|
# don't re-insert logger status info into cache
|
|
2103
|
if line.startswith('#log#'):
|
|
1833
|
if line.startswith('#log#'):
|
|
2104
|
continue
|
|
1834
|
continue
|
|
2105
|
elif line.startswith('#%s'% self.ESC_MAGIC):
|
|
1835
|
elif line.startswith('#%s'% self.ESC_MAGIC):
|
|
2106
|
self.update_cache(line[1:])
|
|
1836
|
self.update_cache(line[1:])
|
|
2107
|
line = magic2python(line)
|
|
1837
|
line = magic2python(line)
|
|
2108
|
elif line.startswith('#!'):
|
|
1838
|
elif line.startswith('#!'):
|
|
2109
|
self.update_cache(line[1:])
|
|
1839
|
self.update_cache(line[1:])
|
|
2110
|
else:
|
|
1840
|
else:
|
|
2111
|
# build a block of code (maybe a single line) for execution
|
|
1841
|
# build a block of code (maybe a single line) for execution
|
|
2112
|
block = line
|
|
1842
|
block = line
|
|
2113
|
try:
|
|
1843
|
try:
|
|
2114
|
next = filelines[lnum] # lnum has already incremented
|
|
1844
|
next = filelines[lnum] # lnum has already incremented
|
|
2115
|
except:
|
|
1845
|
except:
|
|
2116
|
next = None
|
|
1846
|
next = None
|
|
2117
|
while next and indent_re.match(next):
|
|
1847
|
while next and indent_re.match(next):
|
|
2118
|
block += next
|
|
1848
|
block += next
|
|
2119
|
lnum += 1
|
|
1849
|
lnum += 1
|
|
2120
|
try:
|
|
1850
|
try:
|
|
2121
|
next = filelines[lnum]
|
|
1851
|
next = filelines[lnum]
|
|
2122
|
except:
|
|
1852
|
except:
|
|
2123
|
next = None
|
|
1853
|
next = None
|
|
2124
|
# now execute the block of one or more lines
|
|
1854
|
# now execute the block of one or more lines
|
|
2125
|
try:
|
|
1855
|
try:
|
|
2126
|
exec block in globs,locs
|
|
1856
|
exec block in globs,locs
|
|
2127
|
self.update_cache(block.rstrip())
|
|
1857
|
self.update_cache(block.rstrip())
|
|
2128
|
except SystemExit:
|
|
1858
|
except SystemExit:
|
|
2129
|
pass
|
|
1859
|
pass
|
|
2130
|
except:
|
|
1860
|
except:
|
|
2131
|
badblocks.append(block.rstrip())
|
|
1861
|
badblocks.append(block.rstrip())
|
|
2132
|
if kw['quiet']: # restore stdout
|
|
1862
|
if kw['quiet']: # restore stdout
|
|
2133
|
sys.stdout.close()
|
|
1863
|
sys.stdout.close()
|
|
2134
|
sys.stdout = stdout_save
|
|
1864
|
sys.stdout = stdout_save
|
|
2135
|
print 'Finished replaying log file <%s>' % fname
|
|
1865
|
print 'Finished replaying log file <%s>' % fname
|
|
2136
|
if badblocks:
|
|
1866
|
if badblocks:
|
|
2137
|
print >> sys.stderr, \
|
|
1867
|
print >> sys.stderr, ('\nThe following lines/blocks in file '
|
|
2138
|
'\nThe following lines/blocks in file <%s> reported errors:' \
|
|
1868
|
'<%s> reported errors:' % fname)
|
|
2139
|
% fname
|
|
1869
|
|
|
2140
|
for badline in badblocks:
|
|
1870
|
for badline in badblocks:
|
|
2141
|
print >> sys.stderr, badline
|
|
1871
|
print >> sys.stderr, badline
|
|
2142
|
else: # regular file execution
|
|
1872
|
else: # regular file execution
|
|
2143
|
try:
|
|
1873
|
try:
|
|
2144
|
execfile(fname,*where)
|
|
1874
|
execfile(fname,*where)
|
|
2145
|
except SyntaxError:
|
|
1875
|
except SyntaxError:
|
|
2146
|
etype, evalue = sys.exc_info()[0:2]
|
|
1876
|
etype, evalue = sys.exc_info()[0:2]
|
|
2147
|
self.SyntaxTB(etype,evalue,[])
|
|
1877
|
self.SyntaxTB(etype,evalue,[])
|
|
2148
|
warn('Failure executing file: <%s>' % fname)
|
|
1878
|
warn('Failure executing file: <%s>' % fname)
|
|
2149
|
except SystemExit,status:
|
|
1879
|
except SystemExit,status:
|
|
2150
|
if not kw['exit_ignore']:
|
|
1880
|
if not kw['exit_ignore']:
|
|
2151
|
self.InteractiveTB()
|
|
1881
|
self.InteractiveTB()
|
|
2152
|
warn('Failure executing file: <%s>' % fname)
|
|
1882
|
warn('Failure executing file: <%s>' % fname)
|
|
2153
|
except:
|
|
1883
|
except:
|
|
2154
|
self.InteractiveTB()
|
|
1884
|
self.InteractiveTB()
|
|
2155
|
warn('Failure executing file: <%s>' % fname)
|
|
1885
|
warn('Failure executing file: <%s>' % fname)
|
|
2156
|
|
|
1886
|
|
|
2157
|
#************************* end of file <iplib.py> *****************************
|
|
1887
|
#************************* end of file <iplib.py> *****************************
|