##// END OF EJS Templates
Fix crash with a naked 'alias' call in ipythonrc file.
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

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