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