##// END OF EJS Templates
PromptManager fixes...
MinRK -
Show More
@@ -1,2707 +1,2734 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__ as builtin_mod
20 import __builtin__ as builtin_mod
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32
32
33 try:
33 try:
34 from contextlib import nested
34 from contextlib import nested
35 except:
35 except:
36 from IPython.utils.nested_context import nested
36 from IPython.utils.nested_context import nested
37
37
38 from IPython.config.configurable import SingletonConfigurable
38 from IPython.config.configurable import SingletonConfigurable
39 from IPython.core import debugger, oinspect
39 from IPython.core import debugger, oinspect
40 from IPython.core import history as ipcorehist
40 from IPython.core import history as ipcorehist
41 from IPython.core import page
41 from IPython.core import page
42 from IPython.core import prefilter
42 from IPython.core import prefilter
43 from IPython.core import shadowns
43 from IPython.core import shadowns
44 from IPython.core import ultratb
44 from IPython.core import ultratb
45 from IPython.core.alias import AliasManager, AliasError
45 from IPython.core.alias import AliasManager, AliasError
46 from IPython.core.autocall import ExitAutocall
46 from IPython.core.autocall import ExitAutocall
47 from IPython.core.builtin_trap import BuiltinTrap
47 from IPython.core.builtin_trap import BuiltinTrap
48 from IPython.core.compilerop import CachingCompiler
48 from IPython.core.compilerop import CachingCompiler
49 from IPython.core.display_trap import DisplayTrap
49 from IPython.core.display_trap import DisplayTrap
50 from IPython.core.displayhook import DisplayHook
50 from IPython.core.displayhook import DisplayHook
51 from IPython.core.displaypub import DisplayPublisher
51 from IPython.core.displaypub import DisplayPublisher
52 from IPython.core.error import TryNext, UsageError
52 from IPython.core.error import TryNext, UsageError
53 from IPython.core.extensions import ExtensionManager
53 from IPython.core.extensions import ExtensionManager
54 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
54 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
55 from IPython.core.formatters import DisplayFormatter
55 from IPython.core.formatters import DisplayFormatter
56 from IPython.core.history import HistoryManager
56 from IPython.core.history import HistoryManager
57 from IPython.core.inputsplitter import IPythonInputSplitter
57 from IPython.core.inputsplitter import IPythonInputSplitter
58 from IPython.core.logger import Logger
58 from IPython.core.logger import Logger
59 from IPython.core.macro import Macro
59 from IPython.core.macro import Macro
60 from IPython.core.magic import Magic
60 from IPython.core.magic import Magic
61 from IPython.core.payload import PayloadManager
61 from IPython.core.payload import PayloadManager
62 from IPython.core.plugin import PluginManager
62 from IPython.core.plugin import PluginManager
63 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
63 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
64 from IPython.core.profiledir import ProfileDir
64 from IPython.core.profiledir import ProfileDir
65 from IPython.core.pylabtools import pylab_activate
65 from IPython.core.pylabtools import pylab_activate
66 from IPython.core.prompts import PromptManager
66 from IPython.core.prompts import PromptManager
67 from IPython.external.Itpl import ItplNS
67 from IPython.external.Itpl import ItplNS
68 from IPython.utils import PyColorize
68 from IPython.utils import PyColorize
69 from IPython.utils import io
69 from IPython.utils import io
70 from IPython.utils import py3compat
70 from IPython.utils import py3compat
71 from IPython.utils.doctestreload import doctest_reload
71 from IPython.utils.doctestreload import doctest_reload
72 from IPython.utils.io import ask_yes_no, rprint
72 from IPython.utils.io import ask_yes_no, rprint
73 from IPython.utils.ipstruct import Struct
73 from IPython.utils.ipstruct import Struct
74 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
74 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
75 from IPython.utils.pickleshare import PickleShareDB
75 from IPython.utils.pickleshare import PickleShareDB
76 from IPython.utils.process import system, getoutput
76 from IPython.utils.process import system, getoutput
77 from IPython.utils.strdispatch import StrDispatch
77 from IPython.utils.strdispatch import StrDispatch
78 from IPython.utils.syspathcontext import prepended_to_syspath
78 from IPython.utils.syspathcontext import prepended_to_syspath
79 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
79 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
80 DollarFormatter)
80 DollarFormatter)
81 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
81 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
82 List, Unicode, Instance, Type)
82 List, Unicode, Instance, Type)
83 from IPython.utils.warn import warn, error, fatal
83 from IPython.utils.warn import warn, error, fatal
84 import IPython.core.hooks
84 import IPython.core.hooks
85
85
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87 # Globals
87 # Globals
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89
89
90 # compiled regexps for autoindent management
90 # compiled regexps for autoindent management
91 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
91 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
92
92
93 #-----------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------
94 # Utilities
94 # Utilities
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96
96
97 def softspace(file, newvalue):
97 def softspace(file, newvalue):
98 """Copied from code.py, to remove the dependency"""
98 """Copied from code.py, to remove the dependency"""
99
99
100 oldvalue = 0
100 oldvalue = 0
101 try:
101 try:
102 oldvalue = file.softspace
102 oldvalue = file.softspace
103 except AttributeError:
103 except AttributeError:
104 pass
104 pass
105 try:
105 try:
106 file.softspace = newvalue
106 file.softspace = newvalue
107 except (AttributeError, TypeError):
107 except (AttributeError, TypeError):
108 # "attribute-less object" or "read-only attributes"
108 # "attribute-less object" or "read-only attributes"
109 pass
109 pass
110 return oldvalue
110 return oldvalue
111
111
112
112
113 def no_op(*a, **kw): pass
113 def no_op(*a, **kw): pass
114
114
115 class NoOpContext(object):
115 class NoOpContext(object):
116 def __enter__(self): pass
116 def __enter__(self): pass
117 def __exit__(self, type, value, traceback): pass
117 def __exit__(self, type, value, traceback): pass
118 no_op_context = NoOpContext()
118 no_op_context = NoOpContext()
119
119
120 class SpaceInInput(Exception): pass
120 class SpaceInInput(Exception): pass
121
121
122 class Bunch: pass
122 class Bunch: pass
123
123
124
124
125 def get_default_colors():
125 def get_default_colors():
126 if sys.platform=='darwin':
126 if sys.platform=='darwin':
127 return "LightBG"
127 return "LightBG"
128 elif os.name=='nt':
128 elif os.name=='nt':
129 return 'Linux'
129 return 'Linux'
130 else:
130 else:
131 return 'Linux'
131 return 'Linux'
132
132
133
133
134 class SeparateUnicode(Unicode):
134 class SeparateUnicode(Unicode):
135 """A Unicode subclass to validate separate_in, separate_out, etc.
135 """A Unicode subclass to validate separate_in, separate_out, etc.
136
136
137 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
137 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
138 """
138 """
139
139
140 def validate(self, obj, value):
140 def validate(self, obj, value):
141 if value == '0': value = ''
141 if value == '0': value = ''
142 value = value.replace('\\n','\n')
142 value = value.replace('\\n','\n')
143 return super(SeparateUnicode, self).validate(obj, value)
143 return super(SeparateUnicode, self).validate(obj, value)
144
144
145
145
146 class ReadlineNoRecord(object):
146 class ReadlineNoRecord(object):
147 """Context manager to execute some code, then reload readline history
147 """Context manager to execute some code, then reload readline history
148 so that interactive input to the code doesn't appear when pressing up."""
148 so that interactive input to the code doesn't appear when pressing up."""
149 def __init__(self, shell):
149 def __init__(self, shell):
150 self.shell = shell
150 self.shell = shell
151 self._nested_level = 0
151 self._nested_level = 0
152
152
153 def __enter__(self):
153 def __enter__(self):
154 if self._nested_level == 0:
154 if self._nested_level == 0:
155 try:
155 try:
156 self.orig_length = self.current_length()
156 self.orig_length = self.current_length()
157 self.readline_tail = self.get_readline_tail()
157 self.readline_tail = self.get_readline_tail()
158 except (AttributeError, IndexError): # Can fail with pyreadline
158 except (AttributeError, IndexError): # Can fail with pyreadline
159 self.orig_length, self.readline_tail = 999999, []
159 self.orig_length, self.readline_tail = 999999, []
160 self._nested_level += 1
160 self._nested_level += 1
161
161
162 def __exit__(self, type, value, traceback):
162 def __exit__(self, type, value, traceback):
163 self._nested_level -= 1
163 self._nested_level -= 1
164 if self._nested_level == 0:
164 if self._nested_level == 0:
165 # Try clipping the end if it's got longer
165 # Try clipping the end if it's got longer
166 try:
166 try:
167 e = self.current_length() - self.orig_length
167 e = self.current_length() - self.orig_length
168 if e > 0:
168 if e > 0:
169 for _ in range(e):
169 for _ in range(e):
170 self.shell.readline.remove_history_item(self.orig_length)
170 self.shell.readline.remove_history_item(self.orig_length)
171
171
172 # If it still doesn't match, just reload readline history.
172 # If it still doesn't match, just reload readline history.
173 if self.current_length() != self.orig_length \
173 if self.current_length() != self.orig_length \
174 or self.get_readline_tail() != self.readline_tail:
174 or self.get_readline_tail() != self.readline_tail:
175 self.shell.refill_readline_hist()
175 self.shell.refill_readline_hist()
176 except (AttributeError, IndexError):
176 except (AttributeError, IndexError):
177 pass
177 pass
178 # Returning False will cause exceptions to propagate
178 # Returning False will cause exceptions to propagate
179 return False
179 return False
180
180
181 def current_length(self):
181 def current_length(self):
182 return self.shell.readline.get_current_history_length()
182 return self.shell.readline.get_current_history_length()
183
183
184 def get_readline_tail(self, n=10):
184 def get_readline_tail(self, n=10):
185 """Get the last n items in readline history."""
185 """Get the last n items in readline history."""
186 end = self.shell.readline.get_current_history_length() + 1
186 end = self.shell.readline.get_current_history_length() + 1
187 start = max(end-n, 1)
187 start = max(end-n, 1)
188 ghi = self.shell.readline.get_history_item
188 ghi = self.shell.readline.get_history_item
189 return [ghi(x) for x in range(start, end)]
189 return [ghi(x) for x in range(start, end)]
190
190
191
191
192 _autocall_help = """
192 _autocall_help = """
193 Make IPython automatically call any callable object even if
193 Make IPython automatically call any callable object even if
194 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
194 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
195 automatically. The value can be '0' to disable the feature, '1' for 'smart'
195 automatically. The value can be '0' to disable the feature, '1' for 'smart'
196 autocall, where it is not applied if there are no more arguments on the line,
196 autocall, where it is not applied if there are no more arguments on the line,
197 and '2' for 'full' autocall, where all callable objects are automatically
197 and '2' for 'full' autocall, where all callable objects are automatically
198 called (even if no arguments are present). The default is '1'.
198 called (even if no arguments are present). The default is '1'.
199 """
199 """
200
200
201 #-----------------------------------------------------------------------------
201 #-----------------------------------------------------------------------------
202 # Main IPython class
202 # Main IPython class
203 #-----------------------------------------------------------------------------
203 #-----------------------------------------------------------------------------
204
204
205 class InteractiveShell(SingletonConfigurable, Magic):
205 class InteractiveShell(SingletonConfigurable, Magic):
206 """An enhanced, interactive shell for Python."""
206 """An enhanced, interactive shell for Python."""
207
207
208 _instance = None
208 _instance = None
209
209
210 autocall = Enum((0,1,2), default_value=1, config=True, help=
210 autocall = Enum((0,1,2), default_value=1, config=True, help=
211 """
211 """
212 Make IPython automatically call any callable object even if you didn't
212 Make IPython automatically call any callable object even if you didn't
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 automatically. The value can be '0' to disable the feature, '1' for
214 automatically. The value can be '0' to disable the feature, '1' for
215 'smart' autocall, where it is not applied if there are no more
215 'smart' autocall, where it is not applied if there are no more
216 arguments on the line, and '2' for 'full' autocall, where all callable
216 arguments on the line, and '2' for 'full' autocall, where all callable
217 objects are automatically called (even if no arguments are present).
217 objects are automatically called (even if no arguments are present).
218 The default is '1'.
218 The default is '1'.
219 """
219 """
220 )
220 )
221 # TODO: remove all autoindent logic and put into frontends.
221 # TODO: remove all autoindent logic and put into frontends.
222 # We can't do this yet because even runlines uses the autoindent.
222 # We can't do this yet because even runlines uses the autoindent.
223 autoindent = CBool(True, config=True, help=
223 autoindent = CBool(True, config=True, help=
224 """
224 """
225 Autoindent IPython code entered interactively.
225 Autoindent IPython code entered interactively.
226 """
226 """
227 )
227 )
228 automagic = CBool(True, config=True, help=
228 automagic = CBool(True, config=True, help=
229 """
229 """
230 Enable magic commands to be called without the leading %.
230 Enable magic commands to be called without the leading %.
231 """
231 """
232 )
232 )
233 cache_size = Integer(1000, config=True, help=
233 cache_size = Integer(1000, config=True, help=
234 """
234 """
235 Set the size of the output cache. The default is 1000, you can
235 Set the size of the output cache. The default is 1000, you can
236 change it permanently in your config file. Setting it to 0 completely
236 change it permanently in your config file. Setting it to 0 completely
237 disables the caching system, and the minimum value accepted is 20 (if
237 disables the caching system, and the minimum value accepted is 20 (if
238 you provide a value less than 20, it is reset to 0 and a warning is
238 you provide a value less than 20, it is reset to 0 and a warning is
239 issued). This limit is defined because otherwise you'll spend more
239 issued). This limit is defined because otherwise you'll spend more
240 time re-flushing a too small cache than working
240 time re-flushing a too small cache than working
241 """
241 """
242 )
242 )
243 color_info = CBool(True, config=True, help=
243 color_info = CBool(True, config=True, help=
244 """
244 """
245 Use colors for displaying information about objects. Because this
245 Use colors for displaying information about objects. Because this
246 information is passed through a pager (like 'less'), and some pagers
246 information is passed through a pager (like 'less'), and some pagers
247 get confused with color codes, this capability can be turned off.
247 get confused with color codes, this capability can be turned off.
248 """
248 """
249 )
249 )
250 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
250 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
251 default_value=get_default_colors(), config=True,
251 default_value=get_default_colors(), config=True,
252 help="Set the color scheme (NoColor, Linux, or LightBG)."
252 help="Set the color scheme (NoColor, Linux, or LightBG)."
253 )
253 )
254 colors_force = CBool(False, help=
254 colors_force = CBool(False, help=
255 """
255 """
256 Force use of ANSI color codes, regardless of OS and readline
256 Force use of ANSI color codes, regardless of OS and readline
257 availability.
257 availability.
258 """
258 """
259 # FIXME: This is essentially a hack to allow ZMQShell to show colors
259 # FIXME: This is essentially a hack to allow ZMQShell to show colors
260 # without readline on Win32. When the ZMQ formatting system is
260 # without readline on Win32. When the ZMQ formatting system is
261 # refactored, this should be removed.
261 # refactored, this should be removed.
262 )
262 )
263 debug = CBool(False, config=True)
263 debug = CBool(False, config=True)
264 deep_reload = CBool(False, config=True, help=
264 deep_reload = CBool(False, config=True, help=
265 """
265 """
266 Enable deep (recursive) reloading by default. IPython can use the
266 Enable deep (recursive) reloading by default. IPython can use the
267 deep_reload module which reloads changes in modules recursively (it
267 deep_reload module which reloads changes in modules recursively (it
268 replaces the reload() function, so you don't need to change anything to
268 replaces the reload() function, so you don't need to change anything to
269 use it). deep_reload() forces a full reload of modules whose code may
269 use it). deep_reload() forces a full reload of modules whose code may
270 have changed, which the default reload() function does not. When
270 have changed, which the default reload() function does not. When
271 deep_reload is off, IPython will use the normal reload(), but
271 deep_reload is off, IPython will use the normal reload(), but
272 deep_reload will still be available as dreload().
272 deep_reload will still be available as dreload().
273 """
273 """
274 )
274 )
275 display_formatter = Instance(DisplayFormatter)
275 display_formatter = Instance(DisplayFormatter)
276 displayhook_class = Type(DisplayHook)
276 displayhook_class = Type(DisplayHook)
277 display_pub_class = Type(DisplayPublisher)
277 display_pub_class = Type(DisplayPublisher)
278
278
279 exit_now = CBool(False)
279 exit_now = CBool(False)
280 exiter = Instance(ExitAutocall)
280 exiter = Instance(ExitAutocall)
281 def _exiter_default(self):
281 def _exiter_default(self):
282 return ExitAutocall(self)
282 return ExitAutocall(self)
283 # Monotonically increasing execution counter
283 # Monotonically increasing execution counter
284 execution_count = Integer(1)
284 execution_count = Integer(1)
285 filename = Unicode("<ipython console>")
285 filename = Unicode("<ipython console>")
286 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
286 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
287
287
288 # Input splitter, to split entire cells of input into either individual
288 # Input splitter, to split entire cells of input into either individual
289 # interactive statements or whole blocks.
289 # interactive statements or whole blocks.
290 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
290 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
291 (), {})
291 (), {})
292 logstart = CBool(False, config=True, help=
292 logstart = CBool(False, config=True, help=
293 """
293 """
294 Start logging to the default log file.
294 Start logging to the default log file.
295 """
295 """
296 )
296 )
297 logfile = Unicode('', config=True, help=
297 logfile = Unicode('', config=True, help=
298 """
298 """
299 The name of the logfile to use.
299 The name of the logfile to use.
300 """
300 """
301 )
301 )
302 logappend = Unicode('', config=True, help=
302 logappend = Unicode('', config=True, help=
303 """
303 """
304 Start logging to the given file in append mode.
304 Start logging to the given file in append mode.
305 """
305 """
306 )
306 )
307 object_info_string_level = Enum((0,1,2), default_value=0,
307 object_info_string_level = Enum((0,1,2), default_value=0,
308 config=True)
308 config=True)
309 pdb = CBool(False, config=True, help=
309 pdb = CBool(False, config=True, help=
310 """
310 """
311 Automatically call the pdb debugger after every exception.
311 Automatically call the pdb debugger after every exception.
312 """
312 """
313 )
313 )
314 multiline_history = CBool(sys.platform != 'win32', config=True,
314 multiline_history = CBool(sys.platform != 'win32', config=True,
315 help="Save multi-line entries as one entry in readline history"
315 help="Save multi-line entries as one entry in readline history"
316 )
316 )
317
317
318 prompt_in1 = Unicode('In [\\#]: ', config=True)
318 # deprecated prompt traits:
319 prompt_in2 = Unicode(' .\\D.: ', config=True)
319
320 prompt_out = Unicode('Out[\\#]: ', config=True)
320 prompt_in1 = Unicode('In [\\#]: ', config=True,
321 prompts_pad_left = CBool(True, config=True)
321 help="Deprecated, use PromptManager.in_template")
322 prompt_in2 = Unicode(' .\\D.: ', config=True,
323 help="Deprecated, use PromptManager.in2_template")
324 prompt_out = Unicode('Out[\\#]: ', config=True,
325 help="Deprecated, use PromptManager.out_template")
326 prompts_pad_left = CBool(True, config=True,
327 help="Deprecated, use PromptManager.justify")
328
329 def _prompt_trait_changed(self, name, old, new):
330 table = {
331 'prompt_in1' : 'in_template',
332 'prompt_in2' : 'in2_template',
333 'prompt_out' : 'out_template',
334 'prompts_pad_left' : 'justify',
335 }
336 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
337 name=name, newname=table[name])
338 )
339 # protect against weird cases where self.config may not exist:
340 if self.config is not None:
341 # propagate to corresponding PromptManager trait
342 setattr(self.config.PromptManager, table[name], new)
343
344 _prompt_in1_changed = _prompt_trait_changed
345 _prompt_in2_changed = _prompt_trait_changed
346 _prompt_out_changed = _prompt_trait_changed
347 _prompt_pad_left_changed = _prompt_trait_changed
348
322 quiet = CBool(False, config=True)
349 quiet = CBool(False, config=True)
323
350
324 history_length = Integer(10000, config=True)
351 history_length = Integer(10000, config=True)
325
352
326 # The readline stuff will eventually be moved to the terminal subclass
353 # The readline stuff will eventually be moved to the terminal subclass
327 # but for now, we can't do that as readline is welded in everywhere.
354 # but for now, we can't do that as readline is welded in everywhere.
328 readline_use = CBool(True, config=True)
355 readline_use = CBool(True, config=True)
329 readline_remove_delims = Unicode('-/~', config=True)
356 readline_remove_delims = Unicode('-/~', config=True)
330 # don't use \M- bindings by default, because they
357 # don't use \M- bindings by default, because they
331 # conflict with 8-bit encodings. See gh-58,gh-88
358 # conflict with 8-bit encodings. See gh-58,gh-88
332 readline_parse_and_bind = List([
359 readline_parse_and_bind = List([
333 'tab: complete',
360 'tab: complete',
334 '"\C-l": clear-screen',
361 '"\C-l": clear-screen',
335 'set show-all-if-ambiguous on',
362 'set show-all-if-ambiguous on',
336 '"\C-o": tab-insert',
363 '"\C-o": tab-insert',
337 '"\C-r": reverse-search-history',
364 '"\C-r": reverse-search-history',
338 '"\C-s": forward-search-history',
365 '"\C-s": forward-search-history',
339 '"\C-p": history-search-backward',
366 '"\C-p": history-search-backward',
340 '"\C-n": history-search-forward',
367 '"\C-n": history-search-forward',
341 '"\e[A": history-search-backward',
368 '"\e[A": history-search-backward',
342 '"\e[B": history-search-forward',
369 '"\e[B": history-search-forward',
343 '"\C-k": kill-line',
370 '"\C-k": kill-line',
344 '"\C-u": unix-line-discard',
371 '"\C-u": unix-line-discard',
345 ], allow_none=False, config=True)
372 ], allow_none=False, config=True)
346
373
347 # TODO: this part of prompt management should be moved to the frontends.
374 # TODO: this part of prompt management should be moved to the frontends.
348 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
375 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
349 separate_in = SeparateUnicode('\n', config=True)
376 separate_in = SeparateUnicode('\n', config=True)
350 separate_out = SeparateUnicode('', config=True)
377 separate_out = SeparateUnicode('', config=True)
351 separate_out2 = SeparateUnicode('', config=True)
378 separate_out2 = SeparateUnicode('', config=True)
352 wildcards_case_sensitive = CBool(True, config=True)
379 wildcards_case_sensitive = CBool(True, config=True)
353 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
380 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
354 default_value='Context', config=True)
381 default_value='Context', config=True)
355
382
356 # Subcomponents of InteractiveShell
383 # Subcomponents of InteractiveShell
357 alias_manager = Instance('IPython.core.alias.AliasManager')
384 alias_manager = Instance('IPython.core.alias.AliasManager')
358 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
385 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
359 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
386 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
360 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
387 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
361 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
388 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
362 plugin_manager = Instance('IPython.core.plugin.PluginManager')
389 plugin_manager = Instance('IPython.core.plugin.PluginManager')
363 payload_manager = Instance('IPython.core.payload.PayloadManager')
390 payload_manager = Instance('IPython.core.payload.PayloadManager')
364 history_manager = Instance('IPython.core.history.HistoryManager')
391 history_manager = Instance('IPython.core.history.HistoryManager')
365
392
366 profile_dir = Instance('IPython.core.application.ProfileDir')
393 profile_dir = Instance('IPython.core.application.ProfileDir')
367 @property
394 @property
368 def profile(self):
395 def profile(self):
369 if self.profile_dir is not None:
396 if self.profile_dir is not None:
370 name = os.path.basename(self.profile_dir.location)
397 name = os.path.basename(self.profile_dir.location)
371 return name.replace('profile_','')
398 return name.replace('profile_','')
372
399
373
400
374 # Private interface
401 # Private interface
375 _post_execute = Instance(dict)
402 _post_execute = Instance(dict)
376
403
377 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
404 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
378 user_module=None, user_ns=None,
405 user_module=None, user_ns=None,
379 custom_exceptions=((), None)):
406 custom_exceptions=((), None)):
380
407
381 # This is where traits with a config_key argument are updated
408 # This is where traits with a config_key argument are updated
382 # from the values on config.
409 # from the values on config.
383 super(InteractiveShell, self).__init__(config=config)
410 super(InteractiveShell, self).__init__(config=config)
384 self.configurables = [self]
411 self.configurables = [self]
385
412
386 # These are relatively independent and stateless
413 # These are relatively independent and stateless
387 self.init_ipython_dir(ipython_dir)
414 self.init_ipython_dir(ipython_dir)
388 self.init_profile_dir(profile_dir)
415 self.init_profile_dir(profile_dir)
389 self.init_instance_attrs()
416 self.init_instance_attrs()
390 self.init_environment()
417 self.init_environment()
391
418
392 # Create namespaces (user_ns, user_global_ns, etc.)
419 # Create namespaces (user_ns, user_global_ns, etc.)
393 self.init_create_namespaces(user_module, user_ns)
420 self.init_create_namespaces(user_module, user_ns)
394 # This has to be done after init_create_namespaces because it uses
421 # This has to be done after init_create_namespaces because it uses
395 # something in self.user_ns, but before init_sys_modules, which
422 # something in self.user_ns, but before init_sys_modules, which
396 # is the first thing to modify sys.
423 # is the first thing to modify sys.
397 # TODO: When we override sys.stdout and sys.stderr before this class
424 # TODO: When we override sys.stdout and sys.stderr before this class
398 # is created, we are saving the overridden ones here. Not sure if this
425 # is created, we are saving the overridden ones here. Not sure if this
399 # is what we want to do.
426 # is what we want to do.
400 self.save_sys_module_state()
427 self.save_sys_module_state()
401 self.init_sys_modules()
428 self.init_sys_modules()
402
429
403 # While we're trying to have each part of the code directly access what
430 # While we're trying to have each part of the code directly access what
404 # it needs without keeping redundant references to objects, we have too
431 # it needs without keeping redundant references to objects, we have too
405 # much legacy code that expects ip.db to exist.
432 # much legacy code that expects ip.db to exist.
406 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
433 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
407
434
408 self.init_history()
435 self.init_history()
409 self.init_encoding()
436 self.init_encoding()
410 self.init_prefilter()
437 self.init_prefilter()
411
438
412 Magic.__init__(self, self)
439 Magic.__init__(self, self)
413
440
414 self.init_syntax_highlighting()
441 self.init_syntax_highlighting()
415 self.init_hooks()
442 self.init_hooks()
416 self.init_pushd_popd_magic()
443 self.init_pushd_popd_magic()
417 # self.init_traceback_handlers use to be here, but we moved it below
444 # self.init_traceback_handlers use to be here, but we moved it below
418 # because it and init_io have to come after init_readline.
445 # because it and init_io have to come after init_readline.
419 self.init_user_ns()
446 self.init_user_ns()
420 self.init_logger()
447 self.init_logger()
421 self.init_alias()
448 self.init_alias()
422 self.init_builtins()
449 self.init_builtins()
423
450
424 # pre_config_initialization
451 # pre_config_initialization
425
452
426 # The next section should contain everything that was in ipmaker.
453 # The next section should contain everything that was in ipmaker.
427 self.init_logstart()
454 self.init_logstart()
428
455
429 # The following was in post_config_initialization
456 # The following was in post_config_initialization
430 self.init_inspector()
457 self.init_inspector()
431 # init_readline() must come before init_io(), because init_io uses
458 # init_readline() must come before init_io(), because init_io uses
432 # readline related things.
459 # readline related things.
433 self.init_readline()
460 self.init_readline()
434 # We save this here in case user code replaces raw_input, but it needs
461 # We save this here in case user code replaces raw_input, but it needs
435 # to be after init_readline(), because PyPy's readline works by replacing
462 # to be after init_readline(), because PyPy's readline works by replacing
436 # raw_input.
463 # raw_input.
437 if py3compat.PY3:
464 if py3compat.PY3:
438 self.raw_input_original = input
465 self.raw_input_original = input
439 else:
466 else:
440 self.raw_input_original = raw_input
467 self.raw_input_original = raw_input
441 # init_completer must come after init_readline, because it needs to
468 # init_completer must come after init_readline, because it needs to
442 # know whether readline is present or not system-wide to configure the
469 # know whether readline is present or not system-wide to configure the
443 # completers, since the completion machinery can now operate
470 # completers, since the completion machinery can now operate
444 # independently of readline (e.g. over the network)
471 # independently of readline (e.g. over the network)
445 self.init_completer()
472 self.init_completer()
446 # TODO: init_io() needs to happen before init_traceback handlers
473 # TODO: init_io() needs to happen before init_traceback handlers
447 # because the traceback handlers hardcode the stdout/stderr streams.
474 # because the traceback handlers hardcode the stdout/stderr streams.
448 # This logic in in debugger.Pdb and should eventually be changed.
475 # This logic in in debugger.Pdb and should eventually be changed.
449 self.init_io()
476 self.init_io()
450 self.init_traceback_handlers(custom_exceptions)
477 self.init_traceback_handlers(custom_exceptions)
451 self.init_prompts()
478 self.init_prompts()
452 self.init_display_formatter()
479 self.init_display_formatter()
453 self.init_display_pub()
480 self.init_display_pub()
454 self.init_displayhook()
481 self.init_displayhook()
455 self.init_reload_doctest()
482 self.init_reload_doctest()
456 self.init_magics()
483 self.init_magics()
457 self.init_pdb()
484 self.init_pdb()
458 self.init_extension_manager()
485 self.init_extension_manager()
459 self.init_plugin_manager()
486 self.init_plugin_manager()
460 self.init_payload()
487 self.init_payload()
461 self.hooks.late_startup_hook()
488 self.hooks.late_startup_hook()
462 atexit.register(self.atexit_operations)
489 atexit.register(self.atexit_operations)
463
490
464 def get_ipython(self):
491 def get_ipython(self):
465 """Return the currently running IPython instance."""
492 """Return the currently running IPython instance."""
466 return self
493 return self
467
494
468 #-------------------------------------------------------------------------
495 #-------------------------------------------------------------------------
469 # Trait changed handlers
496 # Trait changed handlers
470 #-------------------------------------------------------------------------
497 #-------------------------------------------------------------------------
471
498
472 def _ipython_dir_changed(self, name, new):
499 def _ipython_dir_changed(self, name, new):
473 if not os.path.isdir(new):
500 if not os.path.isdir(new):
474 os.makedirs(new, mode = 0777)
501 os.makedirs(new, mode = 0777)
475
502
476 def set_autoindent(self,value=None):
503 def set_autoindent(self,value=None):
477 """Set the autoindent flag, checking for readline support.
504 """Set the autoindent flag, checking for readline support.
478
505
479 If called with no arguments, it acts as a toggle."""
506 If called with no arguments, it acts as a toggle."""
480
507
481 if value != 0 and not self.has_readline:
508 if value != 0 and not self.has_readline:
482 if os.name == 'posix':
509 if os.name == 'posix':
483 warn("The auto-indent feature requires the readline library")
510 warn("The auto-indent feature requires the readline library")
484 self.autoindent = 0
511 self.autoindent = 0
485 return
512 return
486 if value is None:
513 if value is None:
487 self.autoindent = not self.autoindent
514 self.autoindent = not self.autoindent
488 else:
515 else:
489 self.autoindent = value
516 self.autoindent = value
490
517
491 #-------------------------------------------------------------------------
518 #-------------------------------------------------------------------------
492 # init_* methods called by __init__
519 # init_* methods called by __init__
493 #-------------------------------------------------------------------------
520 #-------------------------------------------------------------------------
494
521
495 def init_ipython_dir(self, ipython_dir):
522 def init_ipython_dir(self, ipython_dir):
496 if ipython_dir is not None:
523 if ipython_dir is not None:
497 self.ipython_dir = ipython_dir
524 self.ipython_dir = ipython_dir
498 return
525 return
499
526
500 self.ipython_dir = get_ipython_dir()
527 self.ipython_dir = get_ipython_dir()
501
528
502 def init_profile_dir(self, profile_dir):
529 def init_profile_dir(self, profile_dir):
503 if profile_dir is not None:
530 if profile_dir is not None:
504 self.profile_dir = profile_dir
531 self.profile_dir = profile_dir
505 return
532 return
506 self.profile_dir =\
533 self.profile_dir =\
507 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
534 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
508
535
509 def init_instance_attrs(self):
536 def init_instance_attrs(self):
510 self.more = False
537 self.more = False
511
538
512 # command compiler
539 # command compiler
513 self.compile = CachingCompiler()
540 self.compile = CachingCompiler()
514
541
515 # Make an empty namespace, which extension writers can rely on both
542 # Make an empty namespace, which extension writers can rely on both
516 # existing and NEVER being used by ipython itself. This gives them a
543 # existing and NEVER being used by ipython itself. This gives them a
517 # convenient location for storing additional information and state
544 # convenient location for storing additional information and state
518 # their extensions may require, without fear of collisions with other
545 # their extensions may require, without fear of collisions with other
519 # ipython names that may develop later.
546 # ipython names that may develop later.
520 self.meta = Struct()
547 self.meta = Struct()
521
548
522 # Temporary files used for various purposes. Deleted at exit.
549 # Temporary files used for various purposes. Deleted at exit.
523 self.tempfiles = []
550 self.tempfiles = []
524
551
525 # Keep track of readline usage (later set by init_readline)
552 # Keep track of readline usage (later set by init_readline)
526 self.has_readline = False
553 self.has_readline = False
527
554
528 # keep track of where we started running (mainly for crash post-mortem)
555 # keep track of where we started running (mainly for crash post-mortem)
529 # This is not being used anywhere currently.
556 # This is not being used anywhere currently.
530 self.starting_dir = os.getcwdu()
557 self.starting_dir = os.getcwdu()
531
558
532 # Indentation management
559 # Indentation management
533 self.indent_current_nsp = 0
560 self.indent_current_nsp = 0
534
561
535 # Dict to track post-execution functions that have been registered
562 # Dict to track post-execution functions that have been registered
536 self._post_execute = {}
563 self._post_execute = {}
537
564
538 def init_environment(self):
565 def init_environment(self):
539 """Any changes we need to make to the user's environment."""
566 """Any changes we need to make to the user's environment."""
540 pass
567 pass
541
568
542 def init_encoding(self):
569 def init_encoding(self):
543 # Get system encoding at startup time. Certain terminals (like Emacs
570 # Get system encoding at startup time. Certain terminals (like Emacs
544 # under Win32 have it set to None, and we need to have a known valid
571 # under Win32 have it set to None, and we need to have a known valid
545 # encoding to use in the raw_input() method
572 # encoding to use in the raw_input() method
546 try:
573 try:
547 self.stdin_encoding = sys.stdin.encoding or 'ascii'
574 self.stdin_encoding = sys.stdin.encoding or 'ascii'
548 except AttributeError:
575 except AttributeError:
549 self.stdin_encoding = 'ascii'
576 self.stdin_encoding = 'ascii'
550
577
551 def init_syntax_highlighting(self):
578 def init_syntax_highlighting(self):
552 # Python source parser/formatter for syntax highlighting
579 # Python source parser/formatter for syntax highlighting
553 pyformat = PyColorize.Parser().format
580 pyformat = PyColorize.Parser().format
554 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
581 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
555
582
556 def init_pushd_popd_magic(self):
583 def init_pushd_popd_magic(self):
557 # for pushd/popd management
584 # for pushd/popd management
558 self.home_dir = get_home_dir()
585 self.home_dir = get_home_dir()
559
586
560 self.dir_stack = []
587 self.dir_stack = []
561
588
562 def init_logger(self):
589 def init_logger(self):
563 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
590 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
564 logmode='rotate')
591 logmode='rotate')
565
592
566 def init_logstart(self):
593 def init_logstart(self):
567 """Initialize logging in case it was requested at the command line.
594 """Initialize logging in case it was requested at the command line.
568 """
595 """
569 if self.logappend:
596 if self.logappend:
570 self.magic_logstart(self.logappend + ' append')
597 self.magic_logstart(self.logappend + ' append')
571 elif self.logfile:
598 elif self.logfile:
572 self.magic_logstart(self.logfile)
599 self.magic_logstart(self.logfile)
573 elif self.logstart:
600 elif self.logstart:
574 self.magic_logstart()
601 self.magic_logstart()
575
602
576 def init_builtins(self):
603 def init_builtins(self):
577 self.builtin_trap = BuiltinTrap(shell=self)
604 self.builtin_trap = BuiltinTrap(shell=self)
578
605
579 def init_inspector(self):
606 def init_inspector(self):
580 # Object inspector
607 # Object inspector
581 self.inspector = oinspect.Inspector(oinspect.InspectColors,
608 self.inspector = oinspect.Inspector(oinspect.InspectColors,
582 PyColorize.ANSICodeColors,
609 PyColorize.ANSICodeColors,
583 'NoColor',
610 'NoColor',
584 self.object_info_string_level)
611 self.object_info_string_level)
585
612
586 def init_io(self):
613 def init_io(self):
587 # This will just use sys.stdout and sys.stderr. If you want to
614 # This will just use sys.stdout and sys.stderr. If you want to
588 # override sys.stdout and sys.stderr themselves, you need to do that
615 # override sys.stdout and sys.stderr themselves, you need to do that
589 # *before* instantiating this class, because io holds onto
616 # *before* instantiating this class, because io holds onto
590 # references to the underlying streams.
617 # references to the underlying streams.
591 if sys.platform == 'win32' and self.has_readline:
618 if sys.platform == 'win32' and self.has_readline:
592 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
619 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
593 else:
620 else:
594 io.stdout = io.IOStream(sys.stdout)
621 io.stdout = io.IOStream(sys.stdout)
595 io.stderr = io.IOStream(sys.stderr)
622 io.stderr = io.IOStream(sys.stderr)
596
623
597 def init_prompts(self):
624 def init_prompts(self):
598 self.prompt_manager = PromptManager(shell=self, config=self.config)
625 self.prompt_manager = PromptManager(shell=self, config=self.config)
599 self.configurables.append(self.prompt_manager)
626 self.configurables.append(self.prompt_manager)
600
627
601 def init_display_formatter(self):
628 def init_display_formatter(self):
602 self.display_formatter = DisplayFormatter(config=self.config)
629 self.display_formatter = DisplayFormatter(config=self.config)
603 self.configurables.append(self.display_formatter)
630 self.configurables.append(self.display_formatter)
604
631
605 def init_display_pub(self):
632 def init_display_pub(self):
606 self.display_pub = self.display_pub_class(config=self.config)
633 self.display_pub = self.display_pub_class(config=self.config)
607 self.configurables.append(self.display_pub)
634 self.configurables.append(self.display_pub)
608
635
609 def init_displayhook(self):
636 def init_displayhook(self):
610 # Initialize displayhook, set in/out prompts and printing system
637 # Initialize displayhook, set in/out prompts and printing system
611 self.displayhook = self.displayhook_class(
638 self.displayhook = self.displayhook_class(
612 config=self.config,
639 config=self.config,
613 shell=self,
640 shell=self,
614 cache_size=self.cache_size,
641 cache_size=self.cache_size,
615 )
642 )
616 self.configurables.append(self.displayhook)
643 self.configurables.append(self.displayhook)
617 # This is a context manager that installs/revmoes the displayhook at
644 # This is a context manager that installs/revmoes the displayhook at
618 # the appropriate time.
645 # the appropriate time.
619 self.display_trap = DisplayTrap(hook=self.displayhook)
646 self.display_trap = DisplayTrap(hook=self.displayhook)
620
647
621 def init_reload_doctest(self):
648 def init_reload_doctest(self):
622 # Do a proper resetting of doctest, including the necessary displayhook
649 # Do a proper resetting of doctest, including the necessary displayhook
623 # monkeypatching
650 # monkeypatching
624 try:
651 try:
625 doctest_reload()
652 doctest_reload()
626 except ImportError:
653 except ImportError:
627 warn("doctest module does not exist.")
654 warn("doctest module does not exist.")
628
655
629 #-------------------------------------------------------------------------
656 #-------------------------------------------------------------------------
630 # Things related to injections into the sys module
657 # Things related to injections into the sys module
631 #-------------------------------------------------------------------------
658 #-------------------------------------------------------------------------
632
659
633 def save_sys_module_state(self):
660 def save_sys_module_state(self):
634 """Save the state of hooks in the sys module.
661 """Save the state of hooks in the sys module.
635
662
636 This has to be called after self.user_module is created.
663 This has to be called after self.user_module is created.
637 """
664 """
638 self._orig_sys_module_state = {}
665 self._orig_sys_module_state = {}
639 self._orig_sys_module_state['stdin'] = sys.stdin
666 self._orig_sys_module_state['stdin'] = sys.stdin
640 self._orig_sys_module_state['stdout'] = sys.stdout
667 self._orig_sys_module_state['stdout'] = sys.stdout
641 self._orig_sys_module_state['stderr'] = sys.stderr
668 self._orig_sys_module_state['stderr'] = sys.stderr
642 self._orig_sys_module_state['excepthook'] = sys.excepthook
669 self._orig_sys_module_state['excepthook'] = sys.excepthook
643 self._orig_sys_modules_main_name = self.user_module.__name__
670 self._orig_sys_modules_main_name = self.user_module.__name__
644
671
645 def restore_sys_module_state(self):
672 def restore_sys_module_state(self):
646 """Restore the state of the sys module."""
673 """Restore the state of the sys module."""
647 try:
674 try:
648 for k, v in self._orig_sys_module_state.iteritems():
675 for k, v in self._orig_sys_module_state.iteritems():
649 setattr(sys, k, v)
676 setattr(sys, k, v)
650 except AttributeError:
677 except AttributeError:
651 pass
678 pass
652 # Reset what what done in self.init_sys_modules
679 # Reset what what done in self.init_sys_modules
653 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
680 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
654
681
655 #-------------------------------------------------------------------------
682 #-------------------------------------------------------------------------
656 # Things related to hooks
683 # Things related to hooks
657 #-------------------------------------------------------------------------
684 #-------------------------------------------------------------------------
658
685
659 def init_hooks(self):
686 def init_hooks(self):
660 # hooks holds pointers used for user-side customizations
687 # hooks holds pointers used for user-side customizations
661 self.hooks = Struct()
688 self.hooks = Struct()
662
689
663 self.strdispatchers = {}
690 self.strdispatchers = {}
664
691
665 # Set all default hooks, defined in the IPython.hooks module.
692 # Set all default hooks, defined in the IPython.hooks module.
666 hooks = IPython.core.hooks
693 hooks = IPython.core.hooks
667 for hook_name in hooks.__all__:
694 for hook_name in hooks.__all__:
668 # default hooks have priority 100, i.e. low; user hooks should have
695 # default hooks have priority 100, i.e. low; user hooks should have
669 # 0-100 priority
696 # 0-100 priority
670 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
697 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
671
698
672 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
699 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
673 """set_hook(name,hook) -> sets an internal IPython hook.
700 """set_hook(name,hook) -> sets an internal IPython hook.
674
701
675 IPython exposes some of its internal API as user-modifiable hooks. By
702 IPython exposes some of its internal API as user-modifiable hooks. By
676 adding your function to one of these hooks, you can modify IPython's
703 adding your function to one of these hooks, you can modify IPython's
677 behavior to call at runtime your own routines."""
704 behavior to call at runtime your own routines."""
678
705
679 # At some point in the future, this should validate the hook before it
706 # At some point in the future, this should validate the hook before it
680 # accepts it. Probably at least check that the hook takes the number
707 # accepts it. Probably at least check that the hook takes the number
681 # of args it's supposed to.
708 # of args it's supposed to.
682
709
683 f = types.MethodType(hook,self)
710 f = types.MethodType(hook,self)
684
711
685 # check if the hook is for strdispatcher first
712 # check if the hook is for strdispatcher first
686 if str_key is not None:
713 if str_key is not None:
687 sdp = self.strdispatchers.get(name, StrDispatch())
714 sdp = self.strdispatchers.get(name, StrDispatch())
688 sdp.add_s(str_key, f, priority )
715 sdp.add_s(str_key, f, priority )
689 self.strdispatchers[name] = sdp
716 self.strdispatchers[name] = sdp
690 return
717 return
691 if re_key is not None:
718 if re_key is not None:
692 sdp = self.strdispatchers.get(name, StrDispatch())
719 sdp = self.strdispatchers.get(name, StrDispatch())
693 sdp.add_re(re.compile(re_key), f, priority )
720 sdp.add_re(re.compile(re_key), f, priority )
694 self.strdispatchers[name] = sdp
721 self.strdispatchers[name] = sdp
695 return
722 return
696
723
697 dp = getattr(self.hooks, name, None)
724 dp = getattr(self.hooks, name, None)
698 if name not in IPython.core.hooks.__all__:
725 if name not in IPython.core.hooks.__all__:
699 print "Warning! Hook '%s' is not one of %s" % \
726 print "Warning! Hook '%s' is not one of %s" % \
700 (name, IPython.core.hooks.__all__ )
727 (name, IPython.core.hooks.__all__ )
701 if not dp:
728 if not dp:
702 dp = IPython.core.hooks.CommandChainDispatcher()
729 dp = IPython.core.hooks.CommandChainDispatcher()
703
730
704 try:
731 try:
705 dp.add(f,priority)
732 dp.add(f,priority)
706 except AttributeError:
733 except AttributeError:
707 # it was not commandchain, plain old func - replace
734 # it was not commandchain, plain old func - replace
708 dp = f
735 dp = f
709
736
710 setattr(self.hooks,name, dp)
737 setattr(self.hooks,name, dp)
711
738
712 def register_post_execute(self, func):
739 def register_post_execute(self, func):
713 """Register a function for calling after code execution.
740 """Register a function for calling after code execution.
714 """
741 """
715 if not callable(func):
742 if not callable(func):
716 raise ValueError('argument %s must be callable' % func)
743 raise ValueError('argument %s must be callable' % func)
717 self._post_execute[func] = True
744 self._post_execute[func] = True
718
745
719 #-------------------------------------------------------------------------
746 #-------------------------------------------------------------------------
720 # Things related to the "main" module
747 # Things related to the "main" module
721 #-------------------------------------------------------------------------
748 #-------------------------------------------------------------------------
722
749
723 def new_main_mod(self,ns=None):
750 def new_main_mod(self,ns=None):
724 """Return a new 'main' module object for user code execution.
751 """Return a new 'main' module object for user code execution.
725 """
752 """
726 main_mod = self._user_main_module
753 main_mod = self._user_main_module
727 init_fakemod_dict(main_mod,ns)
754 init_fakemod_dict(main_mod,ns)
728 return main_mod
755 return main_mod
729
756
730 def cache_main_mod(self,ns,fname):
757 def cache_main_mod(self,ns,fname):
731 """Cache a main module's namespace.
758 """Cache a main module's namespace.
732
759
733 When scripts are executed via %run, we must keep a reference to the
760 When scripts are executed via %run, we must keep a reference to the
734 namespace of their __main__ module (a FakeModule instance) around so
761 namespace of their __main__ module (a FakeModule instance) around so
735 that Python doesn't clear it, rendering objects defined therein
762 that Python doesn't clear it, rendering objects defined therein
736 useless.
763 useless.
737
764
738 This method keeps said reference in a private dict, keyed by the
765 This method keeps said reference in a private dict, keyed by the
739 absolute path of the module object (which corresponds to the script
766 absolute path of the module object (which corresponds to the script
740 path). This way, for multiple executions of the same script we only
767 path). This way, for multiple executions of the same script we only
741 keep one copy of the namespace (the last one), thus preventing memory
768 keep one copy of the namespace (the last one), thus preventing memory
742 leaks from old references while allowing the objects from the last
769 leaks from old references while allowing the objects from the last
743 execution to be accessible.
770 execution to be accessible.
744
771
745 Note: we can not allow the actual FakeModule instances to be deleted,
772 Note: we can not allow the actual FakeModule instances to be deleted,
746 because of how Python tears down modules (it hard-sets all their
773 because of how Python tears down modules (it hard-sets all their
747 references to None without regard for reference counts). This method
774 references to None without regard for reference counts). This method
748 must therefore make a *copy* of the given namespace, to allow the
775 must therefore make a *copy* of the given namespace, to allow the
749 original module's __dict__ to be cleared and reused.
776 original module's __dict__ to be cleared and reused.
750
777
751
778
752 Parameters
779 Parameters
753 ----------
780 ----------
754 ns : a namespace (a dict, typically)
781 ns : a namespace (a dict, typically)
755
782
756 fname : str
783 fname : str
757 Filename associated with the namespace.
784 Filename associated with the namespace.
758
785
759 Examples
786 Examples
760 --------
787 --------
761
788
762 In [10]: import IPython
789 In [10]: import IPython
763
790
764 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
791 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
765
792
766 In [12]: IPython.__file__ in _ip._main_ns_cache
793 In [12]: IPython.__file__ in _ip._main_ns_cache
767 Out[12]: True
794 Out[12]: True
768 """
795 """
769 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
796 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
770
797
771 def clear_main_mod_cache(self):
798 def clear_main_mod_cache(self):
772 """Clear the cache of main modules.
799 """Clear the cache of main modules.
773
800
774 Mainly for use by utilities like %reset.
801 Mainly for use by utilities like %reset.
775
802
776 Examples
803 Examples
777 --------
804 --------
778
805
779 In [15]: import IPython
806 In [15]: import IPython
780
807
781 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
808 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
782
809
783 In [17]: len(_ip._main_ns_cache) > 0
810 In [17]: len(_ip._main_ns_cache) > 0
784 Out[17]: True
811 Out[17]: True
785
812
786 In [18]: _ip.clear_main_mod_cache()
813 In [18]: _ip.clear_main_mod_cache()
787
814
788 In [19]: len(_ip._main_ns_cache) == 0
815 In [19]: len(_ip._main_ns_cache) == 0
789 Out[19]: True
816 Out[19]: True
790 """
817 """
791 self._main_ns_cache.clear()
818 self._main_ns_cache.clear()
792
819
793 #-------------------------------------------------------------------------
820 #-------------------------------------------------------------------------
794 # Things related to debugging
821 # Things related to debugging
795 #-------------------------------------------------------------------------
822 #-------------------------------------------------------------------------
796
823
797 def init_pdb(self):
824 def init_pdb(self):
798 # Set calling of pdb on exceptions
825 # Set calling of pdb on exceptions
799 # self.call_pdb is a property
826 # self.call_pdb is a property
800 self.call_pdb = self.pdb
827 self.call_pdb = self.pdb
801
828
802 def _get_call_pdb(self):
829 def _get_call_pdb(self):
803 return self._call_pdb
830 return self._call_pdb
804
831
805 def _set_call_pdb(self,val):
832 def _set_call_pdb(self,val):
806
833
807 if val not in (0,1,False,True):
834 if val not in (0,1,False,True):
808 raise ValueError,'new call_pdb value must be boolean'
835 raise ValueError,'new call_pdb value must be boolean'
809
836
810 # store value in instance
837 # store value in instance
811 self._call_pdb = val
838 self._call_pdb = val
812
839
813 # notify the actual exception handlers
840 # notify the actual exception handlers
814 self.InteractiveTB.call_pdb = val
841 self.InteractiveTB.call_pdb = val
815
842
816 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
843 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
817 'Control auto-activation of pdb at exceptions')
844 'Control auto-activation of pdb at exceptions')
818
845
819 def debugger(self,force=False):
846 def debugger(self,force=False):
820 """Call the pydb/pdb debugger.
847 """Call the pydb/pdb debugger.
821
848
822 Keywords:
849 Keywords:
823
850
824 - force(False): by default, this routine checks the instance call_pdb
851 - force(False): by default, this routine checks the instance call_pdb
825 flag and does not actually invoke the debugger if the flag is false.
852 flag and does not actually invoke the debugger if the flag is false.
826 The 'force' option forces the debugger to activate even if the flag
853 The 'force' option forces the debugger to activate even if the flag
827 is false.
854 is false.
828 """
855 """
829
856
830 if not (force or self.call_pdb):
857 if not (force or self.call_pdb):
831 return
858 return
832
859
833 if not hasattr(sys,'last_traceback'):
860 if not hasattr(sys,'last_traceback'):
834 error('No traceback has been produced, nothing to debug.')
861 error('No traceback has been produced, nothing to debug.')
835 return
862 return
836
863
837 # use pydb if available
864 # use pydb if available
838 if debugger.has_pydb:
865 if debugger.has_pydb:
839 from pydb import pm
866 from pydb import pm
840 else:
867 else:
841 # fallback to our internal debugger
868 # fallback to our internal debugger
842 pm = lambda : self.InteractiveTB.debugger(force=True)
869 pm = lambda : self.InteractiveTB.debugger(force=True)
843
870
844 with self.readline_no_record:
871 with self.readline_no_record:
845 pm()
872 pm()
846
873
847 #-------------------------------------------------------------------------
874 #-------------------------------------------------------------------------
848 # Things related to IPython's various namespaces
875 # Things related to IPython's various namespaces
849 #-------------------------------------------------------------------------
876 #-------------------------------------------------------------------------
850
877
851 def init_create_namespaces(self, user_module=None, user_ns=None):
878 def init_create_namespaces(self, user_module=None, user_ns=None):
852 # Create the namespace where the user will operate. user_ns is
879 # Create the namespace where the user will operate. user_ns is
853 # normally the only one used, and it is passed to the exec calls as
880 # normally the only one used, and it is passed to the exec calls as
854 # the locals argument. But we do carry a user_global_ns namespace
881 # the locals argument. But we do carry a user_global_ns namespace
855 # given as the exec 'globals' argument, This is useful in embedding
882 # given as the exec 'globals' argument, This is useful in embedding
856 # situations where the ipython shell opens in a context where the
883 # situations where the ipython shell opens in a context where the
857 # distinction between locals and globals is meaningful. For
884 # distinction between locals and globals is meaningful. For
858 # non-embedded contexts, it is just the same object as the user_ns dict.
885 # non-embedded contexts, it is just the same object as the user_ns dict.
859
886
860 # FIXME. For some strange reason, __builtins__ is showing up at user
887 # FIXME. For some strange reason, __builtins__ is showing up at user
861 # level as a dict instead of a module. This is a manual fix, but I
888 # level as a dict instead of a module. This is a manual fix, but I
862 # should really track down where the problem is coming from. Alex
889 # should really track down where the problem is coming from. Alex
863 # Schmolck reported this problem first.
890 # Schmolck reported this problem first.
864
891
865 # A useful post by Alex Martelli on this topic:
892 # A useful post by Alex Martelli on this topic:
866 # Re: inconsistent value from __builtins__
893 # Re: inconsistent value from __builtins__
867 # Von: Alex Martelli <aleaxit@yahoo.com>
894 # Von: Alex Martelli <aleaxit@yahoo.com>
868 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
895 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
869 # Gruppen: comp.lang.python
896 # Gruppen: comp.lang.python
870
897
871 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
898 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
872 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
899 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
873 # > <type 'dict'>
900 # > <type 'dict'>
874 # > >>> print type(__builtins__)
901 # > >>> print type(__builtins__)
875 # > <type 'module'>
902 # > <type 'module'>
876 # > Is this difference in return value intentional?
903 # > Is this difference in return value intentional?
877
904
878 # Well, it's documented that '__builtins__' can be either a dictionary
905 # Well, it's documented that '__builtins__' can be either a dictionary
879 # or a module, and it's been that way for a long time. Whether it's
906 # or a module, and it's been that way for a long time. Whether it's
880 # intentional (or sensible), I don't know. In any case, the idea is
907 # intentional (or sensible), I don't know. In any case, the idea is
881 # that if you need to access the built-in namespace directly, you
908 # that if you need to access the built-in namespace directly, you
882 # should start with "import __builtin__" (note, no 's') which will
909 # should start with "import __builtin__" (note, no 's') which will
883 # definitely give you a module. Yeah, it's somewhat confusing:-(.
910 # definitely give you a module. Yeah, it's somewhat confusing:-(.
884
911
885 # These routines return a properly built module and dict as needed by
912 # These routines return a properly built module and dict as needed by
886 # the rest of the code, and can also be used by extension writers to
913 # the rest of the code, and can also be used by extension writers to
887 # generate properly initialized namespaces.
914 # generate properly initialized namespaces.
888 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
915 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
889
916
890 # A record of hidden variables we have added to the user namespace, so
917 # A record of hidden variables we have added to the user namespace, so
891 # we can list later only variables defined in actual interactive use.
918 # we can list later only variables defined in actual interactive use.
892 self.user_ns_hidden = set()
919 self.user_ns_hidden = set()
893
920
894 # Now that FakeModule produces a real module, we've run into a nasty
921 # Now that FakeModule produces a real module, we've run into a nasty
895 # problem: after script execution (via %run), the module where the user
922 # problem: after script execution (via %run), the module where the user
896 # code ran is deleted. Now that this object is a true module (needed
923 # code ran is deleted. Now that this object is a true module (needed
897 # so docetst and other tools work correctly), the Python module
924 # so docetst and other tools work correctly), the Python module
898 # teardown mechanism runs over it, and sets to None every variable
925 # teardown mechanism runs over it, and sets to None every variable
899 # present in that module. Top-level references to objects from the
926 # present in that module. Top-level references to objects from the
900 # script survive, because the user_ns is updated with them. However,
927 # script survive, because the user_ns is updated with them. However,
901 # calling functions defined in the script that use other things from
928 # calling functions defined in the script that use other things from
902 # the script will fail, because the function's closure had references
929 # the script will fail, because the function's closure had references
903 # to the original objects, which are now all None. So we must protect
930 # to the original objects, which are now all None. So we must protect
904 # these modules from deletion by keeping a cache.
931 # these modules from deletion by keeping a cache.
905 #
932 #
906 # To avoid keeping stale modules around (we only need the one from the
933 # To avoid keeping stale modules around (we only need the one from the
907 # last run), we use a dict keyed with the full path to the script, so
934 # last run), we use a dict keyed with the full path to the script, so
908 # only the last version of the module is held in the cache. Note,
935 # only the last version of the module is held in the cache. Note,
909 # however, that we must cache the module *namespace contents* (their
936 # however, that we must cache the module *namespace contents* (their
910 # __dict__). Because if we try to cache the actual modules, old ones
937 # __dict__). Because if we try to cache the actual modules, old ones
911 # (uncached) could be destroyed while still holding references (such as
938 # (uncached) could be destroyed while still holding references (such as
912 # those held by GUI objects that tend to be long-lived)>
939 # those held by GUI objects that tend to be long-lived)>
913 #
940 #
914 # The %reset command will flush this cache. See the cache_main_mod()
941 # The %reset command will flush this cache. See the cache_main_mod()
915 # and clear_main_mod_cache() methods for details on use.
942 # and clear_main_mod_cache() methods for details on use.
916
943
917 # This is the cache used for 'main' namespaces
944 # This is the cache used for 'main' namespaces
918 self._main_ns_cache = {}
945 self._main_ns_cache = {}
919 # And this is the single instance of FakeModule whose __dict__ we keep
946 # And this is the single instance of FakeModule whose __dict__ we keep
920 # copying and clearing for reuse on each %run
947 # copying and clearing for reuse on each %run
921 self._user_main_module = FakeModule()
948 self._user_main_module = FakeModule()
922
949
923 # A table holding all the namespaces IPython deals with, so that
950 # A table holding all the namespaces IPython deals with, so that
924 # introspection facilities can search easily.
951 # introspection facilities can search easily.
925 self.ns_table = {'user_global':self.user_module.__dict__,
952 self.ns_table = {'user_global':self.user_module.__dict__,
926 'user_local':user_ns,
953 'user_local':user_ns,
927 'builtin':builtin_mod.__dict__
954 'builtin':builtin_mod.__dict__
928 }
955 }
929
956
930 @property
957 @property
931 def user_global_ns(self):
958 def user_global_ns(self):
932 return self.user_module.__dict__
959 return self.user_module.__dict__
933
960
934 def prepare_user_module(self, user_module=None, user_ns=None):
961 def prepare_user_module(self, user_module=None, user_ns=None):
935 """Prepare the module and namespace in which user code will be run.
962 """Prepare the module and namespace in which user code will be run.
936
963
937 When IPython is started normally, both parameters are None: a new module
964 When IPython is started normally, both parameters are None: a new module
938 is created automatically, and its __dict__ used as the namespace.
965 is created automatically, and its __dict__ used as the namespace.
939
966
940 If only user_module is provided, its __dict__ is used as the namespace.
967 If only user_module is provided, its __dict__ is used as the namespace.
941 If only user_ns is provided, a dummy module is created, and user_ns
968 If only user_ns is provided, a dummy module is created, and user_ns
942 becomes the global namespace. If both are provided (as they may be
969 becomes the global namespace. If both are provided (as they may be
943 when embedding), user_ns is the local namespace, and user_module
970 when embedding), user_ns is the local namespace, and user_module
944 provides the global namespace.
971 provides the global namespace.
945
972
946 Parameters
973 Parameters
947 ----------
974 ----------
948 user_module : module, optional
975 user_module : module, optional
949 The current user module in which IPython is being run. If None,
976 The current user module in which IPython is being run. If None,
950 a clean module will be created.
977 a clean module will be created.
951 user_ns : dict, optional
978 user_ns : dict, optional
952 A namespace in which to run interactive commands.
979 A namespace in which to run interactive commands.
953
980
954 Returns
981 Returns
955 -------
982 -------
956 A tuple of user_module and user_ns, each properly initialised.
983 A tuple of user_module and user_ns, each properly initialised.
957 """
984 """
958 if user_module is None and user_ns is not None:
985 if user_module is None and user_ns is not None:
959 user_ns.setdefault("__name__", "__main__")
986 user_ns.setdefault("__name__", "__main__")
960 class DummyMod(object):
987 class DummyMod(object):
961 "A dummy module used for IPython's interactive namespace."
988 "A dummy module used for IPython's interactive namespace."
962 pass
989 pass
963 user_module = DummyMod()
990 user_module = DummyMod()
964 user_module.__dict__ = user_ns
991 user_module.__dict__ = user_ns
965
992
966 if user_module is None:
993 if user_module is None:
967 user_module = types.ModuleType("__main__",
994 user_module = types.ModuleType("__main__",
968 doc="Automatically created module for IPython interactive environment")
995 doc="Automatically created module for IPython interactive environment")
969
996
970 # We must ensure that __builtin__ (without the final 's') is always
997 # We must ensure that __builtin__ (without the final 's') is always
971 # available and pointing to the __builtin__ *module*. For more details:
998 # available and pointing to the __builtin__ *module*. For more details:
972 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
999 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
973 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1000 user_module.__dict__.setdefault('__builtin__', builtin_mod)
974 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1001 user_module.__dict__.setdefault('__builtins__', builtin_mod)
975
1002
976 if user_ns is None:
1003 if user_ns is None:
977 user_ns = user_module.__dict__
1004 user_ns = user_module.__dict__
978
1005
979 return user_module, user_ns
1006 return user_module, user_ns
980
1007
981 def init_sys_modules(self):
1008 def init_sys_modules(self):
982 # We need to insert into sys.modules something that looks like a
1009 # We need to insert into sys.modules something that looks like a
983 # module but which accesses the IPython namespace, for shelve and
1010 # module but which accesses the IPython namespace, for shelve and
984 # pickle to work interactively. Normally they rely on getting
1011 # pickle to work interactively. Normally they rely on getting
985 # everything out of __main__, but for embedding purposes each IPython
1012 # everything out of __main__, but for embedding purposes each IPython
986 # instance has its own private namespace, so we can't go shoving
1013 # instance has its own private namespace, so we can't go shoving
987 # everything into __main__.
1014 # everything into __main__.
988
1015
989 # note, however, that we should only do this for non-embedded
1016 # note, however, that we should only do this for non-embedded
990 # ipythons, which really mimic the __main__.__dict__ with their own
1017 # ipythons, which really mimic the __main__.__dict__ with their own
991 # namespace. Embedded instances, on the other hand, should not do
1018 # namespace. Embedded instances, on the other hand, should not do
992 # this because they need to manage the user local/global namespaces
1019 # this because they need to manage the user local/global namespaces
993 # only, but they live within a 'normal' __main__ (meaning, they
1020 # only, but they live within a 'normal' __main__ (meaning, they
994 # shouldn't overtake the execution environment of the script they're
1021 # shouldn't overtake the execution environment of the script they're
995 # embedded in).
1022 # embedded in).
996
1023
997 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1024 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
998 main_name = self.user_module.__name__
1025 main_name = self.user_module.__name__
999 sys.modules[main_name] = self.user_module
1026 sys.modules[main_name] = self.user_module
1000
1027
1001 def init_user_ns(self):
1028 def init_user_ns(self):
1002 """Initialize all user-visible namespaces to their minimum defaults.
1029 """Initialize all user-visible namespaces to their minimum defaults.
1003
1030
1004 Certain history lists are also initialized here, as they effectively
1031 Certain history lists are also initialized here, as they effectively
1005 act as user namespaces.
1032 act as user namespaces.
1006
1033
1007 Notes
1034 Notes
1008 -----
1035 -----
1009 All data structures here are only filled in, they are NOT reset by this
1036 All data structures here are only filled in, they are NOT reset by this
1010 method. If they were not empty before, data will simply be added to
1037 method. If they were not empty before, data will simply be added to
1011 therm.
1038 therm.
1012 """
1039 """
1013 # This function works in two parts: first we put a few things in
1040 # This function works in two parts: first we put a few things in
1014 # user_ns, and we sync that contents into user_ns_hidden so that these
1041 # user_ns, and we sync that contents into user_ns_hidden so that these
1015 # initial variables aren't shown by %who. After the sync, we add the
1042 # initial variables aren't shown by %who. After the sync, we add the
1016 # rest of what we *do* want the user to see with %who even on a new
1043 # rest of what we *do* want the user to see with %who even on a new
1017 # session (probably nothing, so theye really only see their own stuff)
1044 # session (probably nothing, so theye really only see their own stuff)
1018
1045
1019 # The user dict must *always* have a __builtin__ reference to the
1046 # The user dict must *always* have a __builtin__ reference to the
1020 # Python standard __builtin__ namespace, which must be imported.
1047 # Python standard __builtin__ namespace, which must be imported.
1021 # This is so that certain operations in prompt evaluation can be
1048 # This is so that certain operations in prompt evaluation can be
1022 # reliably executed with builtins. Note that we can NOT use
1049 # reliably executed with builtins. Note that we can NOT use
1023 # __builtins__ (note the 's'), because that can either be a dict or a
1050 # __builtins__ (note the 's'), because that can either be a dict or a
1024 # module, and can even mutate at runtime, depending on the context
1051 # module, and can even mutate at runtime, depending on the context
1025 # (Python makes no guarantees on it). In contrast, __builtin__ is
1052 # (Python makes no guarantees on it). In contrast, __builtin__ is
1026 # always a module object, though it must be explicitly imported.
1053 # always a module object, though it must be explicitly imported.
1027
1054
1028 # For more details:
1055 # For more details:
1029 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1056 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1030 ns = dict()
1057 ns = dict()
1031
1058
1032 # Put 'help' in the user namespace
1059 # Put 'help' in the user namespace
1033 try:
1060 try:
1034 from site import _Helper
1061 from site import _Helper
1035 ns['help'] = _Helper()
1062 ns['help'] = _Helper()
1036 except ImportError:
1063 except ImportError:
1037 warn('help() not available - check site.py')
1064 warn('help() not available - check site.py')
1038
1065
1039 # make global variables for user access to the histories
1066 # make global variables for user access to the histories
1040 ns['_ih'] = self.history_manager.input_hist_parsed
1067 ns['_ih'] = self.history_manager.input_hist_parsed
1041 ns['_oh'] = self.history_manager.output_hist
1068 ns['_oh'] = self.history_manager.output_hist
1042 ns['_dh'] = self.history_manager.dir_hist
1069 ns['_dh'] = self.history_manager.dir_hist
1043
1070
1044 ns['_sh'] = shadowns
1071 ns['_sh'] = shadowns
1045
1072
1046 # user aliases to input and output histories. These shouldn't show up
1073 # user aliases to input and output histories. These shouldn't show up
1047 # in %who, as they can have very large reprs.
1074 # in %who, as they can have very large reprs.
1048 ns['In'] = self.history_manager.input_hist_parsed
1075 ns['In'] = self.history_manager.input_hist_parsed
1049 ns['Out'] = self.history_manager.output_hist
1076 ns['Out'] = self.history_manager.output_hist
1050
1077
1051 # Store myself as the public api!!!
1078 # Store myself as the public api!!!
1052 ns['get_ipython'] = self.get_ipython
1079 ns['get_ipython'] = self.get_ipython
1053
1080
1054 ns['exit'] = self.exiter
1081 ns['exit'] = self.exiter
1055 ns['quit'] = self.exiter
1082 ns['quit'] = self.exiter
1056
1083
1057 # Sync what we've added so far to user_ns_hidden so these aren't seen
1084 # Sync what we've added so far to user_ns_hidden so these aren't seen
1058 # by %who
1085 # by %who
1059 self.user_ns_hidden.update(ns)
1086 self.user_ns_hidden.update(ns)
1060
1087
1061 # Anything put into ns now would show up in %who. Think twice before
1088 # Anything put into ns now would show up in %who. Think twice before
1062 # putting anything here, as we really want %who to show the user their
1089 # putting anything here, as we really want %who to show the user their
1063 # stuff, not our variables.
1090 # stuff, not our variables.
1064
1091
1065 # Finally, update the real user's namespace
1092 # Finally, update the real user's namespace
1066 self.user_ns.update(ns)
1093 self.user_ns.update(ns)
1067
1094
1068 @property
1095 @property
1069 def all_ns_refs(self):
1096 def all_ns_refs(self):
1070 """Get a list of references to all the namespace dictionaries in which
1097 """Get a list of references to all the namespace dictionaries in which
1071 IPython might store a user-created object.
1098 IPython might store a user-created object.
1072
1099
1073 Note that this does not include the displayhook, which also caches
1100 Note that this does not include the displayhook, which also caches
1074 objects from the output."""
1101 objects from the output."""
1075 return [self.user_ns, self.user_global_ns,
1102 return [self.user_ns, self.user_global_ns,
1076 self._user_main_module.__dict__] + self._main_ns_cache.values()
1103 self._user_main_module.__dict__] + self._main_ns_cache.values()
1077
1104
1078 def reset(self, new_session=True):
1105 def reset(self, new_session=True):
1079 """Clear all internal namespaces, and attempt to release references to
1106 """Clear all internal namespaces, and attempt to release references to
1080 user objects.
1107 user objects.
1081
1108
1082 If new_session is True, a new history session will be opened.
1109 If new_session is True, a new history session will be opened.
1083 """
1110 """
1084 # Clear histories
1111 # Clear histories
1085 self.history_manager.reset(new_session)
1112 self.history_manager.reset(new_session)
1086 # Reset counter used to index all histories
1113 # Reset counter used to index all histories
1087 if new_session:
1114 if new_session:
1088 self.execution_count = 1
1115 self.execution_count = 1
1089
1116
1090 # Flush cached output items
1117 # Flush cached output items
1091 if self.displayhook.do_full_cache:
1118 if self.displayhook.do_full_cache:
1092 self.displayhook.flush()
1119 self.displayhook.flush()
1093
1120
1094 # The main execution namespaces must be cleared very carefully,
1121 # The main execution namespaces must be cleared very carefully,
1095 # skipping the deletion of the builtin-related keys, because doing so
1122 # skipping the deletion of the builtin-related keys, because doing so
1096 # would cause errors in many object's __del__ methods.
1123 # would cause errors in many object's __del__ methods.
1097 if self.user_ns is not self.user_global_ns:
1124 if self.user_ns is not self.user_global_ns:
1098 self.user_ns.clear()
1125 self.user_ns.clear()
1099 ns = self.user_global_ns
1126 ns = self.user_global_ns
1100 drop_keys = set(ns.keys())
1127 drop_keys = set(ns.keys())
1101 drop_keys.discard('__builtin__')
1128 drop_keys.discard('__builtin__')
1102 drop_keys.discard('__builtins__')
1129 drop_keys.discard('__builtins__')
1103 drop_keys.discard('__name__')
1130 drop_keys.discard('__name__')
1104 for k in drop_keys:
1131 for k in drop_keys:
1105 del ns[k]
1132 del ns[k]
1106
1133
1107 self.user_ns_hidden.clear()
1134 self.user_ns_hidden.clear()
1108
1135
1109 # Restore the user namespaces to minimal usability
1136 # Restore the user namespaces to minimal usability
1110 self.init_user_ns()
1137 self.init_user_ns()
1111
1138
1112 # Restore the default and user aliases
1139 # Restore the default and user aliases
1113 self.alias_manager.clear_aliases()
1140 self.alias_manager.clear_aliases()
1114 self.alias_manager.init_aliases()
1141 self.alias_manager.init_aliases()
1115
1142
1116 # Flush the private list of module references kept for script
1143 # Flush the private list of module references kept for script
1117 # execution protection
1144 # execution protection
1118 self.clear_main_mod_cache()
1145 self.clear_main_mod_cache()
1119
1146
1120 # Clear out the namespace from the last %run
1147 # Clear out the namespace from the last %run
1121 self.new_main_mod()
1148 self.new_main_mod()
1122
1149
1123 def del_var(self, varname, by_name=False):
1150 def del_var(self, varname, by_name=False):
1124 """Delete a variable from the various namespaces, so that, as
1151 """Delete a variable from the various namespaces, so that, as
1125 far as possible, we're not keeping any hidden references to it.
1152 far as possible, we're not keeping any hidden references to it.
1126
1153
1127 Parameters
1154 Parameters
1128 ----------
1155 ----------
1129 varname : str
1156 varname : str
1130 The name of the variable to delete.
1157 The name of the variable to delete.
1131 by_name : bool
1158 by_name : bool
1132 If True, delete variables with the given name in each
1159 If True, delete variables with the given name in each
1133 namespace. If False (default), find the variable in the user
1160 namespace. If False (default), find the variable in the user
1134 namespace, and delete references to it.
1161 namespace, and delete references to it.
1135 """
1162 """
1136 if varname in ('__builtin__', '__builtins__'):
1163 if varname in ('__builtin__', '__builtins__'):
1137 raise ValueError("Refusing to delete %s" % varname)
1164 raise ValueError("Refusing to delete %s" % varname)
1138
1165
1139 ns_refs = self.all_ns_refs
1166 ns_refs = self.all_ns_refs
1140
1167
1141 if by_name: # Delete by name
1168 if by_name: # Delete by name
1142 for ns in ns_refs:
1169 for ns in ns_refs:
1143 try:
1170 try:
1144 del ns[varname]
1171 del ns[varname]
1145 except KeyError:
1172 except KeyError:
1146 pass
1173 pass
1147 else: # Delete by object
1174 else: # Delete by object
1148 try:
1175 try:
1149 obj = self.user_ns[varname]
1176 obj = self.user_ns[varname]
1150 except KeyError:
1177 except KeyError:
1151 raise NameError("name '%s' is not defined" % varname)
1178 raise NameError("name '%s' is not defined" % varname)
1152 # Also check in output history
1179 # Also check in output history
1153 ns_refs.append(self.history_manager.output_hist)
1180 ns_refs.append(self.history_manager.output_hist)
1154 for ns in ns_refs:
1181 for ns in ns_refs:
1155 to_delete = [n for n, o in ns.iteritems() if o is obj]
1182 to_delete = [n for n, o in ns.iteritems() if o is obj]
1156 for name in to_delete:
1183 for name in to_delete:
1157 del ns[name]
1184 del ns[name]
1158
1185
1159 # displayhook keeps extra references, but not in a dictionary
1186 # displayhook keeps extra references, but not in a dictionary
1160 for name in ('_', '__', '___'):
1187 for name in ('_', '__', '___'):
1161 if getattr(self.displayhook, name) is obj:
1188 if getattr(self.displayhook, name) is obj:
1162 setattr(self.displayhook, name, None)
1189 setattr(self.displayhook, name, None)
1163
1190
1164 def reset_selective(self, regex=None):
1191 def reset_selective(self, regex=None):
1165 """Clear selective variables from internal namespaces based on a
1192 """Clear selective variables from internal namespaces based on a
1166 specified regular expression.
1193 specified regular expression.
1167
1194
1168 Parameters
1195 Parameters
1169 ----------
1196 ----------
1170 regex : string or compiled pattern, optional
1197 regex : string or compiled pattern, optional
1171 A regular expression pattern that will be used in searching
1198 A regular expression pattern that will be used in searching
1172 variable names in the users namespaces.
1199 variable names in the users namespaces.
1173 """
1200 """
1174 if regex is not None:
1201 if regex is not None:
1175 try:
1202 try:
1176 m = re.compile(regex)
1203 m = re.compile(regex)
1177 except TypeError:
1204 except TypeError:
1178 raise TypeError('regex must be a string or compiled pattern')
1205 raise TypeError('regex must be a string or compiled pattern')
1179 # Search for keys in each namespace that match the given regex
1206 # Search for keys in each namespace that match the given regex
1180 # If a match is found, delete the key/value pair.
1207 # If a match is found, delete the key/value pair.
1181 for ns in self.all_ns_refs:
1208 for ns in self.all_ns_refs:
1182 for var in ns:
1209 for var in ns:
1183 if m.search(var):
1210 if m.search(var):
1184 del ns[var]
1211 del ns[var]
1185
1212
1186 def push(self, variables, interactive=True):
1213 def push(self, variables, interactive=True):
1187 """Inject a group of variables into the IPython user namespace.
1214 """Inject a group of variables into the IPython user namespace.
1188
1215
1189 Parameters
1216 Parameters
1190 ----------
1217 ----------
1191 variables : dict, str or list/tuple of str
1218 variables : dict, str or list/tuple of str
1192 The variables to inject into the user's namespace. If a dict, a
1219 The variables to inject into the user's namespace. If a dict, a
1193 simple update is done. If a str, the string is assumed to have
1220 simple update is done. If a str, the string is assumed to have
1194 variable names separated by spaces. A list/tuple of str can also
1221 variable names separated by spaces. A list/tuple of str can also
1195 be used to give the variable names. If just the variable names are
1222 be used to give the variable names. If just the variable names are
1196 give (list/tuple/str) then the variable values looked up in the
1223 give (list/tuple/str) then the variable values looked up in the
1197 callers frame.
1224 callers frame.
1198 interactive : bool
1225 interactive : bool
1199 If True (default), the variables will be listed with the ``who``
1226 If True (default), the variables will be listed with the ``who``
1200 magic.
1227 magic.
1201 """
1228 """
1202 vdict = None
1229 vdict = None
1203
1230
1204 # We need a dict of name/value pairs to do namespace updates.
1231 # We need a dict of name/value pairs to do namespace updates.
1205 if isinstance(variables, dict):
1232 if isinstance(variables, dict):
1206 vdict = variables
1233 vdict = variables
1207 elif isinstance(variables, (basestring, list, tuple)):
1234 elif isinstance(variables, (basestring, list, tuple)):
1208 if isinstance(variables, basestring):
1235 if isinstance(variables, basestring):
1209 vlist = variables.split()
1236 vlist = variables.split()
1210 else:
1237 else:
1211 vlist = variables
1238 vlist = variables
1212 vdict = {}
1239 vdict = {}
1213 cf = sys._getframe(1)
1240 cf = sys._getframe(1)
1214 for name in vlist:
1241 for name in vlist:
1215 try:
1242 try:
1216 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1243 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1217 except:
1244 except:
1218 print ('Could not get variable %s from %s' %
1245 print ('Could not get variable %s from %s' %
1219 (name,cf.f_code.co_name))
1246 (name,cf.f_code.co_name))
1220 else:
1247 else:
1221 raise ValueError('variables must be a dict/str/list/tuple')
1248 raise ValueError('variables must be a dict/str/list/tuple')
1222
1249
1223 # Propagate variables to user namespace
1250 # Propagate variables to user namespace
1224 self.user_ns.update(vdict)
1251 self.user_ns.update(vdict)
1225
1252
1226 # And configure interactive visibility
1253 # And configure interactive visibility
1227 user_ns_hidden = self.user_ns_hidden
1254 user_ns_hidden = self.user_ns_hidden
1228 if interactive:
1255 if interactive:
1229 user_ns_hidden.difference_update(vdict)
1256 user_ns_hidden.difference_update(vdict)
1230 else:
1257 else:
1231 user_ns_hidden.update(vdict)
1258 user_ns_hidden.update(vdict)
1232
1259
1233 def drop_by_id(self, variables):
1260 def drop_by_id(self, variables):
1234 """Remove a dict of variables from the user namespace, if they are the
1261 """Remove a dict of variables from the user namespace, if they are the
1235 same as the values in the dictionary.
1262 same as the values in the dictionary.
1236
1263
1237 This is intended for use by extensions: variables that they've added can
1264 This is intended for use by extensions: variables that they've added can
1238 be taken back out if they are unloaded, without removing any that the
1265 be taken back out if they are unloaded, without removing any that the
1239 user has overwritten.
1266 user has overwritten.
1240
1267
1241 Parameters
1268 Parameters
1242 ----------
1269 ----------
1243 variables : dict
1270 variables : dict
1244 A dictionary mapping object names (as strings) to the objects.
1271 A dictionary mapping object names (as strings) to the objects.
1245 """
1272 """
1246 for name, obj in variables.iteritems():
1273 for name, obj in variables.iteritems():
1247 if name in self.user_ns and self.user_ns[name] is obj:
1274 if name in self.user_ns and self.user_ns[name] is obj:
1248 del self.user_ns[name]
1275 del self.user_ns[name]
1249 self.user_ns_hidden.discard(name)
1276 self.user_ns_hidden.discard(name)
1250
1277
1251 #-------------------------------------------------------------------------
1278 #-------------------------------------------------------------------------
1252 # Things related to object introspection
1279 # Things related to object introspection
1253 #-------------------------------------------------------------------------
1280 #-------------------------------------------------------------------------
1254
1281
1255 def _ofind(self, oname, namespaces=None):
1282 def _ofind(self, oname, namespaces=None):
1256 """Find an object in the available namespaces.
1283 """Find an object in the available namespaces.
1257
1284
1258 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1285 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1259
1286
1260 Has special code to detect magic functions.
1287 Has special code to detect magic functions.
1261 """
1288 """
1262 oname = oname.strip()
1289 oname = oname.strip()
1263 #print '1- oname: <%r>' % oname # dbg
1290 #print '1- oname: <%r>' % oname # dbg
1264 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1291 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1265 return dict(found=False)
1292 return dict(found=False)
1266
1293
1267 alias_ns = None
1294 alias_ns = None
1268 if namespaces is None:
1295 if namespaces is None:
1269 # Namespaces to search in:
1296 # Namespaces to search in:
1270 # Put them in a list. The order is important so that we
1297 # Put them in a list. The order is important so that we
1271 # find things in the same order that Python finds them.
1298 # find things in the same order that Python finds them.
1272 namespaces = [ ('Interactive', self.user_ns),
1299 namespaces = [ ('Interactive', self.user_ns),
1273 ('Interactive (global)', self.user_global_ns),
1300 ('Interactive (global)', self.user_global_ns),
1274 ('Python builtin', builtin_mod.__dict__),
1301 ('Python builtin', builtin_mod.__dict__),
1275 ('Alias', self.alias_manager.alias_table),
1302 ('Alias', self.alias_manager.alias_table),
1276 ]
1303 ]
1277 alias_ns = self.alias_manager.alias_table
1304 alias_ns = self.alias_manager.alias_table
1278
1305
1279 # initialize results to 'null'
1306 # initialize results to 'null'
1280 found = False; obj = None; ospace = None; ds = None;
1307 found = False; obj = None; ospace = None; ds = None;
1281 ismagic = False; isalias = False; parent = None
1308 ismagic = False; isalias = False; parent = None
1282
1309
1283 # We need to special-case 'print', which as of python2.6 registers as a
1310 # We need to special-case 'print', which as of python2.6 registers as a
1284 # function but should only be treated as one if print_function was
1311 # function but should only be treated as one if print_function was
1285 # loaded with a future import. In this case, just bail.
1312 # loaded with a future import. In this case, just bail.
1286 if (oname == 'print' and not py3compat.PY3 and not \
1313 if (oname == 'print' and not py3compat.PY3 and not \
1287 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1314 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1288 return {'found':found, 'obj':obj, 'namespace':ospace,
1315 return {'found':found, 'obj':obj, 'namespace':ospace,
1289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1316 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1290
1317
1291 # Look for the given name by splitting it in parts. If the head is
1318 # Look for the given name by splitting it in parts. If the head is
1292 # found, then we look for all the remaining parts as members, and only
1319 # found, then we look for all the remaining parts as members, and only
1293 # declare success if we can find them all.
1320 # declare success if we can find them all.
1294 oname_parts = oname.split('.')
1321 oname_parts = oname.split('.')
1295 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1322 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1296 for nsname,ns in namespaces:
1323 for nsname,ns in namespaces:
1297 try:
1324 try:
1298 obj = ns[oname_head]
1325 obj = ns[oname_head]
1299 except KeyError:
1326 except KeyError:
1300 continue
1327 continue
1301 else:
1328 else:
1302 #print 'oname_rest:', oname_rest # dbg
1329 #print 'oname_rest:', oname_rest # dbg
1303 for part in oname_rest:
1330 for part in oname_rest:
1304 try:
1331 try:
1305 parent = obj
1332 parent = obj
1306 obj = getattr(obj,part)
1333 obj = getattr(obj,part)
1307 except:
1334 except:
1308 # Blanket except b/c some badly implemented objects
1335 # Blanket except b/c some badly implemented objects
1309 # allow __getattr__ to raise exceptions other than
1336 # allow __getattr__ to raise exceptions other than
1310 # AttributeError, which then crashes IPython.
1337 # AttributeError, which then crashes IPython.
1311 break
1338 break
1312 else:
1339 else:
1313 # If we finish the for loop (no break), we got all members
1340 # If we finish the for loop (no break), we got all members
1314 found = True
1341 found = True
1315 ospace = nsname
1342 ospace = nsname
1316 if ns == alias_ns:
1343 if ns == alias_ns:
1317 isalias = True
1344 isalias = True
1318 break # namespace loop
1345 break # namespace loop
1319
1346
1320 # Try to see if it's magic
1347 # Try to see if it's magic
1321 if not found:
1348 if not found:
1322 if oname.startswith(ESC_MAGIC):
1349 if oname.startswith(ESC_MAGIC):
1323 oname = oname[1:]
1350 oname = oname[1:]
1324 obj = getattr(self,'magic_'+oname,None)
1351 obj = getattr(self,'magic_'+oname,None)
1325 if obj is not None:
1352 if obj is not None:
1326 found = True
1353 found = True
1327 ospace = 'IPython internal'
1354 ospace = 'IPython internal'
1328 ismagic = True
1355 ismagic = True
1329
1356
1330 # Last try: special-case some literals like '', [], {}, etc:
1357 # Last try: special-case some literals like '', [], {}, etc:
1331 if not found and oname_head in ["''",'""','[]','{}','()']:
1358 if not found and oname_head in ["''",'""','[]','{}','()']:
1332 obj = eval(oname_head)
1359 obj = eval(oname_head)
1333 found = True
1360 found = True
1334 ospace = 'Interactive'
1361 ospace = 'Interactive'
1335
1362
1336 return {'found':found, 'obj':obj, 'namespace':ospace,
1363 return {'found':found, 'obj':obj, 'namespace':ospace,
1337 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1364 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1338
1365
1339 def _ofind_property(self, oname, info):
1366 def _ofind_property(self, oname, info):
1340 """Second part of object finding, to look for property details."""
1367 """Second part of object finding, to look for property details."""
1341 if info.found:
1368 if info.found:
1342 # Get the docstring of the class property if it exists.
1369 # Get the docstring of the class property if it exists.
1343 path = oname.split('.')
1370 path = oname.split('.')
1344 root = '.'.join(path[:-1])
1371 root = '.'.join(path[:-1])
1345 if info.parent is not None:
1372 if info.parent is not None:
1346 try:
1373 try:
1347 target = getattr(info.parent, '__class__')
1374 target = getattr(info.parent, '__class__')
1348 # The object belongs to a class instance.
1375 # The object belongs to a class instance.
1349 try:
1376 try:
1350 target = getattr(target, path[-1])
1377 target = getattr(target, path[-1])
1351 # The class defines the object.
1378 # The class defines the object.
1352 if isinstance(target, property):
1379 if isinstance(target, property):
1353 oname = root + '.__class__.' + path[-1]
1380 oname = root + '.__class__.' + path[-1]
1354 info = Struct(self._ofind(oname))
1381 info = Struct(self._ofind(oname))
1355 except AttributeError: pass
1382 except AttributeError: pass
1356 except AttributeError: pass
1383 except AttributeError: pass
1357
1384
1358 # We return either the new info or the unmodified input if the object
1385 # We return either the new info or the unmodified input if the object
1359 # hadn't been found
1386 # hadn't been found
1360 return info
1387 return info
1361
1388
1362 def _object_find(self, oname, namespaces=None):
1389 def _object_find(self, oname, namespaces=None):
1363 """Find an object and return a struct with info about it."""
1390 """Find an object and return a struct with info about it."""
1364 inf = Struct(self._ofind(oname, namespaces))
1391 inf = Struct(self._ofind(oname, namespaces))
1365 return Struct(self._ofind_property(oname, inf))
1392 return Struct(self._ofind_property(oname, inf))
1366
1393
1367 def _inspect(self, meth, oname, namespaces=None, **kw):
1394 def _inspect(self, meth, oname, namespaces=None, **kw):
1368 """Generic interface to the inspector system.
1395 """Generic interface to the inspector system.
1369
1396
1370 This function is meant to be called by pdef, pdoc & friends."""
1397 This function is meant to be called by pdef, pdoc & friends."""
1371 info = self._object_find(oname)
1398 info = self._object_find(oname)
1372 if info.found:
1399 if info.found:
1373 pmethod = getattr(self.inspector, meth)
1400 pmethod = getattr(self.inspector, meth)
1374 formatter = format_screen if info.ismagic else None
1401 formatter = format_screen if info.ismagic else None
1375 if meth == 'pdoc':
1402 if meth == 'pdoc':
1376 pmethod(info.obj, oname, formatter)
1403 pmethod(info.obj, oname, formatter)
1377 elif meth == 'pinfo':
1404 elif meth == 'pinfo':
1378 pmethod(info.obj, oname, formatter, info, **kw)
1405 pmethod(info.obj, oname, formatter, info, **kw)
1379 else:
1406 else:
1380 pmethod(info.obj, oname)
1407 pmethod(info.obj, oname)
1381 else:
1408 else:
1382 print 'Object `%s` not found.' % oname
1409 print 'Object `%s` not found.' % oname
1383 return 'not found' # so callers can take other action
1410 return 'not found' # so callers can take other action
1384
1411
1385 def object_inspect(self, oname):
1412 def object_inspect(self, oname):
1386 with self.builtin_trap:
1413 with self.builtin_trap:
1387 info = self._object_find(oname)
1414 info = self._object_find(oname)
1388 if info.found:
1415 if info.found:
1389 return self.inspector.info(info.obj, oname, info=info)
1416 return self.inspector.info(info.obj, oname, info=info)
1390 else:
1417 else:
1391 return oinspect.object_info(name=oname, found=False)
1418 return oinspect.object_info(name=oname, found=False)
1392
1419
1393 #-------------------------------------------------------------------------
1420 #-------------------------------------------------------------------------
1394 # Things related to history management
1421 # Things related to history management
1395 #-------------------------------------------------------------------------
1422 #-------------------------------------------------------------------------
1396
1423
1397 def init_history(self):
1424 def init_history(self):
1398 """Sets up the command history, and starts regular autosaves."""
1425 """Sets up the command history, and starts regular autosaves."""
1399 self.history_manager = HistoryManager(shell=self, config=self.config)
1426 self.history_manager = HistoryManager(shell=self, config=self.config)
1400 self.configurables.append(self.history_manager)
1427 self.configurables.append(self.history_manager)
1401
1428
1402 #-------------------------------------------------------------------------
1429 #-------------------------------------------------------------------------
1403 # Things related to exception handling and tracebacks (not debugging)
1430 # Things related to exception handling and tracebacks (not debugging)
1404 #-------------------------------------------------------------------------
1431 #-------------------------------------------------------------------------
1405
1432
1406 def init_traceback_handlers(self, custom_exceptions):
1433 def init_traceback_handlers(self, custom_exceptions):
1407 # Syntax error handler.
1434 # Syntax error handler.
1408 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1435 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1409
1436
1410 # The interactive one is initialized with an offset, meaning we always
1437 # The interactive one is initialized with an offset, meaning we always
1411 # want to remove the topmost item in the traceback, which is our own
1438 # want to remove the topmost item in the traceback, which is our own
1412 # internal code. Valid modes: ['Plain','Context','Verbose']
1439 # internal code. Valid modes: ['Plain','Context','Verbose']
1413 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1440 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1414 color_scheme='NoColor',
1441 color_scheme='NoColor',
1415 tb_offset = 1,
1442 tb_offset = 1,
1416 check_cache=self.compile.check_cache)
1443 check_cache=self.compile.check_cache)
1417
1444
1418 # The instance will store a pointer to the system-wide exception hook,
1445 # The instance will store a pointer to the system-wide exception hook,
1419 # so that runtime code (such as magics) can access it. This is because
1446 # so that runtime code (such as magics) can access it. This is because
1420 # during the read-eval loop, it may get temporarily overwritten.
1447 # during the read-eval loop, it may get temporarily overwritten.
1421 self.sys_excepthook = sys.excepthook
1448 self.sys_excepthook = sys.excepthook
1422
1449
1423 # and add any custom exception handlers the user may have specified
1450 # and add any custom exception handlers the user may have specified
1424 self.set_custom_exc(*custom_exceptions)
1451 self.set_custom_exc(*custom_exceptions)
1425
1452
1426 # Set the exception mode
1453 # Set the exception mode
1427 self.InteractiveTB.set_mode(mode=self.xmode)
1454 self.InteractiveTB.set_mode(mode=self.xmode)
1428
1455
1429 def set_custom_exc(self, exc_tuple, handler):
1456 def set_custom_exc(self, exc_tuple, handler):
1430 """set_custom_exc(exc_tuple,handler)
1457 """set_custom_exc(exc_tuple,handler)
1431
1458
1432 Set a custom exception handler, which will be called if any of the
1459 Set a custom exception handler, which will be called if any of the
1433 exceptions in exc_tuple occur in the mainloop (specifically, in the
1460 exceptions in exc_tuple occur in the mainloop (specifically, in the
1434 run_code() method).
1461 run_code() method).
1435
1462
1436 Parameters
1463 Parameters
1437 ----------
1464 ----------
1438
1465
1439 exc_tuple : tuple of exception classes
1466 exc_tuple : tuple of exception classes
1440 A *tuple* of exception classes, for which to call the defined
1467 A *tuple* of exception classes, for which to call the defined
1441 handler. It is very important that you use a tuple, and NOT A
1468 handler. It is very important that you use a tuple, and NOT A
1442 LIST here, because of the way Python's except statement works. If
1469 LIST here, because of the way Python's except statement works. If
1443 you only want to trap a single exception, use a singleton tuple::
1470 you only want to trap a single exception, use a singleton tuple::
1444
1471
1445 exc_tuple == (MyCustomException,)
1472 exc_tuple == (MyCustomException,)
1446
1473
1447 handler : callable
1474 handler : callable
1448 handler must have the following signature::
1475 handler must have the following signature::
1449
1476
1450 def my_handler(self, etype, value, tb, tb_offset=None):
1477 def my_handler(self, etype, value, tb, tb_offset=None):
1451 ...
1478 ...
1452 return structured_traceback
1479 return structured_traceback
1453
1480
1454 Your handler must return a structured traceback (a list of strings),
1481 Your handler must return a structured traceback (a list of strings),
1455 or None.
1482 or None.
1456
1483
1457 This will be made into an instance method (via types.MethodType)
1484 This will be made into an instance method (via types.MethodType)
1458 of IPython itself, and it will be called if any of the exceptions
1485 of IPython itself, and it will be called if any of the exceptions
1459 listed in the exc_tuple are caught. If the handler is None, an
1486 listed in the exc_tuple are caught. If the handler is None, an
1460 internal basic one is used, which just prints basic info.
1487 internal basic one is used, which just prints basic info.
1461
1488
1462 To protect IPython from crashes, if your handler ever raises an
1489 To protect IPython from crashes, if your handler ever raises an
1463 exception or returns an invalid result, it will be immediately
1490 exception or returns an invalid result, it will be immediately
1464 disabled.
1491 disabled.
1465
1492
1466 WARNING: by putting in your own exception handler into IPython's main
1493 WARNING: by putting in your own exception handler into IPython's main
1467 execution loop, you run a very good chance of nasty crashes. This
1494 execution loop, you run a very good chance of nasty crashes. This
1468 facility should only be used if you really know what you are doing."""
1495 facility should only be used if you really know what you are doing."""
1469
1496
1470 assert type(exc_tuple)==type(()) , \
1497 assert type(exc_tuple)==type(()) , \
1471 "The custom exceptions must be given AS A TUPLE."
1498 "The custom exceptions must be given AS A TUPLE."
1472
1499
1473 def dummy_handler(self,etype,value,tb,tb_offset=None):
1500 def dummy_handler(self,etype,value,tb,tb_offset=None):
1474 print '*** Simple custom exception handler ***'
1501 print '*** Simple custom exception handler ***'
1475 print 'Exception type :',etype
1502 print 'Exception type :',etype
1476 print 'Exception value:',value
1503 print 'Exception value:',value
1477 print 'Traceback :',tb
1504 print 'Traceback :',tb
1478 #print 'Source code :','\n'.join(self.buffer)
1505 #print 'Source code :','\n'.join(self.buffer)
1479
1506
1480 def validate_stb(stb):
1507 def validate_stb(stb):
1481 """validate structured traceback return type
1508 """validate structured traceback return type
1482
1509
1483 return type of CustomTB *should* be a list of strings, but allow
1510 return type of CustomTB *should* be a list of strings, but allow
1484 single strings or None, which are harmless.
1511 single strings or None, which are harmless.
1485
1512
1486 This function will *always* return a list of strings,
1513 This function will *always* return a list of strings,
1487 and will raise a TypeError if stb is inappropriate.
1514 and will raise a TypeError if stb is inappropriate.
1488 """
1515 """
1489 msg = "CustomTB must return list of strings, not %r" % stb
1516 msg = "CustomTB must return list of strings, not %r" % stb
1490 if stb is None:
1517 if stb is None:
1491 return []
1518 return []
1492 elif isinstance(stb, basestring):
1519 elif isinstance(stb, basestring):
1493 return [stb]
1520 return [stb]
1494 elif not isinstance(stb, list):
1521 elif not isinstance(stb, list):
1495 raise TypeError(msg)
1522 raise TypeError(msg)
1496 # it's a list
1523 # it's a list
1497 for line in stb:
1524 for line in stb:
1498 # check every element
1525 # check every element
1499 if not isinstance(line, basestring):
1526 if not isinstance(line, basestring):
1500 raise TypeError(msg)
1527 raise TypeError(msg)
1501 return stb
1528 return stb
1502
1529
1503 if handler is None:
1530 if handler is None:
1504 wrapped = dummy_handler
1531 wrapped = dummy_handler
1505 else:
1532 else:
1506 def wrapped(self,etype,value,tb,tb_offset=None):
1533 def wrapped(self,etype,value,tb,tb_offset=None):
1507 """wrap CustomTB handler, to protect IPython from user code
1534 """wrap CustomTB handler, to protect IPython from user code
1508
1535
1509 This makes it harder (but not impossible) for custom exception
1536 This makes it harder (but not impossible) for custom exception
1510 handlers to crash IPython.
1537 handlers to crash IPython.
1511 """
1538 """
1512 try:
1539 try:
1513 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1540 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1514 return validate_stb(stb)
1541 return validate_stb(stb)
1515 except:
1542 except:
1516 # clear custom handler immediately
1543 # clear custom handler immediately
1517 self.set_custom_exc((), None)
1544 self.set_custom_exc((), None)
1518 print >> io.stderr, "Custom TB Handler failed, unregistering"
1545 print >> io.stderr, "Custom TB Handler failed, unregistering"
1519 # show the exception in handler first
1546 # show the exception in handler first
1520 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1547 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1521 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1548 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1522 print >> io.stdout, "The original exception:"
1549 print >> io.stdout, "The original exception:"
1523 stb = self.InteractiveTB.structured_traceback(
1550 stb = self.InteractiveTB.structured_traceback(
1524 (etype,value,tb), tb_offset=tb_offset
1551 (etype,value,tb), tb_offset=tb_offset
1525 )
1552 )
1526 return stb
1553 return stb
1527
1554
1528 self.CustomTB = types.MethodType(wrapped,self)
1555 self.CustomTB = types.MethodType(wrapped,self)
1529 self.custom_exceptions = exc_tuple
1556 self.custom_exceptions = exc_tuple
1530
1557
1531 def excepthook(self, etype, value, tb):
1558 def excepthook(self, etype, value, tb):
1532 """One more defense for GUI apps that call sys.excepthook.
1559 """One more defense for GUI apps that call sys.excepthook.
1533
1560
1534 GUI frameworks like wxPython trap exceptions and call
1561 GUI frameworks like wxPython trap exceptions and call
1535 sys.excepthook themselves. I guess this is a feature that
1562 sys.excepthook themselves. I guess this is a feature that
1536 enables them to keep running after exceptions that would
1563 enables them to keep running after exceptions that would
1537 otherwise kill their mainloop. This is a bother for IPython
1564 otherwise kill their mainloop. This is a bother for IPython
1538 which excepts to catch all of the program exceptions with a try:
1565 which excepts to catch all of the program exceptions with a try:
1539 except: statement.
1566 except: statement.
1540
1567
1541 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1568 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1542 any app directly invokes sys.excepthook, it will look to the user like
1569 any app directly invokes sys.excepthook, it will look to the user like
1543 IPython crashed. In order to work around this, we can disable the
1570 IPython crashed. In order to work around this, we can disable the
1544 CrashHandler and replace it with this excepthook instead, which prints a
1571 CrashHandler and replace it with this excepthook instead, which prints a
1545 regular traceback using our InteractiveTB. In this fashion, apps which
1572 regular traceback using our InteractiveTB. In this fashion, apps which
1546 call sys.excepthook will generate a regular-looking exception from
1573 call sys.excepthook will generate a regular-looking exception from
1547 IPython, and the CrashHandler will only be triggered by real IPython
1574 IPython, and the CrashHandler will only be triggered by real IPython
1548 crashes.
1575 crashes.
1549
1576
1550 This hook should be used sparingly, only in places which are not likely
1577 This hook should be used sparingly, only in places which are not likely
1551 to be true IPython errors.
1578 to be true IPython errors.
1552 """
1579 """
1553 self.showtraceback((etype,value,tb),tb_offset=0)
1580 self.showtraceback((etype,value,tb),tb_offset=0)
1554
1581
1555 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1582 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1556 exception_only=False):
1583 exception_only=False):
1557 """Display the exception that just occurred.
1584 """Display the exception that just occurred.
1558
1585
1559 If nothing is known about the exception, this is the method which
1586 If nothing is known about the exception, this is the method which
1560 should be used throughout the code for presenting user tracebacks,
1587 should be used throughout the code for presenting user tracebacks,
1561 rather than directly invoking the InteractiveTB object.
1588 rather than directly invoking the InteractiveTB object.
1562
1589
1563 A specific showsyntaxerror() also exists, but this method can take
1590 A specific showsyntaxerror() also exists, but this method can take
1564 care of calling it if needed, so unless you are explicitly catching a
1591 care of calling it if needed, so unless you are explicitly catching a
1565 SyntaxError exception, don't try to analyze the stack manually and
1592 SyntaxError exception, don't try to analyze the stack manually and
1566 simply call this method."""
1593 simply call this method."""
1567
1594
1568 try:
1595 try:
1569 if exc_tuple is None:
1596 if exc_tuple is None:
1570 etype, value, tb = sys.exc_info()
1597 etype, value, tb = sys.exc_info()
1571 else:
1598 else:
1572 etype, value, tb = exc_tuple
1599 etype, value, tb = exc_tuple
1573
1600
1574 if etype is None:
1601 if etype is None:
1575 if hasattr(sys, 'last_type'):
1602 if hasattr(sys, 'last_type'):
1576 etype, value, tb = sys.last_type, sys.last_value, \
1603 etype, value, tb = sys.last_type, sys.last_value, \
1577 sys.last_traceback
1604 sys.last_traceback
1578 else:
1605 else:
1579 self.write_err('No traceback available to show.\n')
1606 self.write_err('No traceback available to show.\n')
1580 return
1607 return
1581
1608
1582 if etype is SyntaxError:
1609 if etype is SyntaxError:
1583 # Though this won't be called by syntax errors in the input
1610 # Though this won't be called by syntax errors in the input
1584 # line, there may be SyntaxError cases with imported code.
1611 # line, there may be SyntaxError cases with imported code.
1585 self.showsyntaxerror(filename)
1612 self.showsyntaxerror(filename)
1586 elif etype is UsageError:
1613 elif etype is UsageError:
1587 self.write_err("UsageError: %s" % value)
1614 self.write_err("UsageError: %s" % value)
1588 else:
1615 else:
1589 # WARNING: these variables are somewhat deprecated and not
1616 # WARNING: these variables are somewhat deprecated and not
1590 # necessarily safe to use in a threaded environment, but tools
1617 # necessarily safe to use in a threaded environment, but tools
1591 # like pdb depend on their existence, so let's set them. If we
1618 # like pdb depend on their existence, so let's set them. If we
1592 # find problems in the field, we'll need to revisit their use.
1619 # find problems in the field, we'll need to revisit their use.
1593 sys.last_type = etype
1620 sys.last_type = etype
1594 sys.last_value = value
1621 sys.last_value = value
1595 sys.last_traceback = tb
1622 sys.last_traceback = tb
1596 if etype in self.custom_exceptions:
1623 if etype in self.custom_exceptions:
1597 stb = self.CustomTB(etype, value, tb, tb_offset)
1624 stb = self.CustomTB(etype, value, tb, tb_offset)
1598 else:
1625 else:
1599 if exception_only:
1626 if exception_only:
1600 stb = ['An exception has occurred, use %tb to see '
1627 stb = ['An exception has occurred, use %tb to see '
1601 'the full traceback.\n']
1628 'the full traceback.\n']
1602 stb.extend(self.InteractiveTB.get_exception_only(etype,
1629 stb.extend(self.InteractiveTB.get_exception_only(etype,
1603 value))
1630 value))
1604 else:
1631 else:
1605 stb = self.InteractiveTB.structured_traceback(etype,
1632 stb = self.InteractiveTB.structured_traceback(etype,
1606 value, tb, tb_offset=tb_offset)
1633 value, tb, tb_offset=tb_offset)
1607
1634
1608 self._showtraceback(etype, value, stb)
1635 self._showtraceback(etype, value, stb)
1609 if self.call_pdb:
1636 if self.call_pdb:
1610 # drop into debugger
1637 # drop into debugger
1611 self.debugger(force=True)
1638 self.debugger(force=True)
1612 return
1639 return
1613
1640
1614 # Actually show the traceback
1641 # Actually show the traceback
1615 self._showtraceback(etype, value, stb)
1642 self._showtraceback(etype, value, stb)
1616
1643
1617 except KeyboardInterrupt:
1644 except KeyboardInterrupt:
1618 self.write_err("\nKeyboardInterrupt\n")
1645 self.write_err("\nKeyboardInterrupt\n")
1619
1646
1620 def _showtraceback(self, etype, evalue, stb):
1647 def _showtraceback(self, etype, evalue, stb):
1621 """Actually show a traceback.
1648 """Actually show a traceback.
1622
1649
1623 Subclasses may override this method to put the traceback on a different
1650 Subclasses may override this method to put the traceback on a different
1624 place, like a side channel.
1651 place, like a side channel.
1625 """
1652 """
1626 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1653 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1627
1654
1628 def showsyntaxerror(self, filename=None):
1655 def showsyntaxerror(self, filename=None):
1629 """Display the syntax error that just occurred.
1656 """Display the syntax error that just occurred.
1630
1657
1631 This doesn't display a stack trace because there isn't one.
1658 This doesn't display a stack trace because there isn't one.
1632
1659
1633 If a filename is given, it is stuffed in the exception instead
1660 If a filename is given, it is stuffed in the exception instead
1634 of what was there before (because Python's parser always uses
1661 of what was there before (because Python's parser always uses
1635 "<string>" when reading from a string).
1662 "<string>" when reading from a string).
1636 """
1663 """
1637 etype, value, last_traceback = sys.exc_info()
1664 etype, value, last_traceback = sys.exc_info()
1638
1665
1639 # See note about these variables in showtraceback() above
1666 # See note about these variables in showtraceback() above
1640 sys.last_type = etype
1667 sys.last_type = etype
1641 sys.last_value = value
1668 sys.last_value = value
1642 sys.last_traceback = last_traceback
1669 sys.last_traceback = last_traceback
1643
1670
1644 if filename and etype is SyntaxError:
1671 if filename and etype is SyntaxError:
1645 # Work hard to stuff the correct filename in the exception
1672 # Work hard to stuff the correct filename in the exception
1646 try:
1673 try:
1647 msg, (dummy_filename, lineno, offset, line) = value
1674 msg, (dummy_filename, lineno, offset, line) = value
1648 except:
1675 except:
1649 # Not the format we expect; leave it alone
1676 # Not the format we expect; leave it alone
1650 pass
1677 pass
1651 else:
1678 else:
1652 # Stuff in the right filename
1679 # Stuff in the right filename
1653 try:
1680 try:
1654 # Assume SyntaxError is a class exception
1681 # Assume SyntaxError is a class exception
1655 value = SyntaxError(msg, (filename, lineno, offset, line))
1682 value = SyntaxError(msg, (filename, lineno, offset, line))
1656 except:
1683 except:
1657 # If that failed, assume SyntaxError is a string
1684 # If that failed, assume SyntaxError is a string
1658 value = msg, (filename, lineno, offset, line)
1685 value = msg, (filename, lineno, offset, line)
1659 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1686 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1660 self._showtraceback(etype, value, stb)
1687 self._showtraceback(etype, value, stb)
1661
1688
1662 # This is overridden in TerminalInteractiveShell to show a message about
1689 # This is overridden in TerminalInteractiveShell to show a message about
1663 # the %paste magic.
1690 # the %paste magic.
1664 def showindentationerror(self):
1691 def showindentationerror(self):
1665 """Called by run_cell when there's an IndentationError in code entered
1692 """Called by run_cell when there's an IndentationError in code entered
1666 at the prompt.
1693 at the prompt.
1667
1694
1668 This is overridden in TerminalInteractiveShell to show a message about
1695 This is overridden in TerminalInteractiveShell to show a message about
1669 the %paste magic."""
1696 the %paste magic."""
1670 self.showsyntaxerror()
1697 self.showsyntaxerror()
1671
1698
1672 #-------------------------------------------------------------------------
1699 #-------------------------------------------------------------------------
1673 # Things related to readline
1700 # Things related to readline
1674 #-------------------------------------------------------------------------
1701 #-------------------------------------------------------------------------
1675
1702
1676 def init_readline(self):
1703 def init_readline(self):
1677 """Command history completion/saving/reloading."""
1704 """Command history completion/saving/reloading."""
1678
1705
1679 if self.readline_use:
1706 if self.readline_use:
1680 import IPython.utils.rlineimpl as readline
1707 import IPython.utils.rlineimpl as readline
1681
1708
1682 self.rl_next_input = None
1709 self.rl_next_input = None
1683 self.rl_do_indent = False
1710 self.rl_do_indent = False
1684
1711
1685 if not self.readline_use or not readline.have_readline:
1712 if not self.readline_use or not readline.have_readline:
1686 self.has_readline = False
1713 self.has_readline = False
1687 self.readline = None
1714 self.readline = None
1688 # Set a number of methods that depend on readline to be no-op
1715 # Set a number of methods that depend on readline to be no-op
1689 self.readline_no_record = no_op_context
1716 self.readline_no_record = no_op_context
1690 self.set_readline_completer = no_op
1717 self.set_readline_completer = no_op
1691 self.set_custom_completer = no_op
1718 self.set_custom_completer = no_op
1692 self.set_completer_frame = no_op
1719 self.set_completer_frame = no_op
1693 if self.readline_use:
1720 if self.readline_use:
1694 warn('Readline services not available or not loaded.')
1721 warn('Readline services not available or not loaded.')
1695 else:
1722 else:
1696 self.has_readline = True
1723 self.has_readline = True
1697 self.readline = readline
1724 self.readline = readline
1698 sys.modules['readline'] = readline
1725 sys.modules['readline'] = readline
1699
1726
1700 # Platform-specific configuration
1727 # Platform-specific configuration
1701 if os.name == 'nt':
1728 if os.name == 'nt':
1702 # FIXME - check with Frederick to see if we can harmonize
1729 # FIXME - check with Frederick to see if we can harmonize
1703 # naming conventions with pyreadline to avoid this
1730 # naming conventions with pyreadline to avoid this
1704 # platform-dependent check
1731 # platform-dependent check
1705 self.readline_startup_hook = readline.set_pre_input_hook
1732 self.readline_startup_hook = readline.set_pre_input_hook
1706 else:
1733 else:
1707 self.readline_startup_hook = readline.set_startup_hook
1734 self.readline_startup_hook = readline.set_startup_hook
1708
1735
1709 # Load user's initrc file (readline config)
1736 # Load user's initrc file (readline config)
1710 # Or if libedit is used, load editrc.
1737 # Or if libedit is used, load editrc.
1711 inputrc_name = os.environ.get('INPUTRC')
1738 inputrc_name = os.environ.get('INPUTRC')
1712 if inputrc_name is None:
1739 if inputrc_name is None:
1713 inputrc_name = '.inputrc'
1740 inputrc_name = '.inputrc'
1714 if readline.uses_libedit:
1741 if readline.uses_libedit:
1715 inputrc_name = '.editrc'
1742 inputrc_name = '.editrc'
1716 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1743 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1717 if os.path.isfile(inputrc_name):
1744 if os.path.isfile(inputrc_name):
1718 try:
1745 try:
1719 readline.read_init_file(inputrc_name)
1746 readline.read_init_file(inputrc_name)
1720 except:
1747 except:
1721 warn('Problems reading readline initialization file <%s>'
1748 warn('Problems reading readline initialization file <%s>'
1722 % inputrc_name)
1749 % inputrc_name)
1723
1750
1724 # Configure readline according to user's prefs
1751 # Configure readline according to user's prefs
1725 # This is only done if GNU readline is being used. If libedit
1752 # This is only done if GNU readline is being used. If libedit
1726 # is being used (as on Leopard) the readline config is
1753 # is being used (as on Leopard) the readline config is
1727 # not run as the syntax for libedit is different.
1754 # not run as the syntax for libedit is different.
1728 if not readline.uses_libedit:
1755 if not readline.uses_libedit:
1729 for rlcommand in self.readline_parse_and_bind:
1756 for rlcommand in self.readline_parse_and_bind:
1730 #print "loading rl:",rlcommand # dbg
1757 #print "loading rl:",rlcommand # dbg
1731 readline.parse_and_bind(rlcommand)
1758 readline.parse_and_bind(rlcommand)
1732
1759
1733 # Remove some chars from the delimiters list. If we encounter
1760 # Remove some chars from the delimiters list. If we encounter
1734 # unicode chars, discard them.
1761 # unicode chars, discard them.
1735 delims = readline.get_completer_delims()
1762 delims = readline.get_completer_delims()
1736 if not py3compat.PY3:
1763 if not py3compat.PY3:
1737 delims = delims.encode("ascii", "ignore")
1764 delims = delims.encode("ascii", "ignore")
1738 for d in self.readline_remove_delims:
1765 for d in self.readline_remove_delims:
1739 delims = delims.replace(d, "")
1766 delims = delims.replace(d, "")
1740 delims = delims.replace(ESC_MAGIC, '')
1767 delims = delims.replace(ESC_MAGIC, '')
1741 readline.set_completer_delims(delims)
1768 readline.set_completer_delims(delims)
1742 # otherwise we end up with a monster history after a while:
1769 # otherwise we end up with a monster history after a while:
1743 readline.set_history_length(self.history_length)
1770 readline.set_history_length(self.history_length)
1744
1771
1745 self.refill_readline_hist()
1772 self.refill_readline_hist()
1746 self.readline_no_record = ReadlineNoRecord(self)
1773 self.readline_no_record = ReadlineNoRecord(self)
1747
1774
1748 # Configure auto-indent for all platforms
1775 # Configure auto-indent for all platforms
1749 self.set_autoindent(self.autoindent)
1776 self.set_autoindent(self.autoindent)
1750
1777
1751 def refill_readline_hist(self):
1778 def refill_readline_hist(self):
1752 # Load the last 1000 lines from history
1779 # Load the last 1000 lines from history
1753 self.readline.clear_history()
1780 self.readline.clear_history()
1754 stdin_encoding = sys.stdin.encoding or "utf-8"
1781 stdin_encoding = sys.stdin.encoding or "utf-8"
1755 last_cell = u""
1782 last_cell = u""
1756 for _, _, cell in self.history_manager.get_tail(1000,
1783 for _, _, cell in self.history_manager.get_tail(1000,
1757 include_latest=True):
1784 include_latest=True):
1758 # Ignore blank lines and consecutive duplicates
1785 # Ignore blank lines and consecutive duplicates
1759 cell = cell.rstrip()
1786 cell = cell.rstrip()
1760 if cell and (cell != last_cell):
1787 if cell and (cell != last_cell):
1761 if self.multiline_history:
1788 if self.multiline_history:
1762 self.readline.add_history(py3compat.unicode_to_str(cell,
1789 self.readline.add_history(py3compat.unicode_to_str(cell,
1763 stdin_encoding))
1790 stdin_encoding))
1764 else:
1791 else:
1765 for line in cell.splitlines():
1792 for line in cell.splitlines():
1766 self.readline.add_history(py3compat.unicode_to_str(line,
1793 self.readline.add_history(py3compat.unicode_to_str(line,
1767 stdin_encoding))
1794 stdin_encoding))
1768 last_cell = cell
1795 last_cell = cell
1769
1796
1770 def set_next_input(self, s):
1797 def set_next_input(self, s):
1771 """ Sets the 'default' input string for the next command line.
1798 """ Sets the 'default' input string for the next command line.
1772
1799
1773 Requires readline.
1800 Requires readline.
1774
1801
1775 Example:
1802 Example:
1776
1803
1777 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1804 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1778 [D:\ipython]|2> Hello Word_ # cursor is here
1805 [D:\ipython]|2> Hello Word_ # cursor is here
1779 """
1806 """
1780 self.rl_next_input = py3compat.cast_bytes_py2(s)
1807 self.rl_next_input = py3compat.cast_bytes_py2(s)
1781
1808
1782 # Maybe move this to the terminal subclass?
1809 # Maybe move this to the terminal subclass?
1783 def pre_readline(self):
1810 def pre_readline(self):
1784 """readline hook to be used at the start of each line.
1811 """readline hook to be used at the start of each line.
1785
1812
1786 Currently it handles auto-indent only."""
1813 Currently it handles auto-indent only."""
1787
1814
1788 if self.rl_do_indent:
1815 if self.rl_do_indent:
1789 self.readline.insert_text(self._indent_current_str())
1816 self.readline.insert_text(self._indent_current_str())
1790 if self.rl_next_input is not None:
1817 if self.rl_next_input is not None:
1791 self.readline.insert_text(self.rl_next_input)
1818 self.readline.insert_text(self.rl_next_input)
1792 self.rl_next_input = None
1819 self.rl_next_input = None
1793
1820
1794 def _indent_current_str(self):
1821 def _indent_current_str(self):
1795 """return the current level of indentation as a string"""
1822 """return the current level of indentation as a string"""
1796 return self.input_splitter.indent_spaces * ' '
1823 return self.input_splitter.indent_spaces * ' '
1797
1824
1798 #-------------------------------------------------------------------------
1825 #-------------------------------------------------------------------------
1799 # Things related to text completion
1826 # Things related to text completion
1800 #-------------------------------------------------------------------------
1827 #-------------------------------------------------------------------------
1801
1828
1802 def init_completer(self):
1829 def init_completer(self):
1803 """Initialize the completion machinery.
1830 """Initialize the completion machinery.
1804
1831
1805 This creates completion machinery that can be used by client code,
1832 This creates completion machinery that can be used by client code,
1806 either interactively in-process (typically triggered by the readline
1833 either interactively in-process (typically triggered by the readline
1807 library), programatically (such as in test suites) or out-of-prcess
1834 library), programatically (such as in test suites) or out-of-prcess
1808 (typically over the network by remote frontends).
1835 (typically over the network by remote frontends).
1809 """
1836 """
1810 from IPython.core.completer import IPCompleter
1837 from IPython.core.completer import IPCompleter
1811 from IPython.core.completerlib import (module_completer,
1838 from IPython.core.completerlib import (module_completer,
1812 magic_run_completer, cd_completer)
1839 magic_run_completer, cd_completer)
1813
1840
1814 self.Completer = IPCompleter(shell=self,
1841 self.Completer = IPCompleter(shell=self,
1815 namespace=self.user_ns,
1842 namespace=self.user_ns,
1816 global_namespace=self.user_global_ns,
1843 global_namespace=self.user_global_ns,
1817 alias_table=self.alias_manager.alias_table,
1844 alias_table=self.alias_manager.alias_table,
1818 use_readline=self.has_readline,
1845 use_readline=self.has_readline,
1819 config=self.config,
1846 config=self.config,
1820 )
1847 )
1821 self.configurables.append(self.Completer)
1848 self.configurables.append(self.Completer)
1822
1849
1823 # Add custom completers to the basic ones built into IPCompleter
1850 # Add custom completers to the basic ones built into IPCompleter
1824 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1851 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1825 self.strdispatchers['complete_command'] = sdisp
1852 self.strdispatchers['complete_command'] = sdisp
1826 self.Completer.custom_completers = sdisp
1853 self.Completer.custom_completers = sdisp
1827
1854
1828 self.set_hook('complete_command', module_completer, str_key = 'import')
1855 self.set_hook('complete_command', module_completer, str_key = 'import')
1829 self.set_hook('complete_command', module_completer, str_key = 'from')
1856 self.set_hook('complete_command', module_completer, str_key = 'from')
1830 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1857 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1831 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1858 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1832
1859
1833 # Only configure readline if we truly are using readline. IPython can
1860 # Only configure readline if we truly are using readline. IPython can
1834 # do tab-completion over the network, in GUIs, etc, where readline
1861 # do tab-completion over the network, in GUIs, etc, where readline
1835 # itself may be absent
1862 # itself may be absent
1836 if self.has_readline:
1863 if self.has_readline:
1837 self.set_readline_completer()
1864 self.set_readline_completer()
1838
1865
1839 def complete(self, text, line=None, cursor_pos=None):
1866 def complete(self, text, line=None, cursor_pos=None):
1840 """Return the completed text and a list of completions.
1867 """Return the completed text and a list of completions.
1841
1868
1842 Parameters
1869 Parameters
1843 ----------
1870 ----------
1844
1871
1845 text : string
1872 text : string
1846 A string of text to be completed on. It can be given as empty and
1873 A string of text to be completed on. It can be given as empty and
1847 instead a line/position pair are given. In this case, the
1874 instead a line/position pair are given. In this case, the
1848 completer itself will split the line like readline does.
1875 completer itself will split the line like readline does.
1849
1876
1850 line : string, optional
1877 line : string, optional
1851 The complete line that text is part of.
1878 The complete line that text is part of.
1852
1879
1853 cursor_pos : int, optional
1880 cursor_pos : int, optional
1854 The position of the cursor on the input line.
1881 The position of the cursor on the input line.
1855
1882
1856 Returns
1883 Returns
1857 -------
1884 -------
1858 text : string
1885 text : string
1859 The actual text that was completed.
1886 The actual text that was completed.
1860
1887
1861 matches : list
1888 matches : list
1862 A sorted list with all possible completions.
1889 A sorted list with all possible completions.
1863
1890
1864 The optional arguments allow the completion to take more context into
1891 The optional arguments allow the completion to take more context into
1865 account, and are part of the low-level completion API.
1892 account, and are part of the low-level completion API.
1866
1893
1867 This is a wrapper around the completion mechanism, similar to what
1894 This is a wrapper around the completion mechanism, similar to what
1868 readline does at the command line when the TAB key is hit. By
1895 readline does at the command line when the TAB key is hit. By
1869 exposing it as a method, it can be used by other non-readline
1896 exposing it as a method, it can be used by other non-readline
1870 environments (such as GUIs) for text completion.
1897 environments (such as GUIs) for text completion.
1871
1898
1872 Simple usage example:
1899 Simple usage example:
1873
1900
1874 In [1]: x = 'hello'
1901 In [1]: x = 'hello'
1875
1902
1876 In [2]: _ip.complete('x.l')
1903 In [2]: _ip.complete('x.l')
1877 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1904 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1878 """
1905 """
1879
1906
1880 # Inject names into __builtin__ so we can complete on the added names.
1907 # Inject names into __builtin__ so we can complete on the added names.
1881 with self.builtin_trap:
1908 with self.builtin_trap:
1882 return self.Completer.complete(text, line, cursor_pos)
1909 return self.Completer.complete(text, line, cursor_pos)
1883
1910
1884 def set_custom_completer(self, completer, pos=0):
1911 def set_custom_completer(self, completer, pos=0):
1885 """Adds a new custom completer function.
1912 """Adds a new custom completer function.
1886
1913
1887 The position argument (defaults to 0) is the index in the completers
1914 The position argument (defaults to 0) is the index in the completers
1888 list where you want the completer to be inserted."""
1915 list where you want the completer to be inserted."""
1889
1916
1890 newcomp = types.MethodType(completer,self.Completer)
1917 newcomp = types.MethodType(completer,self.Completer)
1891 self.Completer.matchers.insert(pos,newcomp)
1918 self.Completer.matchers.insert(pos,newcomp)
1892
1919
1893 def set_readline_completer(self):
1920 def set_readline_completer(self):
1894 """Reset readline's completer to be our own."""
1921 """Reset readline's completer to be our own."""
1895 self.readline.set_completer(self.Completer.rlcomplete)
1922 self.readline.set_completer(self.Completer.rlcomplete)
1896
1923
1897 def set_completer_frame(self, frame=None):
1924 def set_completer_frame(self, frame=None):
1898 """Set the frame of the completer."""
1925 """Set the frame of the completer."""
1899 if frame:
1926 if frame:
1900 self.Completer.namespace = frame.f_locals
1927 self.Completer.namespace = frame.f_locals
1901 self.Completer.global_namespace = frame.f_globals
1928 self.Completer.global_namespace = frame.f_globals
1902 else:
1929 else:
1903 self.Completer.namespace = self.user_ns
1930 self.Completer.namespace = self.user_ns
1904 self.Completer.global_namespace = self.user_global_ns
1931 self.Completer.global_namespace = self.user_global_ns
1905
1932
1906 #-------------------------------------------------------------------------
1933 #-------------------------------------------------------------------------
1907 # Things related to magics
1934 # Things related to magics
1908 #-------------------------------------------------------------------------
1935 #-------------------------------------------------------------------------
1909
1936
1910 def init_magics(self):
1937 def init_magics(self):
1911 # FIXME: Move the color initialization to the DisplayHook, which
1938 # FIXME: Move the color initialization to the DisplayHook, which
1912 # should be split into a prompt manager and displayhook. We probably
1939 # should be split into a prompt manager and displayhook. We probably
1913 # even need a centralize colors management object.
1940 # even need a centralize colors management object.
1914 self.magic_colors(self.colors)
1941 self.magic_colors(self.colors)
1915 # History was moved to a separate module
1942 # History was moved to a separate module
1916 from . import history
1943 from . import history
1917 history.init_ipython(self)
1944 history.init_ipython(self)
1918
1945
1919 def magic(self, arg_s, next_input=None):
1946 def magic(self, arg_s, next_input=None):
1920 """Call a magic function by name.
1947 """Call a magic function by name.
1921
1948
1922 Input: a string containing the name of the magic function to call and
1949 Input: a string containing the name of the magic function to call and
1923 any additional arguments to be passed to the magic.
1950 any additional arguments to be passed to the magic.
1924
1951
1925 magic('name -opt foo bar') is equivalent to typing at the ipython
1952 magic('name -opt foo bar') is equivalent to typing at the ipython
1926 prompt:
1953 prompt:
1927
1954
1928 In[1]: %name -opt foo bar
1955 In[1]: %name -opt foo bar
1929
1956
1930 To call a magic without arguments, simply use magic('name').
1957 To call a magic without arguments, simply use magic('name').
1931
1958
1932 This provides a proper Python function to call IPython's magics in any
1959 This provides a proper Python function to call IPython's magics in any
1933 valid Python code you can type at the interpreter, including loops and
1960 valid Python code you can type at the interpreter, including loops and
1934 compound statements.
1961 compound statements.
1935 """
1962 """
1936 # Allow setting the next input - this is used if the user does `a=abs?`.
1963 # Allow setting the next input - this is used if the user does `a=abs?`.
1937 # We do this first so that magic functions can override it.
1964 # We do this first so that magic functions can override it.
1938 if next_input:
1965 if next_input:
1939 self.set_next_input(next_input)
1966 self.set_next_input(next_input)
1940
1967
1941 args = arg_s.split(' ',1)
1968 args = arg_s.split(' ',1)
1942 magic_name = args[0]
1969 magic_name = args[0]
1943 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1970 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1944
1971
1945 try:
1972 try:
1946 magic_args = args[1]
1973 magic_args = args[1]
1947 except IndexError:
1974 except IndexError:
1948 magic_args = ''
1975 magic_args = ''
1949 fn = getattr(self,'magic_'+magic_name,None)
1976 fn = getattr(self,'magic_'+magic_name,None)
1950 if fn is None:
1977 if fn is None:
1951 error("Magic function `%s` not found." % magic_name)
1978 error("Magic function `%s` not found." % magic_name)
1952 else:
1979 else:
1953 magic_args = self.var_expand(magic_args,1)
1980 magic_args = self.var_expand(magic_args,1)
1954 # Grab local namespace if we need it:
1981 # Grab local namespace if we need it:
1955 if getattr(fn, "needs_local_scope", False):
1982 if getattr(fn, "needs_local_scope", False):
1956 self._magic_locals = sys._getframe(1).f_locals
1983 self._magic_locals = sys._getframe(1).f_locals
1957 with self.builtin_trap:
1984 with self.builtin_trap:
1958 result = fn(magic_args)
1985 result = fn(magic_args)
1959 # Ensure we're not keeping object references around:
1986 # Ensure we're not keeping object references around:
1960 self._magic_locals = {}
1987 self._magic_locals = {}
1961 return result
1988 return result
1962
1989
1963 def define_magic(self, magicname, func):
1990 def define_magic(self, magicname, func):
1964 """Expose own function as magic function for ipython
1991 """Expose own function as magic function for ipython
1965
1992
1966 Example::
1993 Example::
1967
1994
1968 def foo_impl(self,parameter_s=''):
1995 def foo_impl(self,parameter_s=''):
1969 'My very own magic!. (Use docstrings, IPython reads them).'
1996 'My very own magic!. (Use docstrings, IPython reads them).'
1970 print 'Magic function. Passed parameter is between < >:'
1997 print 'Magic function. Passed parameter is between < >:'
1971 print '<%s>' % parameter_s
1998 print '<%s>' % parameter_s
1972 print 'The self object is:', self
1999 print 'The self object is:', self
1973
2000
1974 ip.define_magic('foo',foo_impl)
2001 ip.define_magic('foo',foo_impl)
1975 """
2002 """
1976 im = types.MethodType(func,self)
2003 im = types.MethodType(func,self)
1977 old = getattr(self, "magic_" + magicname, None)
2004 old = getattr(self, "magic_" + magicname, None)
1978 setattr(self, "magic_" + magicname, im)
2005 setattr(self, "magic_" + magicname, im)
1979 return old
2006 return old
1980
2007
1981 #-------------------------------------------------------------------------
2008 #-------------------------------------------------------------------------
1982 # Things related to macros
2009 # Things related to macros
1983 #-------------------------------------------------------------------------
2010 #-------------------------------------------------------------------------
1984
2011
1985 def define_macro(self, name, themacro):
2012 def define_macro(self, name, themacro):
1986 """Define a new macro
2013 """Define a new macro
1987
2014
1988 Parameters
2015 Parameters
1989 ----------
2016 ----------
1990 name : str
2017 name : str
1991 The name of the macro.
2018 The name of the macro.
1992 themacro : str or Macro
2019 themacro : str or Macro
1993 The action to do upon invoking the macro. If a string, a new
2020 The action to do upon invoking the macro. If a string, a new
1994 Macro object is created by passing the string to it.
2021 Macro object is created by passing the string to it.
1995 """
2022 """
1996
2023
1997 from IPython.core import macro
2024 from IPython.core import macro
1998
2025
1999 if isinstance(themacro, basestring):
2026 if isinstance(themacro, basestring):
2000 themacro = macro.Macro(themacro)
2027 themacro = macro.Macro(themacro)
2001 if not isinstance(themacro, macro.Macro):
2028 if not isinstance(themacro, macro.Macro):
2002 raise ValueError('A macro must be a string or a Macro instance.')
2029 raise ValueError('A macro must be a string or a Macro instance.')
2003 self.user_ns[name] = themacro
2030 self.user_ns[name] = themacro
2004
2031
2005 #-------------------------------------------------------------------------
2032 #-------------------------------------------------------------------------
2006 # Things related to the running of system commands
2033 # Things related to the running of system commands
2007 #-------------------------------------------------------------------------
2034 #-------------------------------------------------------------------------
2008
2035
2009 def system_piped(self, cmd):
2036 def system_piped(self, cmd):
2010 """Call the given cmd in a subprocess, piping stdout/err
2037 """Call the given cmd in a subprocess, piping stdout/err
2011
2038
2012 Parameters
2039 Parameters
2013 ----------
2040 ----------
2014 cmd : str
2041 cmd : str
2015 Command to execute (can not end in '&', as background processes are
2042 Command to execute (can not end in '&', as background processes are
2016 not supported. Should not be a command that expects input
2043 not supported. Should not be a command that expects input
2017 other than simple text.
2044 other than simple text.
2018 """
2045 """
2019 if cmd.rstrip().endswith('&'):
2046 if cmd.rstrip().endswith('&'):
2020 # this is *far* from a rigorous test
2047 # this is *far* from a rigorous test
2021 # We do not support backgrounding processes because we either use
2048 # We do not support backgrounding processes because we either use
2022 # pexpect or pipes to read from. Users can always just call
2049 # pexpect or pipes to read from. Users can always just call
2023 # os.system() or use ip.system=ip.system_raw
2050 # os.system() or use ip.system=ip.system_raw
2024 # if they really want a background process.
2051 # if they really want a background process.
2025 raise OSError("Background processes not supported.")
2052 raise OSError("Background processes not supported.")
2026
2053
2027 # we explicitly do NOT return the subprocess status code, because
2054 # we explicitly do NOT return the subprocess status code, because
2028 # a non-None value would trigger :func:`sys.displayhook` calls.
2055 # a non-None value would trigger :func:`sys.displayhook` calls.
2029 # Instead, we store the exit_code in user_ns.
2056 # Instead, we store the exit_code in user_ns.
2030 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2057 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2031
2058
2032 def system_raw(self, cmd):
2059 def system_raw(self, cmd):
2033 """Call the given cmd in a subprocess using os.system
2060 """Call the given cmd in a subprocess using os.system
2034
2061
2035 Parameters
2062 Parameters
2036 ----------
2063 ----------
2037 cmd : str
2064 cmd : str
2038 Command to execute.
2065 Command to execute.
2039 """
2066 """
2040 cmd = self.var_expand(cmd, depth=2)
2067 cmd = self.var_expand(cmd, depth=2)
2041 # protect os.system from UNC paths on Windows, which it can't handle:
2068 # protect os.system from UNC paths on Windows, which it can't handle:
2042 if sys.platform == 'win32':
2069 if sys.platform == 'win32':
2043 from IPython.utils._process_win32 import AvoidUNCPath
2070 from IPython.utils._process_win32 import AvoidUNCPath
2044 with AvoidUNCPath() as path:
2071 with AvoidUNCPath() as path:
2045 if path is not None:
2072 if path is not None:
2046 cmd = '"pushd %s &&"%s' % (path, cmd)
2073 cmd = '"pushd %s &&"%s' % (path, cmd)
2047 cmd = py3compat.unicode_to_str(cmd)
2074 cmd = py3compat.unicode_to_str(cmd)
2048 ec = os.system(cmd)
2075 ec = os.system(cmd)
2049 else:
2076 else:
2050 cmd = py3compat.unicode_to_str(cmd)
2077 cmd = py3compat.unicode_to_str(cmd)
2051 ec = os.system(cmd)
2078 ec = os.system(cmd)
2052
2079
2053 # We explicitly do NOT return the subprocess status code, because
2080 # We explicitly do NOT return the subprocess status code, because
2054 # a non-None value would trigger :func:`sys.displayhook` calls.
2081 # a non-None value would trigger :func:`sys.displayhook` calls.
2055 # Instead, we store the exit_code in user_ns.
2082 # Instead, we store the exit_code in user_ns.
2056 self.user_ns['_exit_code'] = ec
2083 self.user_ns['_exit_code'] = ec
2057
2084
2058 # use piped system by default, because it is better behaved
2085 # use piped system by default, because it is better behaved
2059 system = system_piped
2086 system = system_piped
2060
2087
2061 def getoutput(self, cmd, split=True):
2088 def getoutput(self, cmd, split=True):
2062 """Get output (possibly including stderr) from a subprocess.
2089 """Get output (possibly including stderr) from a subprocess.
2063
2090
2064 Parameters
2091 Parameters
2065 ----------
2092 ----------
2066 cmd : str
2093 cmd : str
2067 Command to execute (can not end in '&', as background processes are
2094 Command to execute (can not end in '&', as background processes are
2068 not supported.
2095 not supported.
2069 split : bool, optional
2096 split : bool, optional
2070
2097
2071 If True, split the output into an IPython SList. Otherwise, an
2098 If True, split the output into an IPython SList. Otherwise, an
2072 IPython LSString is returned. These are objects similar to normal
2099 IPython LSString is returned. These are objects similar to normal
2073 lists and strings, with a few convenience attributes for easier
2100 lists and strings, with a few convenience attributes for easier
2074 manipulation of line-based output. You can use '?' on them for
2101 manipulation of line-based output. You can use '?' on them for
2075 details.
2102 details.
2076 """
2103 """
2077 if cmd.rstrip().endswith('&'):
2104 if cmd.rstrip().endswith('&'):
2078 # this is *far* from a rigorous test
2105 # this is *far* from a rigorous test
2079 raise OSError("Background processes not supported.")
2106 raise OSError("Background processes not supported.")
2080 out = getoutput(self.var_expand(cmd, depth=2))
2107 out = getoutput(self.var_expand(cmd, depth=2))
2081 if split:
2108 if split:
2082 out = SList(out.splitlines())
2109 out = SList(out.splitlines())
2083 else:
2110 else:
2084 out = LSString(out)
2111 out = LSString(out)
2085 return out
2112 return out
2086
2113
2087 #-------------------------------------------------------------------------
2114 #-------------------------------------------------------------------------
2088 # Things related to aliases
2115 # Things related to aliases
2089 #-------------------------------------------------------------------------
2116 #-------------------------------------------------------------------------
2090
2117
2091 def init_alias(self):
2118 def init_alias(self):
2092 self.alias_manager = AliasManager(shell=self, config=self.config)
2119 self.alias_manager = AliasManager(shell=self, config=self.config)
2093 self.configurables.append(self.alias_manager)
2120 self.configurables.append(self.alias_manager)
2094 self.ns_table['alias'] = self.alias_manager.alias_table,
2121 self.ns_table['alias'] = self.alias_manager.alias_table,
2095
2122
2096 #-------------------------------------------------------------------------
2123 #-------------------------------------------------------------------------
2097 # Things related to extensions and plugins
2124 # Things related to extensions and plugins
2098 #-------------------------------------------------------------------------
2125 #-------------------------------------------------------------------------
2099
2126
2100 def init_extension_manager(self):
2127 def init_extension_manager(self):
2101 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2128 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2102 self.configurables.append(self.extension_manager)
2129 self.configurables.append(self.extension_manager)
2103
2130
2104 def init_plugin_manager(self):
2131 def init_plugin_manager(self):
2105 self.plugin_manager = PluginManager(config=self.config)
2132 self.plugin_manager = PluginManager(config=self.config)
2106 self.configurables.append(self.plugin_manager)
2133 self.configurables.append(self.plugin_manager)
2107
2134
2108
2135
2109 #-------------------------------------------------------------------------
2136 #-------------------------------------------------------------------------
2110 # Things related to payloads
2137 # Things related to payloads
2111 #-------------------------------------------------------------------------
2138 #-------------------------------------------------------------------------
2112
2139
2113 def init_payload(self):
2140 def init_payload(self):
2114 self.payload_manager = PayloadManager(config=self.config)
2141 self.payload_manager = PayloadManager(config=self.config)
2115 self.configurables.append(self.payload_manager)
2142 self.configurables.append(self.payload_manager)
2116
2143
2117 #-------------------------------------------------------------------------
2144 #-------------------------------------------------------------------------
2118 # Things related to the prefilter
2145 # Things related to the prefilter
2119 #-------------------------------------------------------------------------
2146 #-------------------------------------------------------------------------
2120
2147
2121 def init_prefilter(self):
2148 def init_prefilter(self):
2122 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2149 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2123 self.configurables.append(self.prefilter_manager)
2150 self.configurables.append(self.prefilter_manager)
2124 # Ultimately this will be refactored in the new interpreter code, but
2151 # Ultimately this will be refactored in the new interpreter code, but
2125 # for now, we should expose the main prefilter method (there's legacy
2152 # for now, we should expose the main prefilter method (there's legacy
2126 # code out there that may rely on this).
2153 # code out there that may rely on this).
2127 self.prefilter = self.prefilter_manager.prefilter_lines
2154 self.prefilter = self.prefilter_manager.prefilter_lines
2128
2155
2129 def auto_rewrite_input(self, cmd):
2156 def auto_rewrite_input(self, cmd):
2130 """Print to the screen the rewritten form of the user's command.
2157 """Print to the screen the rewritten form of the user's command.
2131
2158
2132 This shows visual feedback by rewriting input lines that cause
2159 This shows visual feedback by rewriting input lines that cause
2133 automatic calling to kick in, like::
2160 automatic calling to kick in, like::
2134
2161
2135 /f x
2162 /f x
2136
2163
2137 into::
2164 into::
2138
2165
2139 ------> f(x)
2166 ------> f(x)
2140
2167
2141 after the user's input prompt. This helps the user understand that the
2168 after the user's input prompt. This helps the user understand that the
2142 input line was transformed automatically by IPython.
2169 input line was transformed automatically by IPython.
2143 """
2170 """
2144 rw = self.prompt_manager.render('rewrite') + cmd
2171 rw = self.prompt_manager.render('rewrite') + cmd
2145
2172
2146 try:
2173 try:
2147 # plain ascii works better w/ pyreadline, on some machines, so
2174 # plain ascii works better w/ pyreadline, on some machines, so
2148 # we use it and only print uncolored rewrite if we have unicode
2175 # we use it and only print uncolored rewrite if we have unicode
2149 rw = str(rw)
2176 rw = str(rw)
2150 print >> io.stdout, rw
2177 print >> io.stdout, rw
2151 except UnicodeEncodeError:
2178 except UnicodeEncodeError:
2152 print "------> " + cmd
2179 print "------> " + cmd
2153
2180
2154 #-------------------------------------------------------------------------
2181 #-------------------------------------------------------------------------
2155 # Things related to extracting values/expressions from kernel and user_ns
2182 # Things related to extracting values/expressions from kernel and user_ns
2156 #-------------------------------------------------------------------------
2183 #-------------------------------------------------------------------------
2157
2184
2158 def _simple_error(self):
2185 def _simple_error(self):
2159 etype, value = sys.exc_info()[:2]
2186 etype, value = sys.exc_info()[:2]
2160 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2187 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2161
2188
2162 def user_variables(self, names):
2189 def user_variables(self, names):
2163 """Get a list of variable names from the user's namespace.
2190 """Get a list of variable names from the user's namespace.
2164
2191
2165 Parameters
2192 Parameters
2166 ----------
2193 ----------
2167 names : list of strings
2194 names : list of strings
2168 A list of names of variables to be read from the user namespace.
2195 A list of names of variables to be read from the user namespace.
2169
2196
2170 Returns
2197 Returns
2171 -------
2198 -------
2172 A dict, keyed by the input names and with the repr() of each value.
2199 A dict, keyed by the input names and with the repr() of each value.
2173 """
2200 """
2174 out = {}
2201 out = {}
2175 user_ns = self.user_ns
2202 user_ns = self.user_ns
2176 for varname in names:
2203 for varname in names:
2177 try:
2204 try:
2178 value = repr(user_ns[varname])
2205 value = repr(user_ns[varname])
2179 except:
2206 except:
2180 value = self._simple_error()
2207 value = self._simple_error()
2181 out[varname] = value
2208 out[varname] = value
2182 return out
2209 return out
2183
2210
2184 def user_expressions(self, expressions):
2211 def user_expressions(self, expressions):
2185 """Evaluate a dict of expressions in the user's namespace.
2212 """Evaluate a dict of expressions in the user's namespace.
2186
2213
2187 Parameters
2214 Parameters
2188 ----------
2215 ----------
2189 expressions : dict
2216 expressions : dict
2190 A dict with string keys and string values. The expression values
2217 A dict with string keys and string values. The expression values
2191 should be valid Python expressions, each of which will be evaluated
2218 should be valid Python expressions, each of which will be evaluated
2192 in the user namespace.
2219 in the user namespace.
2193
2220
2194 Returns
2221 Returns
2195 -------
2222 -------
2196 A dict, keyed like the input expressions dict, with the repr() of each
2223 A dict, keyed like the input expressions dict, with the repr() of each
2197 value.
2224 value.
2198 """
2225 """
2199 out = {}
2226 out = {}
2200 user_ns = self.user_ns
2227 user_ns = self.user_ns
2201 global_ns = self.user_global_ns
2228 global_ns = self.user_global_ns
2202 for key, expr in expressions.iteritems():
2229 for key, expr in expressions.iteritems():
2203 try:
2230 try:
2204 value = repr(eval(expr, global_ns, user_ns))
2231 value = repr(eval(expr, global_ns, user_ns))
2205 except:
2232 except:
2206 value = self._simple_error()
2233 value = self._simple_error()
2207 out[key] = value
2234 out[key] = value
2208 return out
2235 return out
2209
2236
2210 #-------------------------------------------------------------------------
2237 #-------------------------------------------------------------------------
2211 # Things related to the running of code
2238 # Things related to the running of code
2212 #-------------------------------------------------------------------------
2239 #-------------------------------------------------------------------------
2213
2240
2214 def ex(self, cmd):
2241 def ex(self, cmd):
2215 """Execute a normal python statement in user namespace."""
2242 """Execute a normal python statement in user namespace."""
2216 with self.builtin_trap:
2243 with self.builtin_trap:
2217 exec cmd in self.user_global_ns, self.user_ns
2244 exec cmd in self.user_global_ns, self.user_ns
2218
2245
2219 def ev(self, expr):
2246 def ev(self, expr):
2220 """Evaluate python expression expr in user namespace.
2247 """Evaluate python expression expr in user namespace.
2221
2248
2222 Returns the result of evaluation
2249 Returns the result of evaluation
2223 """
2250 """
2224 with self.builtin_trap:
2251 with self.builtin_trap:
2225 return eval(expr, self.user_global_ns, self.user_ns)
2252 return eval(expr, self.user_global_ns, self.user_ns)
2226
2253
2227 def safe_execfile(self, fname, *where, **kw):
2254 def safe_execfile(self, fname, *where, **kw):
2228 """A safe version of the builtin execfile().
2255 """A safe version of the builtin execfile().
2229
2256
2230 This version will never throw an exception, but instead print
2257 This version will never throw an exception, but instead print
2231 helpful error messages to the screen. This only works on pure
2258 helpful error messages to the screen. This only works on pure
2232 Python files with the .py extension.
2259 Python files with the .py extension.
2233
2260
2234 Parameters
2261 Parameters
2235 ----------
2262 ----------
2236 fname : string
2263 fname : string
2237 The name of the file to be executed.
2264 The name of the file to be executed.
2238 where : tuple
2265 where : tuple
2239 One or two namespaces, passed to execfile() as (globals,locals).
2266 One or two namespaces, passed to execfile() as (globals,locals).
2240 If only one is given, it is passed as both.
2267 If only one is given, it is passed as both.
2241 exit_ignore : bool (False)
2268 exit_ignore : bool (False)
2242 If True, then silence SystemExit for non-zero status (it is always
2269 If True, then silence SystemExit for non-zero status (it is always
2243 silenced for zero status, as it is so common).
2270 silenced for zero status, as it is so common).
2244 raise_exceptions : bool (False)
2271 raise_exceptions : bool (False)
2245 If True raise exceptions everywhere. Meant for testing.
2272 If True raise exceptions everywhere. Meant for testing.
2246
2273
2247 """
2274 """
2248 kw.setdefault('exit_ignore', False)
2275 kw.setdefault('exit_ignore', False)
2249 kw.setdefault('raise_exceptions', False)
2276 kw.setdefault('raise_exceptions', False)
2250
2277
2251 fname = os.path.abspath(os.path.expanduser(fname))
2278 fname = os.path.abspath(os.path.expanduser(fname))
2252
2279
2253 # Make sure we can open the file
2280 # Make sure we can open the file
2254 try:
2281 try:
2255 with open(fname) as thefile:
2282 with open(fname) as thefile:
2256 pass
2283 pass
2257 except:
2284 except:
2258 warn('Could not open file <%s> for safe execution.' % fname)
2285 warn('Could not open file <%s> for safe execution.' % fname)
2259 return
2286 return
2260
2287
2261 # Find things also in current directory. This is needed to mimic the
2288 # Find things also in current directory. This is needed to mimic the
2262 # behavior of running a script from the system command line, where
2289 # behavior of running a script from the system command line, where
2263 # Python inserts the script's directory into sys.path
2290 # Python inserts the script's directory into sys.path
2264 dname = os.path.dirname(fname)
2291 dname = os.path.dirname(fname)
2265
2292
2266 with prepended_to_syspath(dname):
2293 with prepended_to_syspath(dname):
2267 try:
2294 try:
2268 py3compat.execfile(fname,*where)
2295 py3compat.execfile(fname,*where)
2269 except SystemExit, status:
2296 except SystemExit, status:
2270 # If the call was made with 0 or None exit status (sys.exit(0)
2297 # If the call was made with 0 or None exit status (sys.exit(0)
2271 # or sys.exit() ), don't bother showing a traceback, as both of
2298 # or sys.exit() ), don't bother showing a traceback, as both of
2272 # these are considered normal by the OS:
2299 # these are considered normal by the OS:
2273 # > python -c'import sys;sys.exit(0)'; echo $?
2300 # > python -c'import sys;sys.exit(0)'; echo $?
2274 # 0
2301 # 0
2275 # > python -c'import sys;sys.exit()'; echo $?
2302 # > python -c'import sys;sys.exit()'; echo $?
2276 # 0
2303 # 0
2277 # For other exit status, we show the exception unless
2304 # For other exit status, we show the exception unless
2278 # explicitly silenced, but only in short form.
2305 # explicitly silenced, but only in short form.
2279 if kw['raise_exceptions']:
2306 if kw['raise_exceptions']:
2280 raise
2307 raise
2281 if status.code not in (0, None) and not kw['exit_ignore']:
2308 if status.code not in (0, None) and not kw['exit_ignore']:
2282 self.showtraceback(exception_only=True)
2309 self.showtraceback(exception_only=True)
2283 except:
2310 except:
2284 if kw['raise_exceptions']:
2311 if kw['raise_exceptions']:
2285 raise
2312 raise
2286 self.showtraceback()
2313 self.showtraceback()
2287
2314
2288 def safe_execfile_ipy(self, fname):
2315 def safe_execfile_ipy(self, fname):
2289 """Like safe_execfile, but for .ipy files with IPython syntax.
2316 """Like safe_execfile, but for .ipy files with IPython syntax.
2290
2317
2291 Parameters
2318 Parameters
2292 ----------
2319 ----------
2293 fname : str
2320 fname : str
2294 The name of the file to execute. The filename must have a
2321 The name of the file to execute. The filename must have a
2295 .ipy extension.
2322 .ipy extension.
2296 """
2323 """
2297 fname = os.path.abspath(os.path.expanduser(fname))
2324 fname = os.path.abspath(os.path.expanduser(fname))
2298
2325
2299 # Make sure we can open the file
2326 # Make sure we can open the file
2300 try:
2327 try:
2301 with open(fname) as thefile:
2328 with open(fname) as thefile:
2302 pass
2329 pass
2303 except:
2330 except:
2304 warn('Could not open file <%s> for safe execution.' % fname)
2331 warn('Could not open file <%s> for safe execution.' % fname)
2305 return
2332 return
2306
2333
2307 # Find things also in current directory. This is needed to mimic the
2334 # Find things also in current directory. This is needed to mimic the
2308 # behavior of running a script from the system command line, where
2335 # behavior of running a script from the system command line, where
2309 # Python inserts the script's directory into sys.path
2336 # Python inserts the script's directory into sys.path
2310 dname = os.path.dirname(fname)
2337 dname = os.path.dirname(fname)
2311
2338
2312 with prepended_to_syspath(dname):
2339 with prepended_to_syspath(dname):
2313 try:
2340 try:
2314 with open(fname) as thefile:
2341 with open(fname) as thefile:
2315 # self.run_cell currently captures all exceptions
2342 # self.run_cell currently captures all exceptions
2316 # raised in user code. It would be nice if there were
2343 # raised in user code. It would be nice if there were
2317 # versions of runlines, execfile that did raise, so
2344 # versions of runlines, execfile that did raise, so
2318 # we could catch the errors.
2345 # we could catch the errors.
2319 self.run_cell(thefile.read(), store_history=False)
2346 self.run_cell(thefile.read(), store_history=False)
2320 except:
2347 except:
2321 self.showtraceback()
2348 self.showtraceback()
2322 warn('Unknown failure executing file: <%s>' % fname)
2349 warn('Unknown failure executing file: <%s>' % fname)
2323
2350
2324 def run_cell(self, raw_cell, store_history=False):
2351 def run_cell(self, raw_cell, store_history=False):
2325 """Run a complete IPython cell.
2352 """Run a complete IPython cell.
2326
2353
2327 Parameters
2354 Parameters
2328 ----------
2355 ----------
2329 raw_cell : str
2356 raw_cell : str
2330 The code (including IPython code such as %magic functions) to run.
2357 The code (including IPython code such as %magic functions) to run.
2331 store_history : bool
2358 store_history : bool
2332 If True, the raw and translated cell will be stored in IPython's
2359 If True, the raw and translated cell will be stored in IPython's
2333 history. For user code calling back into IPython's machinery, this
2360 history. For user code calling back into IPython's machinery, this
2334 should be set to False.
2361 should be set to False.
2335 """
2362 """
2336 if (not raw_cell) or raw_cell.isspace():
2363 if (not raw_cell) or raw_cell.isspace():
2337 return
2364 return
2338
2365
2339 for line in raw_cell.splitlines():
2366 for line in raw_cell.splitlines():
2340 self.input_splitter.push(line)
2367 self.input_splitter.push(line)
2341 cell = self.input_splitter.source_reset()
2368 cell = self.input_splitter.source_reset()
2342
2369
2343 with self.builtin_trap:
2370 with self.builtin_trap:
2344 prefilter_failed = False
2371 prefilter_failed = False
2345 if len(cell.splitlines()) == 1:
2372 if len(cell.splitlines()) == 1:
2346 try:
2373 try:
2347 # use prefilter_lines to handle trailing newlines
2374 # use prefilter_lines to handle trailing newlines
2348 # restore trailing newline for ast.parse
2375 # restore trailing newline for ast.parse
2349 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2376 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2350 except AliasError as e:
2377 except AliasError as e:
2351 error(e)
2378 error(e)
2352 prefilter_failed = True
2379 prefilter_failed = True
2353 except Exception:
2380 except Exception:
2354 # don't allow prefilter errors to crash IPython
2381 # don't allow prefilter errors to crash IPython
2355 self.showtraceback()
2382 self.showtraceback()
2356 prefilter_failed = True
2383 prefilter_failed = True
2357
2384
2358 # Store raw and processed history
2385 # Store raw and processed history
2359 if store_history:
2386 if store_history:
2360 self.history_manager.store_inputs(self.execution_count,
2387 self.history_manager.store_inputs(self.execution_count,
2361 cell, raw_cell)
2388 cell, raw_cell)
2362
2389
2363 self.logger.log(cell, raw_cell)
2390 self.logger.log(cell, raw_cell)
2364
2391
2365 if not prefilter_failed:
2392 if not prefilter_failed:
2366 # don't run if prefilter failed
2393 # don't run if prefilter failed
2367 cell_name = self.compile.cache(cell, self.execution_count)
2394 cell_name = self.compile.cache(cell, self.execution_count)
2368
2395
2369 with self.display_trap:
2396 with self.display_trap:
2370 try:
2397 try:
2371 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2398 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2372 except IndentationError:
2399 except IndentationError:
2373 self.showindentationerror()
2400 self.showindentationerror()
2374 self.execution_count += 1
2401 self.execution_count += 1
2375 return None
2402 return None
2376 except (OverflowError, SyntaxError, ValueError, TypeError,
2403 except (OverflowError, SyntaxError, ValueError, TypeError,
2377 MemoryError):
2404 MemoryError):
2378 self.showsyntaxerror()
2405 self.showsyntaxerror()
2379 self.execution_count += 1
2406 self.execution_count += 1
2380 return None
2407 return None
2381
2408
2382 self.run_ast_nodes(code_ast.body, cell_name,
2409 self.run_ast_nodes(code_ast.body, cell_name,
2383 interactivity="last_expr")
2410 interactivity="last_expr")
2384
2411
2385 # Execute any registered post-execution functions.
2412 # Execute any registered post-execution functions.
2386 for func, status in self._post_execute.iteritems():
2413 for func, status in self._post_execute.iteritems():
2387 if not status:
2414 if not status:
2388 continue
2415 continue
2389 try:
2416 try:
2390 func()
2417 func()
2391 except KeyboardInterrupt:
2418 except KeyboardInterrupt:
2392 print >> io.stderr, "\nKeyboardInterrupt"
2419 print >> io.stderr, "\nKeyboardInterrupt"
2393 except Exception:
2420 except Exception:
2394 print >> io.stderr, "Disabling failed post-execution function: %s" % func
2421 print >> io.stderr, "Disabling failed post-execution function: %s" % func
2395 self.showtraceback()
2422 self.showtraceback()
2396 # Deactivate failing function
2423 # Deactivate failing function
2397 self._post_execute[func] = False
2424 self._post_execute[func] = False
2398
2425
2399 if store_history:
2426 if store_history:
2400 # Write output to the database. Does nothing unless
2427 # Write output to the database. Does nothing unless
2401 # history output logging is enabled.
2428 # history output logging is enabled.
2402 self.history_manager.store_output(self.execution_count)
2429 self.history_manager.store_output(self.execution_count)
2403 # Each cell is a *single* input, regardless of how many lines it has
2430 # Each cell is a *single* input, regardless of how many lines it has
2404 self.execution_count += 1
2431 self.execution_count += 1
2405
2432
2406 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2433 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2407 """Run a sequence of AST nodes. The execution mode depends on the
2434 """Run a sequence of AST nodes. The execution mode depends on the
2408 interactivity parameter.
2435 interactivity parameter.
2409
2436
2410 Parameters
2437 Parameters
2411 ----------
2438 ----------
2412 nodelist : list
2439 nodelist : list
2413 A sequence of AST nodes to run.
2440 A sequence of AST nodes to run.
2414 cell_name : str
2441 cell_name : str
2415 Will be passed to the compiler as the filename of the cell. Typically
2442 Will be passed to the compiler as the filename of the cell. Typically
2416 the value returned by ip.compile.cache(cell).
2443 the value returned by ip.compile.cache(cell).
2417 interactivity : str
2444 interactivity : str
2418 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2445 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2419 run interactively (displaying output from expressions). 'last_expr'
2446 run interactively (displaying output from expressions). 'last_expr'
2420 will run the last node interactively only if it is an expression (i.e.
2447 will run the last node interactively only if it is an expression (i.e.
2421 expressions in loops or other blocks are not displayed. Other values
2448 expressions in loops or other blocks are not displayed. Other values
2422 for this parameter will raise a ValueError.
2449 for this parameter will raise a ValueError.
2423 """
2450 """
2424 if not nodelist:
2451 if not nodelist:
2425 return
2452 return
2426
2453
2427 if interactivity == 'last_expr':
2454 if interactivity == 'last_expr':
2428 if isinstance(nodelist[-1], ast.Expr):
2455 if isinstance(nodelist[-1], ast.Expr):
2429 interactivity = "last"
2456 interactivity = "last"
2430 else:
2457 else:
2431 interactivity = "none"
2458 interactivity = "none"
2432
2459
2433 if interactivity == 'none':
2460 if interactivity == 'none':
2434 to_run_exec, to_run_interactive = nodelist, []
2461 to_run_exec, to_run_interactive = nodelist, []
2435 elif interactivity == 'last':
2462 elif interactivity == 'last':
2436 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2463 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2437 elif interactivity == 'all':
2464 elif interactivity == 'all':
2438 to_run_exec, to_run_interactive = [], nodelist
2465 to_run_exec, to_run_interactive = [], nodelist
2439 else:
2466 else:
2440 raise ValueError("Interactivity was %r" % interactivity)
2467 raise ValueError("Interactivity was %r" % interactivity)
2441
2468
2442 exec_count = self.execution_count
2469 exec_count = self.execution_count
2443
2470
2444 try:
2471 try:
2445 for i, node in enumerate(to_run_exec):
2472 for i, node in enumerate(to_run_exec):
2446 mod = ast.Module([node])
2473 mod = ast.Module([node])
2447 code = self.compile(mod, cell_name, "exec")
2474 code = self.compile(mod, cell_name, "exec")
2448 if self.run_code(code):
2475 if self.run_code(code):
2449 return True
2476 return True
2450
2477
2451 for i, node in enumerate(to_run_interactive):
2478 for i, node in enumerate(to_run_interactive):
2452 mod = ast.Interactive([node])
2479 mod = ast.Interactive([node])
2453 code = self.compile(mod, cell_name, "single")
2480 code = self.compile(mod, cell_name, "single")
2454 if self.run_code(code):
2481 if self.run_code(code):
2455 return True
2482 return True
2456 except:
2483 except:
2457 # It's possible to have exceptions raised here, typically by
2484 # It's possible to have exceptions raised here, typically by
2458 # compilation of odd code (such as a naked 'return' outside a
2485 # compilation of odd code (such as a naked 'return' outside a
2459 # function) that did parse but isn't valid. Typically the exception
2486 # function) that did parse but isn't valid. Typically the exception
2460 # is a SyntaxError, but it's safest just to catch anything and show
2487 # is a SyntaxError, but it's safest just to catch anything and show
2461 # the user a traceback.
2488 # the user a traceback.
2462
2489
2463 # We do only one try/except outside the loop to minimize the impact
2490 # We do only one try/except outside the loop to minimize the impact
2464 # on runtime, and also because if any node in the node list is
2491 # on runtime, and also because if any node in the node list is
2465 # broken, we should stop execution completely.
2492 # broken, we should stop execution completely.
2466 self.showtraceback()
2493 self.showtraceback()
2467
2494
2468 return False
2495 return False
2469
2496
2470 def run_code(self, code_obj):
2497 def run_code(self, code_obj):
2471 """Execute a code object.
2498 """Execute a code object.
2472
2499
2473 When an exception occurs, self.showtraceback() is called to display a
2500 When an exception occurs, self.showtraceback() is called to display a
2474 traceback.
2501 traceback.
2475
2502
2476 Parameters
2503 Parameters
2477 ----------
2504 ----------
2478 code_obj : code object
2505 code_obj : code object
2479 A compiled code object, to be executed
2506 A compiled code object, to be executed
2480 post_execute : bool [default: True]
2507 post_execute : bool [default: True]
2481 whether to call post_execute hooks after this particular execution.
2508 whether to call post_execute hooks after this particular execution.
2482
2509
2483 Returns
2510 Returns
2484 -------
2511 -------
2485 False : successful execution.
2512 False : successful execution.
2486 True : an error occurred.
2513 True : an error occurred.
2487 """
2514 """
2488
2515
2489 # Set our own excepthook in case the user code tries to call it
2516 # Set our own excepthook in case the user code tries to call it
2490 # directly, so that the IPython crash handler doesn't get triggered
2517 # directly, so that the IPython crash handler doesn't get triggered
2491 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2518 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2492
2519
2493 # we save the original sys.excepthook in the instance, in case config
2520 # we save the original sys.excepthook in the instance, in case config
2494 # code (such as magics) needs access to it.
2521 # code (such as magics) needs access to it.
2495 self.sys_excepthook = old_excepthook
2522 self.sys_excepthook = old_excepthook
2496 outflag = 1 # happens in more places, so it's easier as default
2523 outflag = 1 # happens in more places, so it's easier as default
2497 try:
2524 try:
2498 try:
2525 try:
2499 self.hooks.pre_run_code_hook()
2526 self.hooks.pre_run_code_hook()
2500 #rprint('Running code', repr(code_obj)) # dbg
2527 #rprint('Running code', repr(code_obj)) # dbg
2501 exec code_obj in self.user_global_ns, self.user_ns
2528 exec code_obj in self.user_global_ns, self.user_ns
2502 finally:
2529 finally:
2503 # Reset our crash handler in place
2530 # Reset our crash handler in place
2504 sys.excepthook = old_excepthook
2531 sys.excepthook = old_excepthook
2505 except SystemExit:
2532 except SystemExit:
2506 self.showtraceback(exception_only=True)
2533 self.showtraceback(exception_only=True)
2507 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2534 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2508 except self.custom_exceptions:
2535 except self.custom_exceptions:
2509 etype,value,tb = sys.exc_info()
2536 etype,value,tb = sys.exc_info()
2510 self.CustomTB(etype,value,tb)
2537 self.CustomTB(etype,value,tb)
2511 except:
2538 except:
2512 self.showtraceback()
2539 self.showtraceback()
2513 else:
2540 else:
2514 outflag = 0
2541 outflag = 0
2515 if softspace(sys.stdout, 0):
2542 if softspace(sys.stdout, 0):
2516 print
2543 print
2517
2544
2518 return outflag
2545 return outflag
2519
2546
2520 # For backwards compatibility
2547 # For backwards compatibility
2521 runcode = run_code
2548 runcode = run_code
2522
2549
2523 #-------------------------------------------------------------------------
2550 #-------------------------------------------------------------------------
2524 # Things related to GUI support and pylab
2551 # Things related to GUI support and pylab
2525 #-------------------------------------------------------------------------
2552 #-------------------------------------------------------------------------
2526
2553
2527 def enable_gui(self, gui=None):
2554 def enable_gui(self, gui=None):
2528 raise NotImplementedError('Implement enable_gui in a subclass')
2555 raise NotImplementedError('Implement enable_gui in a subclass')
2529
2556
2530 def enable_pylab(self, gui=None, import_all=True):
2557 def enable_pylab(self, gui=None, import_all=True):
2531 """Activate pylab support at runtime.
2558 """Activate pylab support at runtime.
2532
2559
2533 This turns on support for matplotlib, preloads into the interactive
2560 This turns on support for matplotlib, preloads into the interactive
2534 namespace all of numpy and pylab, and configures IPython to correctly
2561 namespace all of numpy and pylab, and configures IPython to correctly
2535 interact with the GUI event loop. The GUI backend to be used can be
2562 interact with the GUI event loop. The GUI backend to be used can be
2536 optionally selected with the optional :param:`gui` argument.
2563 optionally selected with the optional :param:`gui` argument.
2537
2564
2538 Parameters
2565 Parameters
2539 ----------
2566 ----------
2540 gui : optional, string
2567 gui : optional, string
2541
2568
2542 If given, dictates the choice of matplotlib GUI backend to use
2569 If given, dictates the choice of matplotlib GUI backend to use
2543 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2570 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2544 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2571 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2545 matplotlib (as dictated by the matplotlib build-time options plus the
2572 matplotlib (as dictated by the matplotlib build-time options plus the
2546 user's matplotlibrc configuration file). Note that not all backends
2573 user's matplotlibrc configuration file). Note that not all backends
2547 make sense in all contexts, for example a terminal ipython can't
2574 make sense in all contexts, for example a terminal ipython can't
2548 display figures inline.
2575 display figures inline.
2549 """
2576 """
2550
2577
2551 # We want to prevent the loading of pylab to pollute the user's
2578 # We want to prevent the loading of pylab to pollute the user's
2552 # namespace as shown by the %who* magics, so we execute the activation
2579 # namespace as shown by the %who* magics, so we execute the activation
2553 # code in an empty namespace, and we update *both* user_ns and
2580 # code in an empty namespace, and we update *both* user_ns and
2554 # user_ns_hidden with this information.
2581 # user_ns_hidden with this information.
2555 ns = {}
2582 ns = {}
2556 try:
2583 try:
2557 gui = pylab_activate(ns, gui, import_all, self)
2584 gui = pylab_activate(ns, gui, import_all, self)
2558 except KeyError:
2585 except KeyError:
2559 error("Backend %r not supported" % gui)
2586 error("Backend %r not supported" % gui)
2560 return
2587 return
2561 self.user_ns.update(ns)
2588 self.user_ns.update(ns)
2562 self.user_ns_hidden.update(ns)
2589 self.user_ns_hidden.update(ns)
2563 # Now we must activate the gui pylab wants to use, and fix %run to take
2590 # Now we must activate the gui pylab wants to use, and fix %run to take
2564 # plot updates into account
2591 # plot updates into account
2565 self.enable_gui(gui)
2592 self.enable_gui(gui)
2566 self.magic_run = self._pylab_magic_run
2593 self.magic_run = self._pylab_magic_run
2567
2594
2568 #-------------------------------------------------------------------------
2595 #-------------------------------------------------------------------------
2569 # Utilities
2596 # Utilities
2570 #-------------------------------------------------------------------------
2597 #-------------------------------------------------------------------------
2571
2598
2572 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2599 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2573 """Expand python variables in a string.
2600 """Expand python variables in a string.
2574
2601
2575 The depth argument indicates how many frames above the caller should
2602 The depth argument indicates how many frames above the caller should
2576 be walked to look for the local namespace where to expand variables.
2603 be walked to look for the local namespace where to expand variables.
2577
2604
2578 The global namespace for expansion is always the user's interactive
2605 The global namespace for expansion is always the user's interactive
2579 namespace.
2606 namespace.
2580 """
2607 """
2581 ns = self.user_ns.copy()
2608 ns = self.user_ns.copy()
2582 ns.update(sys._getframe(depth+1).f_locals)
2609 ns.update(sys._getframe(depth+1).f_locals)
2583 ns.pop('self', None)
2610 ns.pop('self', None)
2584 return formatter.format(cmd, **ns)
2611 return formatter.format(cmd, **ns)
2585
2612
2586 def mktempfile(self, data=None, prefix='ipython_edit_'):
2613 def mktempfile(self, data=None, prefix='ipython_edit_'):
2587 """Make a new tempfile and return its filename.
2614 """Make a new tempfile and return its filename.
2588
2615
2589 This makes a call to tempfile.mktemp, but it registers the created
2616 This makes a call to tempfile.mktemp, but it registers the created
2590 filename internally so ipython cleans it up at exit time.
2617 filename internally so ipython cleans it up at exit time.
2591
2618
2592 Optional inputs:
2619 Optional inputs:
2593
2620
2594 - data(None): if data is given, it gets written out to the temp file
2621 - data(None): if data is given, it gets written out to the temp file
2595 immediately, and the file is closed again."""
2622 immediately, and the file is closed again."""
2596
2623
2597 filename = tempfile.mktemp('.py', prefix)
2624 filename = tempfile.mktemp('.py', prefix)
2598 self.tempfiles.append(filename)
2625 self.tempfiles.append(filename)
2599
2626
2600 if data:
2627 if data:
2601 tmp_file = open(filename,'w')
2628 tmp_file = open(filename,'w')
2602 tmp_file.write(data)
2629 tmp_file.write(data)
2603 tmp_file.close()
2630 tmp_file.close()
2604 return filename
2631 return filename
2605
2632
2606 # TODO: This should be removed when Term is refactored.
2633 # TODO: This should be removed when Term is refactored.
2607 def write(self,data):
2634 def write(self,data):
2608 """Write a string to the default output"""
2635 """Write a string to the default output"""
2609 io.stdout.write(data)
2636 io.stdout.write(data)
2610
2637
2611 # TODO: This should be removed when Term is refactored.
2638 # TODO: This should be removed when Term is refactored.
2612 def write_err(self,data):
2639 def write_err(self,data):
2613 """Write a string to the default error output"""
2640 """Write a string to the default error output"""
2614 io.stderr.write(data)
2641 io.stderr.write(data)
2615
2642
2616 def ask_yes_no(self, prompt, default=None):
2643 def ask_yes_no(self, prompt, default=None):
2617 if self.quiet:
2644 if self.quiet:
2618 return True
2645 return True
2619 return ask_yes_no(prompt,default)
2646 return ask_yes_no(prompt,default)
2620
2647
2621 def show_usage(self):
2648 def show_usage(self):
2622 """Show a usage message"""
2649 """Show a usage message"""
2623 page.page(IPython.core.usage.interactive_usage)
2650 page.page(IPython.core.usage.interactive_usage)
2624
2651
2625 def find_user_code(self, target, raw=True):
2652 def find_user_code(self, target, raw=True):
2626 """Get a code string from history, file, or a string or macro.
2653 """Get a code string from history, file, or a string or macro.
2627
2654
2628 This is mainly used by magic functions.
2655 This is mainly used by magic functions.
2629
2656
2630 Parameters
2657 Parameters
2631 ----------
2658 ----------
2632 target : str
2659 target : str
2633 A string specifying code to retrieve. This will be tried respectively
2660 A string specifying code to retrieve. This will be tried respectively
2634 as: ranges of input history (see %history for syntax), a filename, or
2661 as: ranges of input history (see %history for syntax), a filename, or
2635 an expression evaluating to a string or Macro in the user namespace.
2662 an expression evaluating to a string or Macro in the user namespace.
2636 raw : bool
2663 raw : bool
2637 If true (default), retrieve raw history. Has no effect on the other
2664 If true (default), retrieve raw history. Has no effect on the other
2638 retrieval mechanisms.
2665 retrieval mechanisms.
2639
2666
2640 Returns
2667 Returns
2641 -------
2668 -------
2642 A string of code.
2669 A string of code.
2643
2670
2644 ValueError is raised if nothing is found, and TypeError if it evaluates
2671 ValueError is raised if nothing is found, and TypeError if it evaluates
2645 to an object of another type. In each case, .args[0] is a printable
2672 to an object of another type. In each case, .args[0] is a printable
2646 message.
2673 message.
2647 """
2674 """
2648 code = self.extract_input_lines(target, raw=raw) # Grab history
2675 code = self.extract_input_lines(target, raw=raw) # Grab history
2649 if code:
2676 if code:
2650 return code
2677 return code
2651 if os.path.isfile(target): # Read file
2678 if os.path.isfile(target): # Read file
2652 return open(target, "r").read()
2679 return open(target, "r").read()
2653
2680
2654 try: # User namespace
2681 try: # User namespace
2655 codeobj = eval(target, self.user_ns)
2682 codeobj = eval(target, self.user_ns)
2656 except Exception:
2683 except Exception:
2657 raise ValueError(("'%s' was not found in history, as a file, nor in"
2684 raise ValueError(("'%s' was not found in history, as a file, nor in"
2658 " the user namespace.") % target)
2685 " the user namespace.") % target)
2659 if isinstance(codeobj, basestring):
2686 if isinstance(codeobj, basestring):
2660 return codeobj
2687 return codeobj
2661 elif isinstance(codeobj, Macro):
2688 elif isinstance(codeobj, Macro):
2662 return codeobj.value
2689 return codeobj.value
2663
2690
2664 raise TypeError("%s is neither a string nor a macro." % target,
2691 raise TypeError("%s is neither a string nor a macro." % target,
2665 codeobj)
2692 codeobj)
2666
2693
2667 #-------------------------------------------------------------------------
2694 #-------------------------------------------------------------------------
2668 # Things related to IPython exiting
2695 # Things related to IPython exiting
2669 #-------------------------------------------------------------------------
2696 #-------------------------------------------------------------------------
2670 def atexit_operations(self):
2697 def atexit_operations(self):
2671 """This will be executed at the time of exit.
2698 """This will be executed at the time of exit.
2672
2699
2673 Cleanup operations and saving of persistent data that is done
2700 Cleanup operations and saving of persistent data that is done
2674 unconditionally by IPython should be performed here.
2701 unconditionally by IPython should be performed here.
2675
2702
2676 For things that may depend on startup flags or platform specifics (such
2703 For things that may depend on startup flags or platform specifics (such
2677 as having readline or not), register a separate atexit function in the
2704 as having readline or not), register a separate atexit function in the
2678 code that has the appropriate information, rather than trying to
2705 code that has the appropriate information, rather than trying to
2679 clutter
2706 clutter
2680 """
2707 """
2681 # Close the history session (this stores the end time and line count)
2708 # Close the history session (this stores the end time and line count)
2682 # this must be *before* the tempfile cleanup, in case of temporary
2709 # this must be *before* the tempfile cleanup, in case of temporary
2683 # history db
2710 # history db
2684 self.history_manager.end_session()
2711 self.history_manager.end_session()
2685
2712
2686 # Cleanup all tempfiles left around
2713 # Cleanup all tempfiles left around
2687 for tfile in self.tempfiles:
2714 for tfile in self.tempfiles:
2688 try:
2715 try:
2689 os.unlink(tfile)
2716 os.unlink(tfile)
2690 except OSError:
2717 except OSError:
2691 pass
2718 pass
2692
2719
2693 # Clear all user namespaces to release all references cleanly.
2720 # Clear all user namespaces to release all references cleanly.
2694 self.reset(new_session=False)
2721 self.reset(new_session=False)
2695
2722
2696 # Run user hooks
2723 # Run user hooks
2697 self.hooks.shutdown_hook()
2724 self.hooks.shutdown_hook()
2698
2725
2699 def cleanup(self):
2726 def cleanup(self):
2700 self.restore_sys_module_state()
2727 self.restore_sys_module_state()
2701
2728
2702
2729
2703 class InteractiveShellABC(object):
2730 class InteractiveShellABC(object):
2704 """An abstract base class for InteractiveShell."""
2731 """An abstract base class for InteractiveShell."""
2705 __metaclass__ = abc.ABCMeta
2732 __metaclass__ = abc.ABCMeta
2706
2733
2707 InteractiveShellABC.register(InteractiveShell)
2734 InteractiveShellABC.register(InteractiveShell)
@@ -1,378 +1,382 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Classes for handling input/output prompts.
2 """Classes for handling input/output prompts.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian Granger
7 * Brian Granger
8 * Thomas Kluyver
8 * Thomas Kluyver
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2011 The IPython Development Team
12 # Copyright (C) 2008-2011 The IPython Development Team
13 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import os
23 import os
24 import re
24 import re
25 import socket
25 import socket
26 import sys
26 import sys
27 import time
27 import time
28
28
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.core import release
30 from IPython.core import release
31 from IPython.utils import coloransi
31 from IPython.utils import coloransi
32 from IPython.utils.traitlets import (Unicode, Instance, Dict, Bool, Int)
32 from IPython.utils.traitlets import (Unicode, Instance, Dict, Bool, Int)
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Color schemes for prompts
35 # Color schemes for prompts
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 InputColors = coloransi.InputTermColors # just a shorthand
38 InputColors = coloransi.InputTermColors # just a shorthand
39 Colors = coloransi.TermColors # just a shorthand
39 Colors = coloransi.TermColors # just a shorthand
40
40
41 color_lists = dict(normal=Colors(), inp=InputColors(), nocolor=coloransi.NoColors())
41 color_lists = dict(normal=Colors(), inp=InputColors(), nocolor=coloransi.NoColors())
42
42
43 PColNoColors = coloransi.ColorScheme(
43 PColNoColors = coloransi.ColorScheme(
44 'NoColor',
44 'NoColor',
45 in_prompt = InputColors.NoColor, # Input prompt
45 in_prompt = InputColors.NoColor, # Input prompt
46 in_number = InputColors.NoColor, # Input prompt number
46 in_number = InputColors.NoColor, # Input prompt number
47 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 in_prompt2 = InputColors.NoColor, # Continuation prompt
48 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
49
49
50 out_prompt = Colors.NoColor, # Output prompt
50 out_prompt = Colors.NoColor, # Output prompt
51 out_number = Colors.NoColor, # Output prompt number
51 out_number = Colors.NoColor, # Output prompt number
52
52
53 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 normal = Colors.NoColor # color off (usu. Colors.Normal)
54 )
54 )
55
55
56 # make some schemes as instances so we can copy them for modification easily:
56 # make some schemes as instances so we can copy them for modification easily:
57 PColLinux = coloransi.ColorScheme(
57 PColLinux = coloransi.ColorScheme(
58 'Linux',
58 'Linux',
59 in_prompt = InputColors.Green,
59 in_prompt = InputColors.Green,
60 in_number = InputColors.LightGreen,
60 in_number = InputColors.LightGreen,
61 in_prompt2 = InputColors.Green,
61 in_prompt2 = InputColors.Green,
62 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
63
63
64 out_prompt = Colors.Red,
64 out_prompt = Colors.Red,
65 out_number = Colors.LightRed,
65 out_number = Colors.LightRed,
66
66
67 normal = Colors.Normal
67 normal = Colors.Normal
68 )
68 )
69
69
70 # Slightly modified Linux for light backgrounds
70 # Slightly modified Linux for light backgrounds
71 PColLightBG = PColLinux.copy('LightBG')
71 PColLightBG = PColLinux.copy('LightBG')
72
72
73 PColLightBG.colors.update(
73 PColLightBG.colors.update(
74 in_prompt = InputColors.Blue,
74 in_prompt = InputColors.Blue,
75 in_number = InputColors.LightBlue,
75 in_number = InputColors.LightBlue,
76 in_prompt2 = InputColors.Blue
76 in_prompt2 = InputColors.Blue
77 )
77 )
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Utilities
80 # Utilities
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 class LazyEvaluate(object):
83 class LazyEvaluate(object):
84 """This is used for formatting strings with values that need to be updated
84 """This is used for formatting strings with values that need to be updated
85 at that time, such as the current time or working directory."""
85 at that time, such as the current time or working directory."""
86 def __init__(self, func, *args, **kwargs):
86 def __init__(self, func, *args, **kwargs):
87 self.func = func
87 self.func = func
88 self.args = args
88 self.args = args
89 self.kwargs = kwargs
89 self.kwargs = kwargs
90
90
91 def __call__(self, **kwargs):
91 def __call__(self, **kwargs):
92 self.kwargs.update(kwargs)
92 self.kwargs.update(kwargs)
93 return self.func(*self.args, **self.kwargs)
93 return self.func(*self.args, **self.kwargs)
94
94
95 def __str__(self):
95 def __str__(self):
96 return str(self())
96 return str(self())
97
97
98 def multiple_replace(dict, text):
98 def multiple_replace(dict, text):
99 """ Replace in 'text' all occurences of any key in the given
99 """ Replace in 'text' all occurences of any key in the given
100 dictionary by its corresponding value. Returns the new string."""
100 dictionary by its corresponding value. Returns the new string."""
101
101
102 # Function by Xavier Defrang, originally found at:
102 # Function by Xavier Defrang, originally found at:
103 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
103 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
104
104
105 # Create a regular expression from the dictionary keys
105 # Create a regular expression from the dictionary keys
106 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
106 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
107 # For each match, look-up corresponding value in dictionary
107 # For each match, look-up corresponding value in dictionary
108 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
108 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
109
109
110 #-----------------------------------------------------------------------------
110 #-----------------------------------------------------------------------------
111 # Special characters that can be used in prompt templates, mainly bash-like
111 # Special characters that can be used in prompt templates, mainly bash-like
112 #-----------------------------------------------------------------------------
112 #-----------------------------------------------------------------------------
113
113
114 # If $HOME isn't defined (Windows), make it an absurd string so that it can
114 # If $HOME isn't defined (Windows), make it an absurd string so that it can
115 # never be expanded out into '~'. Basically anything which can never be a
115 # never be expanded out into '~'. Basically anything which can never be a
116 # reasonable directory name will do, we just want the $HOME -> '~' operation
116 # reasonable directory name will do, we just want the $HOME -> '~' operation
117 # to become a no-op. We pre-compute $HOME here so it's not done on every
117 # to become a no-op. We pre-compute $HOME here so it's not done on every
118 # prompt call.
118 # prompt call.
119
119
120 # FIXME:
120 # FIXME:
121
121
122 # - This should be turned into a class which does proper namespace management,
122 # - This should be turned into a class which does proper namespace management,
123 # since the prompt specials need to be evaluated in a certain namespace.
123 # since the prompt specials need to be evaluated in a certain namespace.
124 # Currently it's just globals, which need to be managed manually by code
124 # Currently it's just globals, which need to be managed manually by code
125 # below.
125 # below.
126
126
127 # - I also need to split up the color schemes from the prompt specials
127 # - I also need to split up the color schemes from the prompt specials
128 # somehow. I don't have a clean design for that quite yet.
128 # somehow. I don't have a clean design for that quite yet.
129
129
130 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
130 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
131
131
132 # We precompute a few more strings here for the prompt_specials, which are
132 # We precompute a few more strings here for the prompt_specials, which are
133 # fixed once ipython starts. This reduces the runtime overhead of computing
133 # fixed once ipython starts. This reduces the runtime overhead of computing
134 # prompt strings.
134 # prompt strings.
135 USER = os.environ.get("USER")
135 USER = os.environ.get("USER")
136 HOSTNAME = socket.gethostname()
136 HOSTNAME = socket.gethostname()
137 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
137 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
138 ROOT_SYMBOL = "#" if (os.name=='nt' or os.getuid()==0) else "$"
138 ROOT_SYMBOL = "#" if (os.name=='nt' or os.getuid()==0) else "$"
139
139
140 prompt_abbreviations = {
140 prompt_abbreviations = {
141 # Prompt/history count
141 # Prompt/history count
142 '%n' : '{color.number}' '{count}' '{color.prompt}',
142 '%n' : '{color.number}' '{count}' '{color.prompt}',
143 r'\#': '{color.number}' '{count}' '{color.prompt}',
143 r'\#': '{color.number}' '{count}' '{color.prompt}',
144 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
144 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
145 # can get numbers displayed in whatever color they want.
145 # can get numbers displayed in whatever color they want.
146 r'\N': '{count}',
146 r'\N': '{count}',
147
147
148 # Prompt/history count, with the actual digits replaced by dots. Used
148 # Prompt/history count, with the actual digits replaced by dots. Used
149 # mainly in continuation prompts (prompt_in2)
149 # mainly in continuation prompts (prompt_in2)
150 r'\D': '{dots}',
150 r'\D': '{dots}',
151
151
152 # Current time
152 # Current time
153 r'\T' : '{time}',
153 r'\T' : '{time}',
154 # Current working directory
154 # Current working directory
155 r'\w': '{cwd}',
155 r'\w': '{cwd}',
156 # Basename of current working directory.
156 # Basename of current working directory.
157 # (use os.sep to make this portable across OSes)
157 # (use os.sep to make this portable across OSes)
158 r'\W' : '{cwd_last}',
158 r'\W' : '{cwd_last}',
159 # These X<N> are an extension to the normal bash prompts. They return
159 # These X<N> are an extension to the normal bash prompts. They return
160 # N terms of the path, after replacing $HOME with '~'
160 # N terms of the path, after replacing $HOME with '~'
161 r'\X0': '{cwd_x[0]}',
161 r'\X0': '{cwd_x[0]}',
162 r'\X1': '{cwd_x[1]}',
162 r'\X1': '{cwd_x[1]}',
163 r'\X2': '{cwd_x[2]}',
163 r'\X2': '{cwd_x[2]}',
164 r'\X3': '{cwd_x[3]}',
164 r'\X3': '{cwd_x[3]}',
165 r'\X4': '{cwd_x[4]}',
165 r'\X4': '{cwd_x[4]}',
166 r'\X5': '{cwd_x[5]}',
166 r'\X5': '{cwd_x[5]}',
167 # Y<N> are similar to X<N>, but they show '~' if it's the directory
167 # Y<N> are similar to X<N>, but they show '~' if it's the directory
168 # N+1 in the list. Somewhat like %cN in tcsh.
168 # N+1 in the list. Somewhat like %cN in tcsh.
169 r'\Y0': '{cwd_y[0]}',
169 r'\Y0': '{cwd_y[0]}',
170 r'\Y1': '{cwd_y[1]}',
170 r'\Y1': '{cwd_y[1]}',
171 r'\Y2': '{cwd_y[2]}',
171 r'\Y2': '{cwd_y[2]}',
172 r'\Y3': '{cwd_y[3]}',
172 r'\Y3': '{cwd_y[3]}',
173 r'\Y4': '{cwd_y[4]}',
173 r'\Y4': '{cwd_y[4]}',
174 r'\Y5': '{cwd_y[5]}',
174 r'\Y5': '{cwd_y[5]}',
175 # Hostname up to first .
175 # Hostname up to first .
176 r'\h': HOSTNAME_SHORT,
176 r'\h': HOSTNAME_SHORT,
177 # Full hostname
177 # Full hostname
178 r'\H': HOSTNAME,
178 r'\H': HOSTNAME,
179 # Username of current user
179 # Username of current user
180 r'\u': USER,
180 r'\u': USER,
181 # Escaped '\'
181 # Escaped '\'
182 '\\\\': '\\',
182 '\\\\': '\\',
183 # Newline
183 # Newline
184 r'\n': '\n',
184 r'\n': '\n',
185 # Carriage return
185 # Carriage return
186 r'\r': '\r',
186 r'\r': '\r',
187 # Release version
187 # Release version
188 r'\v': release.version,
188 r'\v': release.version,
189 # Root symbol ($ or #)
189 # Root symbol ($ or #)
190 r'\$': ROOT_SYMBOL,
190 r'\$': ROOT_SYMBOL,
191 }
191 }
192
192
193 #-----------------------------------------------------------------------------
193 #-----------------------------------------------------------------------------
194 # More utilities
194 # More utilities
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196
196
197 def cwd_filt(depth):
197 def cwd_filt(depth):
198 """Return the last depth elements of the current working directory.
198 """Return the last depth elements of the current working directory.
199
199
200 $HOME is always replaced with '~'.
200 $HOME is always replaced with '~'.
201 If depth==0, the full path is returned."""
201 If depth==0, the full path is returned."""
202
202
203 cwd = os.getcwd().replace(HOME,"~")
203 cwd = os.getcwd().replace(HOME,"~")
204 out = os.sep.join(cwd.split(os.sep)[-depth:])
204 out = os.sep.join(cwd.split(os.sep)[-depth:])
205 return out or os.sep
205 return out or os.sep
206
206
207 def cwd_filt2(depth):
207 def cwd_filt2(depth):
208 """Return the last depth elements of the current working directory.
208 """Return the last depth elements of the current working directory.
209
209
210 $HOME is always replaced with '~'.
210 $HOME is always replaced with '~'.
211 If depth==0, the full path is returned."""
211 If depth==0, the full path is returned."""
212
212
213 full_cwd = os.getcwd()
213 full_cwd = os.getcwd()
214 cwd = full_cwd.replace(HOME,"~").split(os.sep)
214 cwd = full_cwd.replace(HOME,"~").split(os.sep)
215 if '~' in cwd and len(cwd) == depth+1:
215 if '~' in cwd and len(cwd) == depth+1:
216 depth += 1
216 depth += 1
217 drivepart = ''
217 drivepart = ''
218 if sys.platform == 'win32' and len(cwd) > depth:
218 if sys.platform == 'win32' and len(cwd) > depth:
219 drivepart = os.path.splitdrive(full_cwd)[0]
219 drivepart = os.path.splitdrive(full_cwd)[0]
220 out = drivepart + '/'.join(cwd[-depth:])
220 out = drivepart + '/'.join(cwd[-depth:])
221
221
222 return out or os.sep
222 return out or os.sep
223
223
224 #-----------------------------------------------------------------------------
224 #-----------------------------------------------------------------------------
225 # Prompt classes
225 # Prompt classes
226 #-----------------------------------------------------------------------------
226 #-----------------------------------------------------------------------------
227
227
228 lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"),
228 lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"),
229 'cwd': LazyEvaluate(os.getcwd),
229 'cwd': LazyEvaluate(os.getcwd),
230 'cwd_last': LazyEvaluate(lambda: os.getcwd().split(os.sep)[-1]),
230 'cwd_last': LazyEvaluate(lambda: os.getcwd().split(os.sep)[-1]),
231 'cwd_x': [LazyEvaluate(lambda: os.getcwd().replace("%s","~"))] +\
231 'cwd_x': [LazyEvaluate(lambda: os.getcwd().replace("%s","~"))] +\
232 [LazyEvaluate(cwd_filt, x) for x in range(1,6)],
232 [LazyEvaluate(cwd_filt, x) for x in range(1,6)],
233 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)]
233 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)]
234 }
234 }
235
235
236
236
237 class PromptManager(Configurable):
237 class PromptManager(Configurable):
238 """This is the primary interface for producing IPython's prompts."""
238 """This is the primary interface for producing IPython's prompts."""
239 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
239 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
240
240
241 color_scheme_table = Instance(coloransi.ColorSchemeTable)
241 color_scheme_table = Instance(coloransi.ColorSchemeTable)
242 color_scheme = Unicode('Linux', config=True)
242 color_scheme = Unicode('Linux', config=True)
243 def _color_scheme_changed(self, name, new_value):
243 def _color_scheme_changed(self, name, new_value):
244 self.color_scheme_table.set_active_scheme(new_value)
244 self.color_scheme_table.set_active_scheme(new_value)
245 for pname in ['in', 'in2', 'out', 'rewrite']:
245 for pname in ['in', 'in2', 'out', 'rewrite']:
246 # We need to recalculate the number of invisible characters
246 # We need to recalculate the number of invisible characters
247 self.update_prompt(pname)
247 self.update_prompt(pname)
248
248
249 lazy_evaluate_fields = Dict(help="""
249 lazy_evaluate_fields = Dict(help="""
250 This maps field names used in the prompt templates to functions which
250 This maps field names used in the prompt templates to functions which
251 will be called when the prompt is rendered. This allows us to include
251 will be called when the prompt is rendered. This allows us to include
252 things like the current time in the prompts. Functions are only called
252 things like the current time in the prompts. Functions are only called
253 if they are used in the prompt.
253 if they are used in the prompt.
254 """)
254 """)
255 def _lazy_evaluate_fields_default(self): return lazily_evaluate.copy()
255 def _lazy_evaluate_fields_default(self): return lazily_evaluate.copy()
256
256
257 in_template = Unicode('In [\\#]: ', config=True)
257 in_template = Unicode('In [\\#]: ', config=True,
258 in2_template = Unicode(' .\\D.: ', config=True)
258 help="Input prompt. '\\#' will be transformed to the prompt number")
259 out_template = Unicode('Out[\\#]: ', config=True)
259 in2_template = Unicode(' .\\D.: ', config=True,
260 rewrite_template = Unicode("------> ", config=True)
260 help="Continuation prompt.")
261 out_template = Unicode('Out[\\#]: ', config=True,
262 help="Output prompt. '\\#' will be transformed to the prompt number")
263 rewrite_template = Unicode("------> ", config=True,
264 help="Rewrite prompt. When inputs are transformed, the rewritten input will follow this.")
261
265
262 justify = Bool(True, config=True, help="""
266 justify = Bool(True, config=True, help="""
263 If True (default), each prompt will be right-aligned with the
267 If True (default), each prompt will be right-aligned with the
264 preceding one.
268 preceding one.
265 """)
269 """)
266
270
267 # We actually store the expanded templates here:
271 # We actually store the expanded templates here:
268 templates = Dict()
272 templates = Dict()
269
273
270 # The number of characters in the last prompt rendered, not including
274 # The number of characters in the last prompt rendered, not including
271 # colour characters.
275 # colour characters.
272 width = Int()
276 width = Int()
273
277
274 # The number of characters in each prompt which don't contribute to width
278 # The number of characters in each prompt which don't contribute to width
275 invisible_chars = Dict()
279 invisible_chars = Dict()
276 def _invisible_chars_default(self):
280 def _invisible_chars_default(self):
277 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite': 0}
281 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite': 0}
278
282
279 def __init__(self, shell, config=None):
283 def __init__(self, shell, config=None):
280 super(PromptManager, self).__init__(shell=shell, config=config)
284 super(PromptManager, self).__init__(shell=shell, config=config)
281
285
282 # Prepare colour scheme table
286 # Prepare colour scheme table
283 self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors,
287 self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors,
284 PColLinux, PColLightBG], self.color_scheme)
288 PColLinux, PColLightBG], self.color_scheme)
285
289
286 # Prepare templates
290 # Prepare templates
287 self.update_prompt('in', self.in_template)
291 self.update_prompt('in', self.in_template)
288 self.update_prompt('in2', self.in2_template)
292 self.update_prompt('in2', self.in2_template)
289 self.update_prompt('out', self.out_template)
293 self.update_prompt('out', self.out_template)
290 self.update_prompt('rewrite', self.rewrite_template)
294 self.update_prompt('rewrite', self.rewrite_template)
291 self.on_trait_change(self._update_prompt_trait, ['in_template',
295 self.on_trait_change(self._update_prompt_trait, ['in_template',
292 'in2_template', 'out_template', 'rewrite_template'])
296 'in2_template', 'out_template', 'rewrite_template'])
293
297
294 def update_prompt(self, name, new_template=None):
298 def update_prompt(self, name, new_template=None):
295 """This is called when a prompt template is updated. It processes
299 """This is called when a prompt template is updated. It processes
296 abbreviations used in the prompt template (like \#) and calculates how
300 abbreviations used in the prompt template (like \#) and calculates how
297 many invisible characters (ANSI colour escapes) the resulting prompt
301 many invisible characters (ANSI colour escapes) the resulting prompt
298 contains.
302 contains.
299
303
300 It is also called for each prompt on changing the colour scheme. In both
304 It is also called for each prompt on changing the colour scheme. In both
301 cases, traitlets should take care of calling this automatically.
305 cases, traitlets should take care of calling this automatically.
302 """
306 """
303 if new_template is not None:
307 if new_template is not None:
304 self.templates[name] = multiple_replace(prompt_abbreviations, new_template)
308 self.templates[name] = multiple_replace(prompt_abbreviations, new_template)
305 invis_chars = len(self.render(name, color=True, just=False)) - \
309 invis_chars = len(self.render(name, color=True, just=False)) - \
306 len(self.render(name, color=False, just=False))
310 len(self.render(name, color=False, just=False))
307 self.invisible_chars[name] = invis_chars
311 self.invisible_chars[name] = invis_chars
308
312
309 def _update_prompt_trait(self, traitname, new_template):
313 def _update_prompt_trait(self, traitname, new_template):
310 name = traitname[:-9] # Cut off '_template'
314 name = traitname[:-9] # Cut off '_template'
311 self.update_prompt(name, new_template)
315 self.update_prompt(name, new_template)
312
316
313 def render(self, name, color=True, just=None, **kwargs):
317 def render(self, name, color=True, just=None, **kwargs):
314 """
318 """
315 Render the selected prompt.
319 Render the selected prompt.
316
320
317 Parameters
321 Parameters
318 ----------
322 ----------
319 name : str
323 name : str
320 Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
324 Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
321 color : bool
325 color : bool
322 If True (default), include ANSI escape sequences for a coloured prompt.
326 If True (default), include ANSI escape sequences for a coloured prompt.
323 just : bool
327 just : bool
324 If True, justify the prompt to the width of the last prompt. The
328 If True, justify the prompt to the width of the last prompt. The
325 default is stored in self.justify.
329 default is stored in self.justify.
326 **kwargs :
330 **kwargs :
327 Additional arguments will be passed to the string formatting operation,
331 Additional arguments will be passed to the string formatting operation,
328 so they can override the values that would otherwise fill in the
332 so they can override the values that would otherwise fill in the
329 template.
333 template.
330
334
331 Returns
335 Returns
332 -------
336 -------
333 A string containing the rendered prompt.
337 A string containing the rendered prompt.
334 """
338 """
335 if color:
339 if color:
336 scheme = self.color_scheme_table.active_colors
340 scheme = self.color_scheme_table.active_colors
337 if name=='out':
341 if name=='out':
338 colors = color_lists['normal']
342 colors = color_lists['normal']
339 colors.number, colors.prompt, colors.normal = \
343 colors.number, colors.prompt, colors.normal = \
340 scheme.out_number, scheme.out_prompt, scheme.normal
344 scheme.out_number, scheme.out_prompt, scheme.normal
341 elif name=='rewrite':
345 elif name=='rewrite':
342 colors = color_lists['normal']
346 colors = color_lists['normal']
343 # We need a non-input version of these escapes
347 # We need a non-input version of these escapes
344 colors.number = scheme.in_number.replace("\001","").replace("\002","")
348 colors.number = scheme.in_number.replace("\001","").replace("\002","")
345 colors.prompt = scheme.in_prompt.replace("\001","").replace("\002","")
349 colors.prompt = scheme.in_prompt.replace("\001","").replace("\002","")
346 colors.normal = scheme.normal
350 colors.normal = scheme.normal
347 else:
351 else:
348 colors = color_lists['inp']
352 colors = color_lists['inp']
349 colors.number, colors.prompt, colors.normal = \
353 colors.number, colors.prompt, colors.normal = \
350 scheme.in_number, scheme.in_prompt, scheme.in_normal
354 scheme.in_number, scheme.in_prompt, scheme.in_normal
351 if name=='in2':
355 if name=='in2':
352 colors.prompt = scheme.in_prompt2
356 colors.prompt = scheme.in_prompt2
353 else:
357 else:
354 # No color
358 # No color
355 colors = color_lists['nocolor']
359 colors = color_lists['nocolor']
356 colors.number, colors.prompt, colors.normal = '', '', ''
360 colors.number, colors.prompt, colors.normal = '', '', ''
357
361
358 count = self.shell.execution_count # Shorthand
362 count = self.shell.execution_count # Shorthand
359 # Build the dictionary to be passed to string formatting
363 # Build the dictionary to be passed to string formatting
360 fmtargs = dict(color=colors, count=count,
364 fmtargs = dict(color=colors, count=count,
361 dots="."*len(str(count)) )
365 dots="."*len(str(count)) )
362 fmtargs.update(self.lazy_evaluate_fields)
366 fmtargs.update(self.lazy_evaluate_fields)
363 fmtargs.update(kwargs)
367 fmtargs.update(kwargs)
364
368
365 # Prepare the prompt
369 # Prepare the prompt
366 prompt = colors.prompt + self.templates[name] + colors.normal
370 prompt = colors.prompt + self.templates[name] + colors.normal
367
371
368 # Fill in required fields
372 # Fill in required fields
369 res = prompt.format(**fmtargs)
373 res = prompt.format(**fmtargs)
370
374
371 # Handle justification of prompt
375 # Handle justification of prompt
372 invis_chars = self.invisible_chars[name] if color else 0
376 invis_chars = self.invisible_chars[name] if color else 0
373 just = self.justify if (just is None) else just
377 just = self.justify if (just is None) else just
374 if just:
378 if just:
375 res = res.rjust(self.width + invis_chars)
379 res = res.rjust(self.width + invis_chars)
376 self.width = len(res) - invis_chars
380 self.width = len(res) - invis_chars
377 return res
381 return res
378
382
@@ -1,397 +1,399 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 * Min Ragan-Kelley
12 * Min Ragan-Kelley
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2011 The IPython Development Team
16 # Copyright (C) 2008-2011 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import absolute_import
26 from __future__ import absolute_import
27
27
28 import logging
28 import logging
29 import os
29 import os
30 import sys
30 import sys
31
31
32 from IPython.config.loader import (
32 from IPython.config.loader import (
33 Config, PyFileConfigLoader, ConfigFileNotFound
33 Config, PyFileConfigLoader, ConfigFileNotFound
34 )
34 )
35 from IPython.config.application import boolean_flag, catch_config_error
35 from IPython.config.application import boolean_flag, catch_config_error
36 from IPython.core import release
36 from IPython.core import release
37 from IPython.core import usage
37 from IPython.core import usage
38 from IPython.core.completer import IPCompleter
38 from IPython.core.completer import IPCompleter
39 from IPython.core.crashhandler import CrashHandler
39 from IPython.core.crashhandler import CrashHandler
40 from IPython.core.formatters import PlainTextFormatter
40 from IPython.core.formatters import PlainTextFormatter
41 from IPython.core.prompts import PromptManager
41 from IPython.core.application import (
42 from IPython.core.application import (
42 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
43 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
43 )
44 )
44 from IPython.core.shellapp import (
45 from IPython.core.shellapp import (
45 InteractiveShellApp, shell_flags, shell_aliases
46 InteractiveShellApp, shell_flags, shell_aliases
46 )
47 )
47 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
48 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
48 from IPython.lib import inputhook
49 from IPython.lib import inputhook
49 from IPython.utils import warn
50 from IPython.utils import warn
50 from IPython.utils.path import get_ipython_dir, check_for_old_config
51 from IPython.utils.path import get_ipython_dir, check_for_old_config
51 from IPython.utils.traitlets import (
52 from IPython.utils.traitlets import (
52 Bool, List, Dict, CaselessStrEnum
53 Bool, List, Dict, CaselessStrEnum
53 )
54 )
54
55
55 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
56 # Globals, utilities and helpers
57 # Globals, utilities and helpers
57 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
58
59
59 #: The default config file name for this application.
60 #: The default config file name for this application.
60 default_config_file_name = u'ipython_config.py'
61 default_config_file_name = u'ipython_config.py'
61
62
62 _examples = """
63 _examples = """
63 ipython --pylab # start in pylab mode
64 ipython --pylab # start in pylab mode
64 ipython --pylab=qt # start in pylab mode with the qt4 backend
65 ipython --pylab=qt # start in pylab mode with the qt4 backend
65 ipython --log-level=DEBUG # set logging to DEBUG
66 ipython --log-level=DEBUG # set logging to DEBUG
66 ipython --profile=foo # start with profile foo
67 ipython --profile=foo # start with profile foo
67
68
68 ipython qtconsole # start the qtconsole GUI application
69 ipython qtconsole # start the qtconsole GUI application
69 ipython qtconsole -h # show the help string for the qtconsole subcmd
70 ipython qtconsole -h # show the help string for the qtconsole subcmd
70
71
71 ipython profile create foo # create profile foo w/ default config files
72 ipython profile create foo # create profile foo w/ default config files
72 ipython profile -h # show the help string for the profile subcmd
73 ipython profile -h # show the help string for the profile subcmd
73 """
74 """
74
75
75 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
76 # Crash handler for this application
77 # Crash handler for this application
77 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
78
79
79 class IPAppCrashHandler(CrashHandler):
80 class IPAppCrashHandler(CrashHandler):
80 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
81 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
81
82
82 def __init__(self, app):
83 def __init__(self, app):
83 contact_name = release.authors['Fernando'][0]
84 contact_name = release.authors['Fernando'][0]
84 contact_email = release.author_email
85 contact_email = release.author_email
85 bug_tracker = 'https://github.com/ipython/ipython/issues'
86 bug_tracker = 'https://github.com/ipython/ipython/issues'
86 super(IPAppCrashHandler,self).__init__(
87 super(IPAppCrashHandler,self).__init__(
87 app, contact_name, contact_email, bug_tracker
88 app, contact_name, contact_email, bug_tracker
88 )
89 )
89
90
90 def make_report(self,traceback):
91 def make_report(self,traceback):
91 """Return a string containing a crash report."""
92 """Return a string containing a crash report."""
92
93
93 sec_sep = self.section_sep
94 sec_sep = self.section_sep
94 # Start with parent report
95 # Start with parent report
95 report = [super(IPAppCrashHandler, self).make_report(traceback)]
96 report = [super(IPAppCrashHandler, self).make_report(traceback)]
96 # Add interactive-specific info we may have
97 # Add interactive-specific info we may have
97 rpt_add = report.append
98 rpt_add = report.append
98 try:
99 try:
99 rpt_add(sec_sep+"History of session input:")
100 rpt_add(sec_sep+"History of session input:")
100 for line in self.app.shell.user_ns['_ih']:
101 for line in self.app.shell.user_ns['_ih']:
101 rpt_add(line)
102 rpt_add(line)
102 rpt_add('\n*** Last line of input (may not be in above history):\n')
103 rpt_add('\n*** Last line of input (may not be in above history):\n')
103 rpt_add(self.app.shell._last_input_line+'\n')
104 rpt_add(self.app.shell._last_input_line+'\n')
104 except:
105 except:
105 pass
106 pass
106
107
107 return ''.join(report)
108 return ''.join(report)
108
109
109 #-----------------------------------------------------------------------------
110 #-----------------------------------------------------------------------------
110 # Aliases and Flags
111 # Aliases and Flags
111 #-----------------------------------------------------------------------------
112 #-----------------------------------------------------------------------------
112 flags = dict(base_flags)
113 flags = dict(base_flags)
113 flags.update(shell_flags)
114 flags.update(shell_flags)
114 addflag = lambda *args: flags.update(boolean_flag(*args))
115 addflag = lambda *args: flags.update(boolean_flag(*args))
115 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
116 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
116 'Turn on auto editing of files with syntax errors.',
117 'Turn on auto editing of files with syntax errors.',
117 'Turn off auto editing of files with syntax errors.'
118 'Turn off auto editing of files with syntax errors.'
118 )
119 )
119 addflag('banner', 'TerminalIPythonApp.display_banner',
120 addflag('banner', 'TerminalIPythonApp.display_banner',
120 "Display a banner upon starting IPython.",
121 "Display a banner upon starting IPython.",
121 "Don't display a banner upon starting IPython."
122 "Don't display a banner upon starting IPython."
122 )
123 )
123 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
124 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
124 """Set to confirm when you try to exit IPython with an EOF (Control-D
125 """Set to confirm when you try to exit IPython with an EOF (Control-D
125 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
126 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
126 you can force a direct exit without any confirmation.""",
127 you can force a direct exit without any confirmation.""",
127 "Don't prompt the user when exiting."
128 "Don't prompt the user when exiting."
128 )
129 )
129 addflag('term-title', 'TerminalInteractiveShell.term_title',
130 addflag('term-title', 'TerminalInteractiveShell.term_title',
130 "Enable auto setting the terminal title.",
131 "Enable auto setting the terminal title.",
131 "Disable auto setting the terminal title."
132 "Disable auto setting the terminal title."
132 )
133 )
133 classic_config = Config()
134 classic_config = Config()
134 classic_config.InteractiveShell.cache_size = 0
135 classic_config.InteractiveShell.cache_size = 0
135 classic_config.PlainTextFormatter.pprint = False
136 classic_config.PlainTextFormatter.pprint = False
136 classic_config.InteractiveShell.prompt_in1 = '>>> '
137 classic_config.PromptManager.in_template = '>>> '
137 classic_config.InteractiveShell.prompt_in2 = '... '
138 classic_config.PromptManager.in2_template = '... '
138 classic_config.InteractiveShell.prompt_out = ''
139 classic_config.PromptManager.out_template = ''
139 classic_config.InteractiveShell.separate_in = ''
140 classic_config.InteractiveShell.separate_in = ''
140 classic_config.InteractiveShell.separate_out = ''
141 classic_config.InteractiveShell.separate_out = ''
141 classic_config.InteractiveShell.separate_out2 = ''
142 classic_config.InteractiveShell.separate_out2 = ''
142 classic_config.InteractiveShell.colors = 'NoColor'
143 classic_config.InteractiveShell.colors = 'NoColor'
143 classic_config.InteractiveShell.xmode = 'Plain'
144 classic_config.InteractiveShell.xmode = 'Plain'
144
145
145 flags['classic']=(
146 flags['classic']=(
146 classic_config,
147 classic_config,
147 "Gives IPython a similar feel to the classic Python prompt."
148 "Gives IPython a similar feel to the classic Python prompt."
148 )
149 )
149 # # log doesn't make so much sense this way anymore
150 # # log doesn't make so much sense this way anymore
150 # paa('--log','-l',
151 # paa('--log','-l',
151 # action='store_true', dest='InteractiveShell.logstart',
152 # action='store_true', dest='InteractiveShell.logstart',
152 # help="Start logging to the default log file (./ipython_log.py).")
153 # help="Start logging to the default log file (./ipython_log.py).")
153 #
154 #
154 # # quick is harder to implement
155 # # quick is harder to implement
155 flags['quick']=(
156 flags['quick']=(
156 {'TerminalIPythonApp' : {'quick' : True}},
157 {'TerminalIPythonApp' : {'quick' : True}},
157 "Enable quick startup with no config files."
158 "Enable quick startup with no config files."
158 )
159 )
159
160
160 flags['i'] = (
161 flags['i'] = (
161 {'TerminalIPythonApp' : {'force_interact' : True}},
162 {'TerminalIPythonApp' : {'force_interact' : True}},
162 """If running code from the command line, become interactive afterwards.
163 """If running code from the command line, become interactive afterwards.
163 Note: can also be given simply as '-i.'"""
164 Note: can also be given simply as '-i.'"""
164 )
165 )
165 flags['pylab'] = (
166 flags['pylab'] = (
166 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
167 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
167 """Pre-load matplotlib and numpy for interactive use with
168 """Pre-load matplotlib and numpy for interactive use with
168 the default matplotlib backend."""
169 the default matplotlib backend."""
169 )
170 )
170
171
171 aliases = dict(base_aliases)
172 aliases = dict(base_aliases)
172 aliases.update(shell_aliases)
173 aliases.update(shell_aliases)
173
174
174 # it's possible we don't want short aliases for *all* of these:
175 # it's possible we don't want short aliases for *all* of these:
175 aliases.update(dict(
176 aliases.update(dict(
176 gui='TerminalIPythonApp.gui',
177 gui='TerminalIPythonApp.gui',
177 pylab='TerminalIPythonApp.pylab',
178 pylab='TerminalIPythonApp.pylab',
178 ))
179 ))
179
180
180 #-----------------------------------------------------------------------------
181 #-----------------------------------------------------------------------------
181 # Main classes and functions
182 # Main classes and functions
182 #-----------------------------------------------------------------------------
183 #-----------------------------------------------------------------------------
183
184
184 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
185 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
185 name = u'ipython'
186 name = u'ipython'
186 description = usage.cl_usage
187 description = usage.cl_usage
187 default_config_file_name = default_config_file_name
188 default_config_file_name = default_config_file_name
188 crash_handler_class = IPAppCrashHandler
189 crash_handler_class = IPAppCrashHandler
189 examples = _examples
190 examples = _examples
190
191
191 flags = Dict(flags)
192 flags = Dict(flags)
192 aliases = Dict(aliases)
193 aliases = Dict(aliases)
193 classes = List()
194 classes = List()
194 def _classes_default(self):
195 def _classes_default(self):
195 """This has to be in a method, for TerminalIPythonApp to be available."""
196 """This has to be in a method, for TerminalIPythonApp to be available."""
196 return [
197 return [
197 InteractiveShellApp, # ShellApp comes before TerminalApp, because
198 InteractiveShellApp, # ShellApp comes before TerminalApp, because
198 self.__class__, # it will also affect subclasses (e.g. QtConsole)
199 self.__class__, # it will also affect subclasses (e.g. QtConsole)
199 TerminalInteractiveShell,
200 TerminalInteractiveShell,
201 PromptManager,
200 ProfileDir,
202 ProfileDir,
201 PlainTextFormatter,
203 PlainTextFormatter,
202 IPCompleter,
204 IPCompleter,
203 ]
205 ]
204
206
205 subcommands = Dict(dict(
207 subcommands = Dict(dict(
206 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
208 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
207 """Launch the IPython Qt Console."""
209 """Launch the IPython Qt Console."""
208 ),
210 ),
209 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
211 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
210 """Launch the IPython HTML Notebook Server"""
212 """Launch the IPython HTML Notebook Server"""
211 ),
213 ),
212 profile = ("IPython.core.profileapp.ProfileApp",
214 profile = ("IPython.core.profileapp.ProfileApp",
213 "Create and manage IPython profiles."
215 "Create and manage IPython profiles."
214 ),
216 ),
215 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
217 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
216 "Start a kernel without an attached frontend."
218 "Start a kernel without an attached frontend."
217 ),
219 ),
218 ))
220 ))
219
221
220 # *do* autocreate requested profile, but don't create the config file.
222 # *do* autocreate requested profile, but don't create the config file.
221 auto_create=Bool(True)
223 auto_create=Bool(True)
222 # configurables
224 # configurables
223 ignore_old_config=Bool(False, config=True,
225 ignore_old_config=Bool(False, config=True,
224 help="Suppress warning messages about legacy config files"
226 help="Suppress warning messages about legacy config files"
225 )
227 )
226 quick = Bool(False, config=True,
228 quick = Bool(False, config=True,
227 help="""Start IPython quickly by skipping the loading of config files."""
229 help="""Start IPython quickly by skipping the loading of config files."""
228 )
230 )
229 def _quick_changed(self, name, old, new):
231 def _quick_changed(self, name, old, new):
230 if new:
232 if new:
231 self.load_config_file = lambda *a, **kw: None
233 self.load_config_file = lambda *a, **kw: None
232 self.ignore_old_config=True
234 self.ignore_old_config=True
233
235
234 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet'), config=True,
236 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet'), config=True,
235 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet')."
237 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet')."
236 )
238 )
237 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
239 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
238 config=True,
240 config=True,
239 help="""Pre-load matplotlib and numpy for interactive use,
241 help="""Pre-load matplotlib and numpy for interactive use,
240 selecting a particular matplotlib backend and loop integration.
242 selecting a particular matplotlib backend and loop integration.
241 """
243 """
242 )
244 )
243 display_banner = Bool(True, config=True,
245 display_banner = Bool(True, config=True,
244 help="Whether to display a banner upon starting IPython."
246 help="Whether to display a banner upon starting IPython."
245 )
247 )
246
248
247 # if there is code of files to run from the cmd line, don't interact
249 # if there is code of files to run from the cmd line, don't interact
248 # unless the --i flag (App.force_interact) is true.
250 # unless the --i flag (App.force_interact) is true.
249 force_interact = Bool(False, config=True,
251 force_interact = Bool(False, config=True,
250 help="""If a command or file is given via the command-line,
252 help="""If a command or file is given via the command-line,
251 e.g. 'ipython foo.py"""
253 e.g. 'ipython foo.py"""
252 )
254 )
253 def _force_interact_changed(self, name, old, new):
255 def _force_interact_changed(self, name, old, new):
254 if new:
256 if new:
255 self.interact = True
257 self.interact = True
256
258
257 def _file_to_run_changed(self, name, old, new):
259 def _file_to_run_changed(self, name, old, new):
258 if new and not self.force_interact:
260 if new and not self.force_interact:
259 self.interact = False
261 self.interact = False
260 _code_to_run_changed = _file_to_run_changed
262 _code_to_run_changed = _file_to_run_changed
261
263
262 # internal, not-configurable
264 # internal, not-configurable
263 interact=Bool(True)
265 interact=Bool(True)
264
266
265
267
266 def parse_command_line(self, argv=None):
268 def parse_command_line(self, argv=None):
267 """override to allow old '-pylab' flag with deprecation warning"""
269 """override to allow old '-pylab' flag with deprecation warning"""
268
270
269 argv = sys.argv[1:] if argv is None else argv
271 argv = sys.argv[1:] if argv is None else argv
270
272
271 if '-pylab' in argv:
273 if '-pylab' in argv:
272 # deprecated `-pylab` given,
274 # deprecated `-pylab` given,
273 # warn and transform into current syntax
275 # warn and transform into current syntax
274 argv = argv[:] # copy, don't clobber
276 argv = argv[:] # copy, don't clobber
275 idx = argv.index('-pylab')
277 idx = argv.index('-pylab')
276 warn.warn("`-pylab` flag has been deprecated.\n"
278 warn.warn("`-pylab` flag has been deprecated.\n"
277 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
279 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
278 sub = '--pylab'
280 sub = '--pylab'
279 if len(argv) > idx+1:
281 if len(argv) > idx+1:
280 # check for gui arg, as in '-pylab qt'
282 # check for gui arg, as in '-pylab qt'
281 gui = argv[idx+1]
283 gui = argv[idx+1]
282 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
284 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
283 sub = '--pylab='+gui
285 sub = '--pylab='+gui
284 argv.pop(idx+1)
286 argv.pop(idx+1)
285 argv[idx] = sub
287 argv[idx] = sub
286
288
287 return super(TerminalIPythonApp, self).parse_command_line(argv)
289 return super(TerminalIPythonApp, self).parse_command_line(argv)
288
290
289 @catch_config_error
291 @catch_config_error
290 def initialize(self, argv=None):
292 def initialize(self, argv=None):
291 """Do actions after construct, but before starting the app."""
293 """Do actions after construct, but before starting the app."""
292 super(TerminalIPythonApp, self).initialize(argv)
294 super(TerminalIPythonApp, self).initialize(argv)
293 if self.subapp is not None:
295 if self.subapp is not None:
294 # don't bother initializing further, starting subapp
296 # don't bother initializing further, starting subapp
295 return
297 return
296 if not self.ignore_old_config:
298 if not self.ignore_old_config:
297 check_for_old_config(self.ipython_dir)
299 check_for_old_config(self.ipython_dir)
298 # print self.extra_args
300 # print self.extra_args
299 if self.extra_args:
301 if self.extra_args:
300 self.file_to_run = self.extra_args[0]
302 self.file_to_run = self.extra_args[0]
301 # create the shell
303 # create the shell
302 self.init_shell()
304 self.init_shell()
303 # and draw the banner
305 # and draw the banner
304 self.init_banner()
306 self.init_banner()
305 # Now a variety of things that happen after the banner is printed.
307 # Now a variety of things that happen after the banner is printed.
306 self.init_gui_pylab()
308 self.init_gui_pylab()
307 self.init_extensions()
309 self.init_extensions()
308 self.init_code()
310 self.init_code()
309
311
310 def init_shell(self):
312 def init_shell(self):
311 """initialize the InteractiveShell instance"""
313 """initialize the InteractiveShell instance"""
312 # I am a little hesitant to put these into InteractiveShell itself.
314 # I am a little hesitant to put these into InteractiveShell itself.
313 # But that might be the place for them
315 # But that might be the place for them
314 sys.path.insert(0, '')
316 sys.path.insert(0, '')
315
317
316 # Create an InteractiveShell instance.
318 # Create an InteractiveShell instance.
317 # shell.display_banner should always be False for the terminal
319 # shell.display_banner should always be False for the terminal
318 # based app, because we call shell.show_banner() by hand below
320 # based app, because we call shell.show_banner() by hand below
319 # so the banner shows *before* all extension loading stuff.
321 # so the banner shows *before* all extension loading stuff.
320 self.shell = TerminalInteractiveShell.instance(config=self.config,
322 self.shell = TerminalInteractiveShell.instance(config=self.config,
321 display_banner=False, profile_dir=self.profile_dir,
323 display_banner=False, profile_dir=self.profile_dir,
322 ipython_dir=self.ipython_dir)
324 ipython_dir=self.ipython_dir)
323 self.shell.configurables.append(self)
325 self.shell.configurables.append(self)
324
326
325 def init_banner(self):
327 def init_banner(self):
326 """optionally display the banner"""
328 """optionally display the banner"""
327 if self.display_banner and self.interact:
329 if self.display_banner and self.interact:
328 self.shell.show_banner()
330 self.shell.show_banner()
329 # Make sure there is a space below the banner.
331 # Make sure there is a space below the banner.
330 if self.log_level <= logging.INFO: print
332 if self.log_level <= logging.INFO: print
331
333
332
334
333 def init_gui_pylab(self):
335 def init_gui_pylab(self):
334 """Enable GUI event loop integration, taking pylab into account."""
336 """Enable GUI event loop integration, taking pylab into account."""
335 gui = self.gui
337 gui = self.gui
336
338
337 # Using `pylab` will also require gui activation, though which toolkit
339 # Using `pylab` will also require gui activation, though which toolkit
338 # to use may be chosen automatically based on mpl configuration.
340 # to use may be chosen automatically based on mpl configuration.
339 if self.pylab:
341 if self.pylab:
340 activate = self.shell.enable_pylab
342 activate = self.shell.enable_pylab
341 if self.pylab == 'auto':
343 if self.pylab == 'auto':
342 gui = None
344 gui = None
343 else:
345 else:
344 gui = self.pylab
346 gui = self.pylab
345 else:
347 else:
346 # Enable only GUI integration, no pylab
348 # Enable only GUI integration, no pylab
347 activate = inputhook.enable_gui
349 activate = inputhook.enable_gui
348
350
349 if gui or self.pylab:
351 if gui or self.pylab:
350 try:
352 try:
351 self.log.info("Enabling GUI event loop integration, "
353 self.log.info("Enabling GUI event loop integration, "
352 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
354 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
353 if self.pylab:
355 if self.pylab:
354 activate(gui, import_all=self.pylab_import_all)
356 activate(gui, import_all=self.pylab_import_all)
355 else:
357 else:
356 activate(gui)
358 activate(gui)
357 except:
359 except:
358 self.log.warn("Error in enabling GUI event loop integration:")
360 self.log.warn("Error in enabling GUI event loop integration:")
359 self.shell.showtraceback()
361 self.shell.showtraceback()
360
362
361 def start(self):
363 def start(self):
362 if self.subapp is not None:
364 if self.subapp is not None:
363 return self.subapp.start()
365 return self.subapp.start()
364 # perform any prexec steps:
366 # perform any prexec steps:
365 if self.interact:
367 if self.interact:
366 self.log.debug("Starting IPython's mainloop...")
368 self.log.debug("Starting IPython's mainloop...")
367 self.shell.mainloop()
369 self.shell.mainloop()
368 else:
370 else:
369 self.log.debug("IPython not interactive...")
371 self.log.debug("IPython not interactive...")
370
372
371
373
372 def load_default_config(ipython_dir=None):
374 def load_default_config(ipython_dir=None):
373 """Load the default config file from the default ipython_dir.
375 """Load the default config file from the default ipython_dir.
374
376
375 This is useful for embedded shells.
377 This is useful for embedded shells.
376 """
378 """
377 if ipython_dir is None:
379 if ipython_dir is None:
378 ipython_dir = get_ipython_dir()
380 ipython_dir = get_ipython_dir()
379 profile_dir = os.path.join(ipython_dir, 'profile_default')
381 profile_dir = os.path.join(ipython_dir, 'profile_default')
380 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
382 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
381 try:
383 try:
382 config = cl.load_config()
384 config = cl.load_config()
383 except ConfigFileNotFound:
385 except ConfigFileNotFound:
384 # no config found
386 # no config found
385 config = Config()
387 config = Config()
386 return config
388 return config
387
389
388
390
389 def launch_new_instance():
391 def launch_new_instance():
390 """Create and run a full blown IPython instance"""
392 """Create and run a full blown IPython instance"""
391 app = TerminalIPythonApp.instance()
393 app = TerminalIPythonApp.instance()
392 app.initialize()
394 app.initialize()
393 app.start()
395 app.start()
394
396
395
397
396 if __name__ == '__main__':
398 if __name__ == '__main__':
397 launch_new_instance()
399 launch_new_instance()
@@ -1,402 +1,402 b''
1 """Generic testing tools that do NOT depend on Twisted.
1 """Generic testing tools that do NOT depend on Twisted.
2
2
3 In particular, this module exposes a set of top-level assert* functions that
3 In particular, this module exposes a set of top-level assert* functions that
4 can be used in place of nose.tools.assert* in method generators (the ones in
4 can be used in place of nose.tools.assert* in method generators (the ones in
5 nose can not, at least as of nose 0.10.4).
5 nose can not, at least as of nose 0.10.4).
6
6
7 Note: our testing package contains testing.util, which does depend on Twisted
7 Note: our testing package contains testing.util, which does depend on Twisted
8 and provides utilities for tests that manage Deferreds. All testing support
8 and provides utilities for tests that manage Deferreds. All testing support
9 tools that only depend on nose, IPython or the standard library should go here
9 tools that only depend on nose, IPython or the standard library should go here
10 instead.
10 instead.
11
11
12
12
13 Authors
13 Authors
14 -------
14 -------
15 - Fernando Perez <Fernando.Perez@berkeley.edu>
15 - Fernando Perez <Fernando.Perez@berkeley.edu>
16 """
16 """
17
17
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Copyright (C) 2009-2011 The IPython Development Team
21 # Copyright (C) 2009-2011 The IPython Development Team
22 #
22 #
23 # Distributed under the terms of the BSD License. The full license is in
23 # Distributed under the terms of the BSD License. The full license is in
24 # the file COPYING, distributed as part of this software.
24 # the file COPYING, distributed as part of this software.
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Imports
28 # Imports
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 import os
31 import os
32 import re
32 import re
33 import sys
33 import sys
34 import tempfile
34 import tempfile
35
35
36 from contextlib import contextmanager
36 from contextlib import contextmanager
37 from io import StringIO
37 from io import StringIO
38
38
39 try:
39 try:
40 # These tools are used by parts of the runtime, so we make the nose
40 # These tools are used by parts of the runtime, so we make the nose
41 # dependency optional at this point. Nose is a hard dependency to run the
41 # dependency optional at this point. Nose is a hard dependency to run the
42 # test suite, but NOT to use ipython itself.
42 # test suite, but NOT to use ipython itself.
43 import nose.tools as nt
43 import nose.tools as nt
44 has_nose = True
44 has_nose = True
45 except ImportError:
45 except ImportError:
46 has_nose = False
46 has_nose = False
47
47
48 from IPython.config.loader import Config
48 from IPython.config.loader import Config
49 from IPython.utils.process import find_cmd, getoutputerror
49 from IPython.utils.process import find_cmd, getoutputerror
50 from IPython.utils.text import list_strings, getdefaultencoding
50 from IPython.utils.text import list_strings, getdefaultencoding
51 from IPython.utils.io import temp_pyfile, Tee
51 from IPython.utils.io import temp_pyfile, Tee
52 from IPython.utils import py3compat
52 from IPython.utils import py3compat
53
53
54 from . import decorators as dec
54 from . import decorators as dec
55 from . import skipdoctest
55 from . import skipdoctest
56
56
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 # Globals
58 # Globals
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60
60
61 # Make a bunch of nose.tools assert wrappers that can be used in test
61 # Make a bunch of nose.tools assert wrappers that can be used in test
62 # generators. This will expose an assert* function for each one in nose.tools.
62 # generators. This will expose an assert* function for each one in nose.tools.
63
63
64 _tpl = """
64 _tpl = """
65 def %(name)s(*a,**kw):
65 def %(name)s(*a,**kw):
66 return nt.%(name)s(*a,**kw)
66 return nt.%(name)s(*a,**kw)
67 """
67 """
68
68
69 if has_nose:
69 if has_nose:
70 for _x in [a for a in dir(nt) if a.startswith('assert')]:
70 for _x in [a for a in dir(nt) if a.startswith('assert')]:
71 exec _tpl % dict(name=_x)
71 exec _tpl % dict(name=_x)
72
72
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74 # Functions and classes
74 # Functions and classes
75 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
76
76
77 # The docstring for full_path doctests differently on win32 (different path
77 # The docstring for full_path doctests differently on win32 (different path
78 # separator) so just skip the doctest there. The example remains informative.
78 # separator) so just skip the doctest there. The example remains informative.
79 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
79 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
80
80
81 @doctest_deco
81 @doctest_deco
82 def full_path(startPath,files):
82 def full_path(startPath,files):
83 """Make full paths for all the listed files, based on startPath.
83 """Make full paths for all the listed files, based on startPath.
84
84
85 Only the base part of startPath is kept, since this routine is typically
85 Only the base part of startPath is kept, since this routine is typically
86 used with a script's __file__ variable as startPath. The base of startPath
86 used with a script's __file__ variable as startPath. The base of startPath
87 is then prepended to all the listed files, forming the output list.
87 is then prepended to all the listed files, forming the output list.
88
88
89 Parameters
89 Parameters
90 ----------
90 ----------
91 startPath : string
91 startPath : string
92 Initial path to use as the base for the results. This path is split
92 Initial path to use as the base for the results. This path is split
93 using os.path.split() and only its first component is kept.
93 using os.path.split() and only its first component is kept.
94
94
95 files : string or list
95 files : string or list
96 One or more files.
96 One or more files.
97
97
98 Examples
98 Examples
99 --------
99 --------
100
100
101 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
101 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
102 ['/foo/a.txt', '/foo/b.txt']
102 ['/foo/a.txt', '/foo/b.txt']
103
103
104 >>> full_path('/foo',['a.txt','b.txt'])
104 >>> full_path('/foo',['a.txt','b.txt'])
105 ['/a.txt', '/b.txt']
105 ['/a.txt', '/b.txt']
106
106
107 If a single file is given, the output is still a list:
107 If a single file is given, the output is still a list:
108 >>> full_path('/foo','a.txt')
108 >>> full_path('/foo','a.txt')
109 ['/a.txt']
109 ['/a.txt']
110 """
110 """
111
111
112 files = list_strings(files)
112 files = list_strings(files)
113 base = os.path.split(startPath)[0]
113 base = os.path.split(startPath)[0]
114 return [ os.path.join(base,f) for f in files ]
114 return [ os.path.join(base,f) for f in files ]
115
115
116
116
117 def parse_test_output(txt):
117 def parse_test_output(txt):
118 """Parse the output of a test run and return errors, failures.
118 """Parse the output of a test run and return errors, failures.
119
119
120 Parameters
120 Parameters
121 ----------
121 ----------
122 txt : str
122 txt : str
123 Text output of a test run, assumed to contain a line of one of the
123 Text output of a test run, assumed to contain a line of one of the
124 following forms::
124 following forms::
125 'FAILED (errors=1)'
125 'FAILED (errors=1)'
126 'FAILED (failures=1)'
126 'FAILED (failures=1)'
127 'FAILED (errors=1, failures=1)'
127 'FAILED (errors=1, failures=1)'
128
128
129 Returns
129 Returns
130 -------
130 -------
131 nerr, nfail: number of errors and failures.
131 nerr, nfail: number of errors and failures.
132 """
132 """
133
133
134 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
134 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
135 if err_m:
135 if err_m:
136 nerr = int(err_m.group(1))
136 nerr = int(err_m.group(1))
137 nfail = 0
137 nfail = 0
138 return nerr, nfail
138 return nerr, nfail
139
139
140 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
140 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
141 if fail_m:
141 if fail_m:
142 nerr = 0
142 nerr = 0
143 nfail = int(fail_m.group(1))
143 nfail = int(fail_m.group(1))
144 return nerr, nfail
144 return nerr, nfail
145
145
146 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
146 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
147 re.MULTILINE)
147 re.MULTILINE)
148 if both_m:
148 if both_m:
149 nerr = int(both_m.group(1))
149 nerr = int(both_m.group(1))
150 nfail = int(both_m.group(2))
150 nfail = int(both_m.group(2))
151 return nerr, nfail
151 return nerr, nfail
152
152
153 # If the input didn't match any of these forms, assume no error/failures
153 # If the input didn't match any of these forms, assume no error/failures
154 return 0, 0
154 return 0, 0
155
155
156
156
157 # So nose doesn't think this is a test
157 # So nose doesn't think this is a test
158 parse_test_output.__test__ = False
158 parse_test_output.__test__ = False
159
159
160
160
161 def default_argv():
161 def default_argv():
162 """Return a valid default argv for creating testing instances of ipython"""
162 """Return a valid default argv for creating testing instances of ipython"""
163
163
164 return ['--quick', # so no config file is loaded
164 return ['--quick', # so no config file is loaded
165 # Other defaults to minimize side effects on stdout
165 # Other defaults to minimize side effects on stdout
166 '--colors=NoColor', '--no-term-title','--no-banner',
166 '--colors=NoColor', '--no-term-title','--no-banner',
167 '--autocall=0']
167 '--autocall=0']
168
168
169
169
170 def default_config():
170 def default_config():
171 """Return a config object with good defaults for testing."""
171 """Return a config object with good defaults for testing."""
172 config = Config()
172 config = Config()
173 config.TerminalInteractiveShell.colors = 'NoColor'
173 config.TerminalInteractiveShell.colors = 'NoColor'
174 config.TerminalTerminalInteractiveShell.term_title = False,
174 config.TerminalTerminalInteractiveShell.term_title = False,
175 config.TerminalInteractiveShell.autocall = 0
175 config.TerminalInteractiveShell.autocall = 0
176 config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite')
176 config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite')
177 config.HistoryManager.db_cache_size = 10000
177 config.HistoryManager.db_cache_size = 10000
178 return config
178 return config
179
179
180
180
181 def ipexec(fname, options=None):
181 def ipexec(fname, options=None):
182 """Utility to call 'ipython filename'.
182 """Utility to call 'ipython filename'.
183
183
184 Starts IPython witha minimal and safe configuration to make startup as fast
184 Starts IPython witha minimal and safe configuration to make startup as fast
185 as possible.
185 as possible.
186
186
187 Note that this starts IPython in a subprocess!
187 Note that this starts IPython in a subprocess!
188
188
189 Parameters
189 Parameters
190 ----------
190 ----------
191 fname : str
191 fname : str
192 Name of file to be executed (should have .py or .ipy extension).
192 Name of file to be executed (should have .py or .ipy extension).
193
193
194 options : optional, list
194 options : optional, list
195 Extra command-line flags to be passed to IPython.
195 Extra command-line flags to be passed to IPython.
196
196
197 Returns
197 Returns
198 -------
198 -------
199 (stdout, stderr) of ipython subprocess.
199 (stdout, stderr) of ipython subprocess.
200 """
200 """
201 if options is None: options = []
201 if options is None: options = []
202
202
203 # For these subprocess calls, eliminate all prompt printing so we only see
203 # For these subprocess calls, eliminate all prompt printing so we only see
204 # output from script execution
204 # output from script execution
205 prompt_opts = [ '--InteractiveShell.prompt_in1=""',
205 prompt_opts = [ '--PromptManager.in_template=""',
206 '--InteractiveShell.prompt_in2=""',
206 '--PromptManager.in2_template=""',
207 '--InteractiveShell.prompt_out=""'
207 '--PromptManager.out_template=""'
208 ]
208 ]
209 cmdargs = ' '.join(default_argv() + prompt_opts + options)
209 cmdargs = ' '.join(default_argv() + prompt_opts + options)
210
210
211 _ip = get_ipython()
211 _ip = get_ipython()
212 test_dir = os.path.dirname(__file__)
212 test_dir = os.path.dirname(__file__)
213
213
214 ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython')
214 ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython')
215 # Absolute path for filename
215 # Absolute path for filename
216 full_fname = os.path.join(test_dir, fname)
216 full_fname = os.path.join(test_dir, fname)
217 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
217 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
218 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
218 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
219 out = getoutputerror(full_cmd)
219 out = getoutputerror(full_cmd)
220 # `import readline` causes 'ESC[?1034h' to be the first output sometimes,
220 # `import readline` causes 'ESC[?1034h' to be the first output sometimes,
221 # so strip that off the front of the first line if it is found
221 # so strip that off the front of the first line if it is found
222 if out:
222 if out:
223 first = out[0]
223 first = out[0]
224 m = re.match(r'\x1b\[[^h]+h', first)
224 m = re.match(r'\x1b\[[^h]+h', first)
225 if m:
225 if m:
226 # strip initial readline escape
226 # strip initial readline escape
227 out = list(out)
227 out = list(out)
228 out[0] = first[len(m.group()):]
228 out[0] = first[len(m.group()):]
229 out = tuple(out)
229 out = tuple(out)
230 return out
230 return out
231
231
232
232
233 def ipexec_validate(fname, expected_out, expected_err='',
233 def ipexec_validate(fname, expected_out, expected_err='',
234 options=None):
234 options=None):
235 """Utility to call 'ipython filename' and validate output/error.
235 """Utility to call 'ipython filename' and validate output/error.
236
236
237 This function raises an AssertionError if the validation fails.
237 This function raises an AssertionError if the validation fails.
238
238
239 Note that this starts IPython in a subprocess!
239 Note that this starts IPython in a subprocess!
240
240
241 Parameters
241 Parameters
242 ----------
242 ----------
243 fname : str
243 fname : str
244 Name of the file to be executed (should have .py or .ipy extension).
244 Name of the file to be executed (should have .py or .ipy extension).
245
245
246 expected_out : str
246 expected_out : str
247 Expected stdout of the process.
247 Expected stdout of the process.
248
248
249 expected_err : optional, str
249 expected_err : optional, str
250 Expected stderr of the process.
250 Expected stderr of the process.
251
251
252 options : optional, list
252 options : optional, list
253 Extra command-line flags to be passed to IPython.
253 Extra command-line flags to be passed to IPython.
254
254
255 Returns
255 Returns
256 -------
256 -------
257 None
257 None
258 """
258 """
259
259
260 import nose.tools as nt
260 import nose.tools as nt
261
261
262 out, err = ipexec(fname, options)
262 out, err = ipexec(fname, options)
263 #print 'OUT', out # dbg
263 #print 'OUT', out # dbg
264 #print 'ERR', err # dbg
264 #print 'ERR', err # dbg
265 # If there are any errors, we must check those befor stdout, as they may be
265 # If there are any errors, we must check those befor stdout, as they may be
266 # more informative than simply having an empty stdout.
266 # more informative than simply having an empty stdout.
267 if err:
267 if err:
268 if expected_err:
268 if expected_err:
269 nt.assert_equals(err.strip(), expected_err.strip())
269 nt.assert_equals(err.strip(), expected_err.strip())
270 else:
270 else:
271 raise ValueError('Running file %r produced error: %r' %
271 raise ValueError('Running file %r produced error: %r' %
272 (fname, err))
272 (fname, err))
273 # If no errors or output on stderr was expected, match stdout
273 # If no errors or output on stderr was expected, match stdout
274 nt.assert_equals(out.strip(), expected_out.strip())
274 nt.assert_equals(out.strip(), expected_out.strip())
275
275
276
276
277 class TempFileMixin(object):
277 class TempFileMixin(object):
278 """Utility class to create temporary Python/IPython files.
278 """Utility class to create temporary Python/IPython files.
279
279
280 Meant as a mixin class for test cases."""
280 Meant as a mixin class for test cases."""
281
281
282 def mktmp(self, src, ext='.py'):
282 def mktmp(self, src, ext='.py'):
283 """Make a valid python temp file."""
283 """Make a valid python temp file."""
284 fname, f = temp_pyfile(src, ext)
284 fname, f = temp_pyfile(src, ext)
285 self.tmpfile = f
285 self.tmpfile = f
286 self.fname = fname
286 self.fname = fname
287
287
288 def tearDown(self):
288 def tearDown(self):
289 if hasattr(self, 'tmpfile'):
289 if hasattr(self, 'tmpfile'):
290 # If the tmpfile wasn't made because of skipped tests, like in
290 # If the tmpfile wasn't made because of skipped tests, like in
291 # win32, there's nothing to cleanup.
291 # win32, there's nothing to cleanup.
292 self.tmpfile.close()
292 self.tmpfile.close()
293 try:
293 try:
294 os.unlink(self.fname)
294 os.unlink(self.fname)
295 except:
295 except:
296 # On Windows, even though we close the file, we still can't
296 # On Windows, even though we close the file, we still can't
297 # delete it. I have no clue why
297 # delete it. I have no clue why
298 pass
298 pass
299
299
300 pair_fail_msg = ("Testing {0}\n\n"
300 pair_fail_msg = ("Testing {0}\n\n"
301 "In:\n"
301 "In:\n"
302 " {1!r}\n"
302 " {1!r}\n"
303 "Expected:\n"
303 "Expected:\n"
304 " {2!r}\n"
304 " {2!r}\n"
305 "Got:\n"
305 "Got:\n"
306 " {3!r}\n")
306 " {3!r}\n")
307 def check_pairs(func, pairs):
307 def check_pairs(func, pairs):
308 """Utility function for the common case of checking a function with a
308 """Utility function for the common case of checking a function with a
309 sequence of input/output pairs.
309 sequence of input/output pairs.
310
310
311 Parameters
311 Parameters
312 ----------
312 ----------
313 func : callable
313 func : callable
314 The function to be tested. Should accept a single argument.
314 The function to be tested. Should accept a single argument.
315 pairs : iterable
315 pairs : iterable
316 A list of (input, expected_output) tuples.
316 A list of (input, expected_output) tuples.
317
317
318 Returns
318 Returns
319 -------
319 -------
320 None. Raises an AssertionError if any output does not match the expected
320 None. Raises an AssertionError if any output does not match the expected
321 value.
321 value.
322 """
322 """
323 name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>"))
323 name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>"))
324 for inp, expected in pairs:
324 for inp, expected in pairs:
325 out = func(inp)
325 out = func(inp)
326 assert out == expected, pair_fail_msg.format(name, inp, expected, out)
326 assert out == expected, pair_fail_msg.format(name, inp, expected, out)
327
327
328
328
329 if py3compat.PY3:
329 if py3compat.PY3:
330 MyStringIO = StringIO
330 MyStringIO = StringIO
331 else:
331 else:
332 # In Python 2, stdout/stderr can have either bytes or unicode written to them,
332 # In Python 2, stdout/stderr can have either bytes or unicode written to them,
333 # so we need a class that can handle both.
333 # so we need a class that can handle both.
334 class MyStringIO(StringIO):
334 class MyStringIO(StringIO):
335 def write(self, s):
335 def write(self, s):
336 s = py3compat.cast_unicode(s, encoding=getdefaultencoding())
336 s = py3compat.cast_unicode(s, encoding=getdefaultencoding())
337 super(MyStringIO, self).write(s)
337 super(MyStringIO, self).write(s)
338
338
339 notprinted_msg = """Did not find {0!r} in printed output (on {1}):
339 notprinted_msg = """Did not find {0!r} in printed output (on {1}):
340 {2!r}"""
340 {2!r}"""
341
341
342 class AssertPrints(object):
342 class AssertPrints(object):
343 """Context manager for testing that code prints certain text.
343 """Context manager for testing that code prints certain text.
344
344
345 Examples
345 Examples
346 --------
346 --------
347 >>> with AssertPrints("abc", suppress=False):
347 >>> with AssertPrints("abc", suppress=False):
348 ... print "abcd"
348 ... print "abcd"
349 ... print "def"
349 ... print "def"
350 ...
350 ...
351 abcd
351 abcd
352 def
352 def
353 """
353 """
354 def __init__(self, s, channel='stdout', suppress=True):
354 def __init__(self, s, channel='stdout', suppress=True):
355 self.s = s
355 self.s = s
356 self.channel = channel
356 self.channel = channel
357 self.suppress = suppress
357 self.suppress = suppress
358
358
359 def __enter__(self):
359 def __enter__(self):
360 self.orig_stream = getattr(sys, self.channel)
360 self.orig_stream = getattr(sys, self.channel)
361 self.buffer = MyStringIO()
361 self.buffer = MyStringIO()
362 self.tee = Tee(self.buffer, channel=self.channel)
362 self.tee = Tee(self.buffer, channel=self.channel)
363 setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
363 setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
364
364
365 def __exit__(self, etype, value, traceback):
365 def __exit__(self, etype, value, traceback):
366 self.tee.flush()
366 self.tee.flush()
367 setattr(sys, self.channel, self.orig_stream)
367 setattr(sys, self.channel, self.orig_stream)
368 printed = self.buffer.getvalue()
368 printed = self.buffer.getvalue()
369 assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed)
369 assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed)
370 return False
370 return False
371
371
372 class AssertNotPrints(AssertPrints):
372 class AssertNotPrints(AssertPrints):
373 """Context manager for checking that certain output *isn't* produced.
373 """Context manager for checking that certain output *isn't* produced.
374
374
375 Counterpart of AssertPrints"""
375 Counterpart of AssertPrints"""
376 def __exit__(self, etype, value, traceback):
376 def __exit__(self, etype, value, traceback):
377 self.tee.flush()
377 self.tee.flush()
378 setattr(sys, self.channel, self.orig_stream)
378 setattr(sys, self.channel, self.orig_stream)
379 printed = self.buffer.getvalue()
379 printed = self.buffer.getvalue()
380 assert self.s not in printed, notprinted_msg.format(self.s, self.channel, printed)
380 assert self.s not in printed, notprinted_msg.format(self.s, self.channel, printed)
381 return False
381 return False
382
382
383 @contextmanager
383 @contextmanager
384 def mute_warn():
384 def mute_warn():
385 from IPython.utils import warn
385 from IPython.utils import warn
386 save_warn = warn.warn
386 save_warn = warn.warn
387 warn.warn = lambda *a, **kw: None
387 warn.warn = lambda *a, **kw: None
388 try:
388 try:
389 yield
389 yield
390 finally:
390 finally:
391 warn.warn = save_warn
391 warn.warn = save_warn
392
392
393 @contextmanager
393 @contextmanager
394 def make_tempfile(name):
394 def make_tempfile(name):
395 """ Create an empty, named, temporary file for the duration of the context.
395 """ Create an empty, named, temporary file for the duration of the context.
396 """
396 """
397 f = open(name, 'w')
397 f = open(name, 'w')
398 f.close()
398 f.close()
399 try:
399 try:
400 yield
400 yield
401 finally:
401 finally:
402 os.unlink(name)
402 os.unlink(name)
@@ -1,137 +1,137 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 """An example of how to embed an IPython shell into a running program.
3 """An example of how to embed an IPython shell into a running program.
4
4
5 Please see the documentation in the IPython.Shell module for more details.
5 Please see the documentation in the IPython.Shell module for more details.
6
6
7 The accompanying file example-embed-short.py has quick code fragments for
7 The accompanying file example-embed-short.py has quick code fragments for
8 embedding which you can cut and paste in your code once you understand how
8 embedding which you can cut and paste in your code once you understand how
9 things work.
9 things work.
10
10
11 The code in this file is deliberately extra-verbose, meant for learning."""
11 The code in this file is deliberately extra-verbose, meant for learning."""
12
12
13 # The basics to get you going:
13 # The basics to get you going:
14
14
15 # IPython sets the __IPYTHON__ variable so you can know if you have nested
15 # IPython sets the __IPYTHON__ variable so you can know if you have nested
16 # copies running.
16 # copies running.
17
17
18 # Try running this code both at the command line and from inside IPython (with
18 # Try running this code both at the command line and from inside IPython (with
19 # %run example-embed.py)
19 # %run example-embed.py)
20 from IPython.config.loader import Config
20 from IPython.config.loader import Config
21 try:
21 try:
22 get_ipython
22 get_ipython
23 except NameError:
23 except NameError:
24 nested = 0
24 nested = 0
25 cfg = Config()
25 cfg = Config()
26 shell_config = cfg.InteractiveShellEmbed
26 prompt_config = cfg.PromptManager
27 shell_config.prompt_in1 = 'In <\\#>: '
27 prompt_config.in_template = 'In <\\#>: '
28 shell_config.prompt_in2 = ' .\\D.: '
28 prompt_config.in2_template = ' .\\D.: '
29 shell_config.prompt_out = 'Out<\\#>: '
29 prompt_config.out_template = 'Out<\\#>: '
30 else:
30 else:
31 print "Running nested copies of IPython."
31 print "Running nested copies of IPython."
32 print "The prompts for the nested copy have been modified"
32 print "The prompts for the nested copy have been modified"
33 cfg = Config()
33 cfg = Config()
34 nested = 1
34 nested = 1
35
35
36 # First import the embeddable shell class
36 # First import the embeddable shell class
37 from IPython.frontend.terminal.embed import InteractiveShellEmbed
37 from IPython.frontend.terminal.embed import InteractiveShellEmbed
38
38
39 # Now create an instance of the embeddable shell. The first argument is a
39 # Now create an instance of the embeddable shell. The first argument is a
40 # string with options exactly as you would type them if you were starting
40 # string with options exactly as you would type them if you were starting
41 # IPython at the system command line. Any parameters you want to define for
41 # IPython at the system command line. Any parameters you want to define for
42 # configuration can thus be specified here.
42 # configuration can thus be specified here.
43 ipshell = InteractiveShellEmbed(config=cfg,
43 ipshell = InteractiveShellEmbed(config=cfg,
44 banner1 = 'Dropping into IPython',
44 banner1 = 'Dropping into IPython',
45 exit_msg = 'Leaving Interpreter, back to program.')
45 exit_msg = 'Leaving Interpreter, back to program.')
46
46
47 # Make a second instance, you can have as many as you want.
47 # Make a second instance, you can have as many as you want.
48 cfg2 = cfg.copy()
48 cfg2 = cfg.copy()
49 shell_config = cfg2.InteractiveShellEmbed
49 prompt_config = cfg2.PromptManager
50 shell_config.prompt_in1 = 'In2<\\#>: '
50 prompt_config.in_template = 'In2<\\#>: '
51 if not nested:
51 if not nested:
52 shell_config.prompt_in1 = 'In2<\\#>: '
52 prompt_config.in_template = 'In2<\\#>: '
53 shell_config.prompt_in2 = ' .\\D.: '
53 prompt_config.in2_template = ' .\\D.: '
54 shell_config.prompt_out = 'Out<\\#>: '
54 prompt_config.out_template = 'Out<\\#>: '
55 ipshell2 = InteractiveShellEmbed(config=cfg,
55 ipshell2 = InteractiveShellEmbed(config=cfg,
56 banner1 = 'Second IPython instance.')
56 banner1 = 'Second IPython instance.')
57
57
58 print '\nHello. This is printed from the main controller program.\n'
58 print '\nHello. This is printed from the main controller program.\n'
59
59
60 # You can then call ipshell() anywhere you need it (with an optional
60 # You can then call ipshell() anywhere you need it (with an optional
61 # message):
61 # message):
62 ipshell('***Called from top level. '
62 ipshell('***Called from top level. '
63 'Hit Ctrl-D to exit interpreter and continue program.\n'
63 'Hit Ctrl-D to exit interpreter and continue program.\n'
64 'Note that if you use %kill_embedded, you can fully deactivate\n'
64 'Note that if you use %kill_embedded, you can fully deactivate\n'
65 'This embedded instance so it will never turn on again')
65 'This embedded instance so it will never turn on again')
66
66
67 print '\nBack in caller program, moving along...\n'
67 print '\nBack in caller program, moving along...\n'
68
68
69 #---------------------------------------------------------------------------
69 #---------------------------------------------------------------------------
70 # More details:
70 # More details:
71
71
72 # InteractiveShellEmbed instances don't print the standard system banner and
72 # InteractiveShellEmbed instances don't print the standard system banner and
73 # messages. The IPython banner (which actually may contain initialization
73 # messages. The IPython banner (which actually may contain initialization
74 # messages) is available as get_ipython().banner in case you want it.
74 # messages) is available as get_ipython().banner in case you want it.
75
75
76 # InteractiveShellEmbed instances print the following information everytime they
76 # InteractiveShellEmbed instances print the following information everytime they
77 # start:
77 # start:
78
78
79 # - A global startup banner.
79 # - A global startup banner.
80
80
81 # - A call-specific header string, which you can use to indicate where in the
81 # - A call-specific header string, which you can use to indicate where in the
82 # execution flow the shell is starting.
82 # execution flow the shell is starting.
83
83
84 # They also print an exit message every time they exit.
84 # They also print an exit message every time they exit.
85
85
86 # Both the startup banner and the exit message default to None, and can be set
86 # Both the startup banner and the exit message default to None, and can be set
87 # either at the instance constructor or at any other time with the
87 # either at the instance constructor or at any other time with the
88 # by setting the banner and exit_msg attributes.
88 # by setting the banner and exit_msg attributes.
89
89
90 # The shell instance can be also put in 'dummy' mode globally or on a per-call
90 # The shell instance can be also put in 'dummy' mode globally or on a per-call
91 # basis. This gives you fine control for debugging without having to change
91 # basis. This gives you fine control for debugging without having to change
92 # code all over the place.
92 # code all over the place.
93
93
94 # The code below illustrates all this.
94 # The code below illustrates all this.
95
95
96
96
97 # This is how the global banner and exit_msg can be reset at any point
97 # This is how the global banner and exit_msg can be reset at any point
98 ipshell.banner = 'Entering interpreter - New Banner'
98 ipshell.banner = 'Entering interpreter - New Banner'
99 ipshell.exit_msg = 'Leaving interpreter - New exit_msg'
99 ipshell.exit_msg = 'Leaving interpreter - New exit_msg'
100
100
101 def foo(m):
101 def foo(m):
102 s = 'spam'
102 s = 'spam'
103 ipshell('***In foo(). Try %whos, or print s or m:')
103 ipshell('***In foo(). Try %whos, or print s or m:')
104 print 'foo says m = ',m
104 print 'foo says m = ',m
105
105
106 def bar(n):
106 def bar(n):
107 s = 'eggs'
107 s = 'eggs'
108 ipshell('***In bar(). Try %whos, or print s or n:')
108 ipshell('***In bar(). Try %whos, or print s or n:')
109 print 'bar says n = ',n
109 print 'bar says n = ',n
110
110
111 # Some calls to the above functions which will trigger IPython:
111 # Some calls to the above functions which will trigger IPython:
112 print 'Main program calling foo("eggs")\n'
112 print 'Main program calling foo("eggs")\n'
113 foo('eggs')
113 foo('eggs')
114
114
115 # The shell can be put in 'dummy' mode where calls to it silently return. This
115 # The shell can be put in 'dummy' mode where calls to it silently return. This
116 # allows you, for example, to globally turn off debugging for a program with a
116 # allows you, for example, to globally turn off debugging for a program with a
117 # single call.
117 # single call.
118 ipshell.dummy_mode = True
118 ipshell.dummy_mode = True
119 print '\nTrying to call IPython which is now "dummy":'
119 print '\nTrying to call IPython which is now "dummy":'
120 ipshell()
120 ipshell()
121 print 'Nothing happened...'
121 print 'Nothing happened...'
122 # The global 'dummy' mode can still be overridden for a single call
122 # The global 'dummy' mode can still be overridden for a single call
123 print '\nOverriding dummy mode manually:'
123 print '\nOverriding dummy mode manually:'
124 ipshell(dummy=False)
124 ipshell(dummy=False)
125
125
126 # Reactivate the IPython shell
126 # Reactivate the IPython shell
127 ipshell.dummy_mode = False
127 ipshell.dummy_mode = False
128
128
129 print 'You can even have multiple embedded instances:'
129 print 'You can even have multiple embedded instances:'
130 ipshell2()
130 ipshell2()
131
131
132 print '\nMain program calling bar("spam")\n'
132 print '\nMain program calling bar("spam")\n'
133 bar('spam')
133 bar('spam')
134
134
135 print 'Main program finished. Bye!'
135 print 'Main program finished. Bye!'
136
136
137 #********************** End of file <example-embed.py> ***********************
137 #********************** End of file <example-embed.py> ***********************
@@ -1,1263 +1,1263 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 .. note::
14 .. note::
15
15
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17
17
18 If invoked with no options, it executes all the files listed in sequence
18 If invoked with no options, it executes all the files listed in sequence
19 and drops you into the interpreter while still acknowledging any options
19 and drops you into the interpreter while still acknowledging any options
20 you may have set in your ipython_config.py. This behavior is different from
20 you may have set in your ipython_config.py. This behavior is different from
21 standard Python, which when called as python -i will only execute one
21 standard Python, which when called as python -i will only execute one
22 file and ignore your configuration setup.
22 file and ignore your configuration setup.
23
23
24 Please note that some of the configuration options are not available at
24 Please note that some of the configuration options are not available at
25 the command line, simply because they are not practical here. Look into
25 the command line, simply because they are not practical here. Look into
26 your configuration files for details on those. There are separate configuration
26 your configuration files for details on those. There are separate configuration
27 files for each profile, and the files look like "ipython_config.py" or
27 files for each profile, and the files look like "ipython_config.py" or
28 "ipython_config_<frontendname>.py". Profile directories look like
28 "ipython_config_<frontendname>.py". Profile directories look like
29 "profile_profilename" and are typically installed in the IPYTHON_DIR directory.
29 "profile_profilename" and are typically installed in the IPYTHON_DIR directory.
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
32 Settings\\YourUserName in most instances.
32 Settings\\YourUserName in most instances.
33
33
34
34
35 Eventloop integration
35 Eventloop integration
36 ---------------------
36 ---------------------
37
37
38 Previously IPython had command line options for controlling GUI event loop
38 Previously IPython had command line options for controlling GUI event loop
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 version 0.11, these have been removed. Please see the new ``%gui``
40 version 0.11, these have been removed. Please see the new ``%gui``
41 magic command or :ref:`this section <gui_support>` for details on the new
41 magic command or :ref:`this section <gui_support>` for details on the new
42 interface, or specify the gui at the commandline::
42 interface, or specify the gui at the commandline::
43
43
44 $ ipython --gui=qt
44 $ ipython --gui=qt
45
45
46
46
47 Regular Options
47 Regular Options
48 ---------------
48 ---------------
49
49
50 After the above threading options have been given, regular options can
50 After the above threading options have been given, regular options can
51 follow in any order. All options can be abbreviated to their shortest
51 follow in any order. All options can be abbreviated to their shortest
52 non-ambiguous form and are case-sensitive.
52 non-ambiguous form and are case-sensitive.
53
53
54 Most options can also be set from your configuration file. See the provided
54 Most options can also be set from your configuration file. See the provided
55 example for more details on what the options do. Options given at the command
55 example for more details on what the options do. Options given at the command
56 line override the values set in the configuration file.
56 line override the values set in the configuration file.
57
57
58 All options with a [no] prepended can be specified in negated form
58 All options with a [no] prepended can be specified in negated form
59 (--no-option instead of --option) to turn the feature off.
59 (--no-option instead of --option) to turn the feature off.
60
60
61 ``-h, --help`` print a help message and exit.
61 ``-h, --help`` print a help message and exit.
62
62
63 ``--pylab, pylab=<name>``
63 ``--pylab, pylab=<name>``
64 See :ref:`Matplotlib support <matplotlib_support>`
64 See :ref:`Matplotlib support <matplotlib_support>`
65 for more details.
65 for more details.
66
66
67 ``--autocall=<val>``
67 ``--autocall=<val>``
68 Make IPython automatically call any callable object even if you
68 Make IPython automatically call any callable object even if you
69 didn't type explicit parentheses. For example, 'str 43' becomes
69 didn't type explicit parentheses. For example, 'str 43' becomes
70 'str(43)' automatically. The value can be '0' to disable the feature,
70 'str(43)' automatically. The value can be '0' to disable the feature,
71 '1' for smart autocall, where it is not applied if there are no more
71 '1' for smart autocall, where it is not applied if there are no more
72 arguments on the line, and '2' for full autocall, where all callable
72 arguments on the line, and '2' for full autocall, where all callable
73 objects are automatically called (even if no arguments are
73 objects are automatically called (even if no arguments are
74 present). The default is '1'.
74 present). The default is '1'.
75
75
76 ``--[no-]autoindent``
76 ``--[no-]autoindent``
77 Turn automatic indentation on/off.
77 Turn automatic indentation on/off.
78
78
79 ``--[no-]automagic``
79 ``--[no-]automagic``
80 make magic commands automatic (without needing their first character
80 make magic commands automatic (without needing their first character
81 to be %). Type %magic at the IPython prompt for more information.
81 to be %). Type %magic at the IPython prompt for more information.
82
82
83 ``--[no-]autoedit_syntax``
83 ``--[no-]autoedit_syntax``
84 When a syntax error occurs after editing a file, automatically
84 When a syntax error occurs after editing a file, automatically
85 open the file to the trouble causing line for convenient
85 open the file to the trouble causing line for convenient
86 fixing.
86 fixing.
87
87
88 ``--[no-]banner``
88 ``--[no-]banner``
89 Print the initial information banner (default on).
89 Print the initial information banner (default on).
90
90
91 ``-c <command>``
91 ``-c <command>``
92 execute the given command string. This is similar to the -c
92 execute the given command string. This is similar to the -c
93 option in the normal Python interpreter.
93 option in the normal Python interpreter.
94
94
95 ``--cache-size=<n>``
95 ``--cache-size=<n>``
96 size of the output cache (maximum number of entries to hold in
96 size of the output cache (maximum number of entries to hold in
97 memory). The default is 1000, you can change it permanently in your
97 memory). The default is 1000, you can change it permanently in your
98 config file. Setting it to 0 completely disables the caching system,
98 config file. Setting it to 0 completely disables the caching system,
99 and the minimum value accepted is 20 (if you provide a value less than
99 and the minimum value accepted is 20 (if you provide a value less than
100 20, it is reset to 0 and a warning is issued) This limit is defined
100 20, it is reset to 0 and a warning is issued) This limit is defined
101 because otherwise you'll spend more time re-flushing a too small cache
101 because otherwise you'll spend more time re-flushing a too small cache
102 than working.
102 than working.
103
103
104 ``--classic``
104 ``--classic``
105 Gives IPython a similar feel to the classic Python
105 Gives IPython a similar feel to the classic Python
106 prompt.
106 prompt.
107
107
108 ``--colors=<scheme>``
108 ``--colors=<scheme>``
109 Color scheme for prompts and exception reporting. Currently
109 Color scheme for prompts and exception reporting. Currently
110 implemented: NoColor, Linux and LightBG.
110 implemented: NoColor, Linux and LightBG.
111
111
112 ``--[no-]color_info``
112 ``--[no-]color_info``
113 IPython can display information about objects via a set of functions,
113 IPython can display information about objects via a set of functions,
114 and optionally can use colors for this, syntax highlighting source
114 and optionally can use colors for this, syntax highlighting source
115 code and various other elements. However, because this information is
115 code and various other elements. However, because this information is
116 passed through a pager (like 'less') and many pagers get confused with
116 passed through a pager (like 'less') and many pagers get confused with
117 color codes, this option is off by default. You can test it and turn
117 color codes, this option is off by default. You can test it and turn
118 it on permanently in your configuration file if it works for you. As a
118 it on permanently in your configuration file if it works for you. As a
119 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
119 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
120 that in RedHat 7.2 doesn't.
120 that in RedHat 7.2 doesn't.
121
121
122 Test it and turn it on permanently if it works with your
122 Test it and turn it on permanently if it works with your
123 system. The magic function %color_info allows you to toggle this
123 system. The magic function %color_info allows you to toggle this
124 interactively for testing.
124 interactively for testing.
125
125
126 ``--[no-]debug``
126 ``--[no-]debug``
127 Show information about the loading process. Very useful to pin down
127 Show information about the loading process. Very useful to pin down
128 problems with your configuration files or to get details about
128 problems with your configuration files or to get details about
129 session restores.
129 session restores.
130
130
131 ``--[no-]deep_reload``
131 ``--[no-]deep_reload``
132 IPython can use the deep_reload module which reloads changes in
132 IPython can use the deep_reload module which reloads changes in
133 modules recursively (it replaces the reload() function, so you don't
133 modules recursively (it replaces the reload() function, so you don't
134 need to change anything to use it). deep_reload() forces a full
134 need to change anything to use it). deep_reload() forces a full
135 reload of modules whose code may have changed, which the default
135 reload of modules whose code may have changed, which the default
136 reload() function does not.
136 reload() function does not.
137
137
138 When deep_reload is off, IPython will use the normal reload(),
138 When deep_reload is off, IPython will use the normal reload(),
139 but deep_reload will still be available as dreload(). This
139 but deep_reload will still be available as dreload(). This
140 feature is off by default [which means that you have both
140 feature is off by default [which means that you have both
141 normal reload() and dreload()].
141 normal reload() and dreload()].
142
142
143 .. this isn't currently working
143 .. this isn't currently working
144 .. ``--editor=<name>``
144 .. ``--editor=<name>``
145 Which editor to use with the %edit command. By default,
145 Which editor to use with the %edit command. By default,
146 IPython will honor your EDITOR environment variable (if not
146 IPython will honor your EDITOR environment variable (if not
147 set, vi is the Unix default and notepad the Windows one).
147 set, vi is the Unix default and notepad the Windows one).
148 Since this editor is invoked on the fly by IPython and is
148 Since this editor is invoked on the fly by IPython and is
149 meant for editing small code snippets, you may want to use a
149 meant for editing small code snippets, you may want to use a
150 small, lightweight editor here (in case your default EDITOR is
150 small, lightweight editor here (in case your default EDITOR is
151 something like Emacs).
151 something like Emacs).
152
152
153 ``--ipython_dir=<name>``
153 ``--ipython_dir=<name>``
154 name of your IPython configuration directory IPYTHON_DIR. This
154 name of your IPython configuration directory IPYTHON_DIR. This
155 can also be specified through the environment variable
155 can also be specified through the environment variable
156 IPYTHON_DIR.
156 IPYTHON_DIR.
157
157
158 ``--logfile=<name>``
158 ``--logfile=<name>``
159 specify the name of your logfile.
159 specify the name of your logfile.
160
160
161 This implies ``%logstart`` at the beginning of your session
161 This implies ``%logstart`` at the beginning of your session
162
162
163 generate a log file of all input. The file is named
163 generate a log file of all input. The file is named
164 ipython_log.py in your current directory (which prevents logs
164 ipython_log.py in your current directory (which prevents logs
165 from multiple IPython sessions from trampling each other). You
165 from multiple IPython sessions from trampling each other). You
166 can use this to later restore a session by loading your
166 can use this to later restore a session by loading your
167 logfile with ``ipython -i ipython_log.py``
167 logfile with ``ipython -i ipython_log.py``
168
168
169 ``--logplay=<name>``
169 ``--logplay=<name>``
170
170
171 NOT AVAILABLE in 0.11
171 NOT AVAILABLE in 0.11
172
172
173 you can replay a previous log. For restoring a session as close as
173 you can replay a previous log. For restoring a session as close as
174 possible to the state you left it in, use this option (don't just run
174 possible to the state you left it in, use this option (don't just run
175 the logfile). With -logplay, IPython will try to reconstruct the
175 the logfile). With -logplay, IPython will try to reconstruct the
176 previous working environment in full, not just execute the commands in
176 previous working environment in full, not just execute the commands in
177 the logfile.
177 the logfile.
178
178
179 When a session is restored, logging is automatically turned on
179 When a session is restored, logging is automatically turned on
180 again with the name of the logfile it was invoked with (it is
180 again with the name of the logfile it was invoked with (it is
181 read from the log header). So once you've turned logging on for
181 read from the log header). So once you've turned logging on for
182 a session, you can quit IPython and reload it as many times as
182 a session, you can quit IPython and reload it as many times as
183 you want and it will continue to log its history and restore
183 you want and it will continue to log its history and restore
184 from the beginning every time.
184 from the beginning every time.
185
185
186 Caveats: there are limitations in this option. The history
186 Caveats: there are limitations in this option. The history
187 variables _i*,_* and _dh don't get restored properly. In the
187 variables _i*,_* and _dh don't get restored properly. In the
188 future we will try to implement full session saving by writing
188 future we will try to implement full session saving by writing
189 and retrieving a 'snapshot' of the memory state of IPython. But
189 and retrieving a 'snapshot' of the memory state of IPython. But
190 our first attempts failed because of inherent limitations of
190 our first attempts failed because of inherent limitations of
191 Python's Pickle module, so this may have to wait.
191 Python's Pickle module, so this may have to wait.
192
192
193 ``--[no-]messages``
193 ``--[no-]messages``
194 Print messages which IPython collects about its startup
194 Print messages which IPython collects about its startup
195 process (default on).
195 process (default on).
196
196
197 ``--[no-]pdb``
197 ``--[no-]pdb``
198 Automatically call the pdb debugger after every uncaught
198 Automatically call the pdb debugger after every uncaught
199 exception. If you are used to debugging using pdb, this puts
199 exception. If you are used to debugging using pdb, this puts
200 you automatically inside of it after any call (either in
200 you automatically inside of it after any call (either in
201 IPython or in code called by it) which triggers an exception
201 IPython or in code called by it) which triggers an exception
202 which goes uncaught.
202 which goes uncaught.
203
203
204 ``--[no-]pprint``
204 ``--[no-]pprint``
205 ipython can optionally use the pprint (pretty printer) module
205 ipython can optionally use the pprint (pretty printer) module
206 for displaying results. pprint tends to give a nicer display
206 for displaying results. pprint tends to give a nicer display
207 of nested data structures. If you like it, you can turn it on
207 of nested data structures. If you like it, you can turn it on
208 permanently in your config file (default off).
208 permanently in your config file (default off).
209
209
210 ``--profile=<name>``
210 ``--profile=<name>``
211
211
212 Select the IPython profile by name.
212 Select the IPython profile by name.
213
213
214 This is a quick way to keep and load multiple
214 This is a quick way to keep and load multiple
215 config files for different tasks, especially if you use the
215 config files for different tasks, especially if you use the
216 include option of config files. You can keep a basic
216 include option of config files. You can keep a basic
217 :file:`IPYTHON_DIR/profile_default/ipython_config.py` file
217 :file:`IPYTHON_DIR/profile_default/ipython_config.py` file
218 and then have other 'profiles' which
218 and then have other 'profiles' which
219 include this one and load extra things for particular
219 include this one and load extra things for particular
220 tasks. For example:
220 tasks. For example:
221
221
222 1. $IPYTHON_DIR/profile_default : load basic things you always want.
222 1. $IPYTHON_DIR/profile_default : load basic things you always want.
223 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules.
223 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules.
224 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules.
224 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules.
225
225
226 Since it is possible to create an endless loop by having
226 Since it is possible to create an endless loop by having
227 circular file inclusions, IPython will stop if it reaches 15
227 circular file inclusions, IPython will stop if it reaches 15
228 recursive inclusions.
228 recursive inclusions.
229
229
230 ``InteractiveShell.prompt_in1=<string>``
230 ``PromptManager.in_template=<string>``
231
231
232 Specify the string used for input prompts. Note that if you are using
232 Specify the string used for input prompts. Note that if you are using
233 numbered prompts, the number is represented with a '\#' in the
233 numbered prompts, the number is represented with a '\#' in the
234 string. Don't forget to quote strings with spaces embedded in
234 string. Don't forget to quote strings with spaces embedded in
235 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
235 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
236 discusses in detail all the available escapes to customize your
236 discusses in detail all the available escapes to customize your
237 prompts.
237 prompts.
238
238
239 ``InteractiveShell.prompt_in2=<string>``
239 ``PromptManager.in2_template=<string>``
240 Similar to the previous option, but used for the continuation
240 Similar to the previous option, but used for the continuation
241 prompts. The special sequence '\D' is similar to '\#', but
241 prompts. The special sequence '\D' is similar to '\#', but
242 with all digits replaced dots (so you can have your
242 with all digits replaced dots (so you can have your
243 continuation prompt aligned with your input prompt). Default:
243 continuation prompt aligned with your input prompt). Default:
244 ' .\D.:' (note three spaces at the start for alignment with
244 ' .\D.:' (note three spaces at the start for alignment with
245 'In [\#]').
245 'In [\#]').
246
246
247 ``InteractiveShell.prompt_out=<string>``
247 ``PromptManager.out_template=<string>``
248 String used for output prompts, also uses numbers like
248 String used for output prompts, also uses numbers like
249 prompt_in1. Default: 'Out[\#]:'
249 in_template. Default: 'Out[\#]:'
250
250
251 ``--quick``
251 ``--quick``
252 start in bare bones mode (no config file loaded).
252 start in bare bones mode (no config file loaded).
253
253
254 ``config_file=<name>``
254 ``config_file=<name>``
255 name of your IPython resource configuration file. Normally
255 name of your IPython resource configuration file. Normally
256 IPython loads ipython_config.py (from current directory) or
256 IPython loads ipython_config.py (from current directory) or
257 IPYTHON_DIR/profile_default.
257 IPYTHON_DIR/profile_default.
258
258
259 If the loading of your config file fails, IPython starts with
259 If the loading of your config file fails, IPython starts with
260 a bare bones configuration (no modules loaded at all).
260 a bare bones configuration (no modules loaded at all).
261
261
262 ``--[no-]readline``
262 ``--[no-]readline``
263 use the readline library, which is needed to support name
263 use the readline library, which is needed to support name
264 completion and command history, among other things. It is
264 completion and command history, among other things. It is
265 enabled by default, but may cause problems for users of
265 enabled by default, but may cause problems for users of
266 X/Emacs in Python comint or shell buffers.
266 X/Emacs in Python comint or shell buffers.
267
267
268 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
268 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
269 IPython's readline and syntax coloring fine, only 'emacs' (M-x
269 IPython's readline and syntax coloring fine, only 'emacs' (M-x
270 shell and C-c !) buffers do not.
270 shell and C-c !) buffers do not.
271
271
272 ``--TerminalInteractiveShell.screen_length=<n>``
272 ``--TerminalInteractiveShell.screen_length=<n>``
273 number of lines of your screen. This is used to control
273 number of lines of your screen. This is used to control
274 printing of very long strings. Strings longer than this number
274 printing of very long strings. Strings longer than this number
275 of lines will be sent through a pager instead of directly
275 of lines will be sent through a pager instead of directly
276 printed.
276 printed.
277
277
278 The default value for this is 0, which means IPython will
278 The default value for this is 0, which means IPython will
279 auto-detect your screen size every time it needs to print certain
279 auto-detect your screen size every time it needs to print certain
280 potentially long strings (this doesn't change the behavior of the
280 potentially long strings (this doesn't change the behavior of the
281 'print' keyword, it's only triggered internally). If for some
281 'print' keyword, it's only triggered internally). If for some
282 reason this isn't working well (it needs curses support), specify
282 reason this isn't working well (it needs curses support), specify
283 it yourself. Otherwise don't change the default.
283 it yourself. Otherwise don't change the default.
284
284
285 ``--TerminalInteractiveShell.separate_in=<string>``
285 ``--TerminalInteractiveShell.separate_in=<string>``
286
286
287 separator before input prompts.
287 separator before input prompts.
288 Default: '\n'
288 Default: '\n'
289
289
290 ``--TerminalInteractiveShell.separate_out=<string>``
290 ``--TerminalInteractiveShell.separate_out=<string>``
291 separator before output prompts.
291 separator before output prompts.
292 Default: nothing.
292 Default: nothing.
293
293
294 ``--TerminalInteractiveShell.separate_out2=<string>``
294 ``--TerminalInteractiveShell.separate_out2=<string>``
295 separator after output prompts.
295 separator after output prompts.
296 Default: nothing.
296 Default: nothing.
297 For these three options, use the value 0 to specify no separator.
297 For these three options, use the value 0 to specify no separator.
298
298
299 ``--nosep``
299 ``--nosep``
300 shorthand for setting the above separators to empty strings.
300 shorthand for setting the above separators to empty strings.
301
301
302 Simply removes all input/output separators.
302 Simply removes all input/output separators.
303
303
304 ``--init``
304 ``--init``
305 allows you to initialize a profile dir for configuration when you
305 allows you to initialize a profile dir for configuration when you
306 install a new version of IPython or want to use a new profile.
306 install a new version of IPython or want to use a new profile.
307 Since new versions may include new command line options or example
307 Since new versions may include new command line options or example
308 files, this copies updated config files. Note that you should probably
308 files, this copies updated config files. Note that you should probably
309 use %upgrade instead,it's a safer alternative.
309 use %upgrade instead,it's a safer alternative.
310
310
311 ``--version`` print version information and exit.
311 ``--version`` print version information and exit.
312
312
313 ``--xmode=<modename>``
313 ``--xmode=<modename>``
314
314
315 Mode for exception reporting.
315 Mode for exception reporting.
316
316
317 Valid modes: Plain, Context and Verbose.
317 Valid modes: Plain, Context and Verbose.
318
318
319 * Plain: similar to python's normal traceback printing.
319 * Plain: similar to python's normal traceback printing.
320 * Context: prints 5 lines of context source code around each
320 * Context: prints 5 lines of context source code around each
321 line in the traceback.
321 line in the traceback.
322 * Verbose: similar to Context, but additionally prints the
322 * Verbose: similar to Context, but additionally prints the
323 variables currently visible where the exception happened
323 variables currently visible where the exception happened
324 (shortening their strings if too long). This can potentially be
324 (shortening their strings if too long). This can potentially be
325 very slow, if you happen to have a huge data structure whose
325 very slow, if you happen to have a huge data structure whose
326 string representation is complex to compute. Your computer may
326 string representation is complex to compute. Your computer may
327 appear to freeze for a while with cpu usage at 100%. If this
327 appear to freeze for a while with cpu usage at 100%. If this
328 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
328 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
329 more than once).
329 more than once).
330
330
331 Interactive use
331 Interactive use
332 ===============
332 ===============
333
333
334 IPython is meant to work as a drop-in replacement for the standard interactive
334 IPython is meant to work as a drop-in replacement for the standard interactive
335 interpreter. As such, any code which is valid python should execute normally
335 interpreter. As such, any code which is valid python should execute normally
336 under IPython (cases where this is not true should be reported as bugs). It
336 under IPython (cases where this is not true should be reported as bugs). It
337 does, however, offer many features which are not available at a standard python
337 does, however, offer many features which are not available at a standard python
338 prompt. What follows is a list of these.
338 prompt. What follows is a list of these.
339
339
340
340
341 Caution for Windows users
341 Caution for Windows users
342 -------------------------
342 -------------------------
343
343
344 Windows, unfortunately, uses the '\\' character as a path separator. This is a
344 Windows, unfortunately, uses the '\\' character as a path separator. This is a
345 terrible choice, because '\\' also represents the escape character in most
345 terrible choice, because '\\' also represents the escape character in most
346 modern programming languages, including Python. For this reason, using '/'
346 modern programming languages, including Python. For this reason, using '/'
347 character is recommended if you have problems with ``\``. However, in Windows
347 character is recommended if you have problems with ``\``. However, in Windows
348 commands '/' flags options, so you can not use it for the root directory. This
348 commands '/' flags options, so you can not use it for the root directory. This
349 means that paths beginning at the root must be typed in a contrived manner
349 means that paths beginning at the root must be typed in a contrived manner
350 like: ``%copy \opt/foo/bar.txt \tmp``
350 like: ``%copy \opt/foo/bar.txt \tmp``
351
351
352 .. _magic:
352 .. _magic:
353
353
354 Magic command system
354 Magic command system
355 --------------------
355 --------------------
356
356
357 IPython will treat any line whose first character is a % as a special
357 IPython will treat any line whose first character is a % as a special
358 call to a 'magic' function. These allow you to control the behavior of
358 call to a 'magic' function. These allow you to control the behavior of
359 IPython itself, plus a lot of system-type features. They are all
359 IPython itself, plus a lot of system-type features. They are all
360 prefixed with a % character, but parameters are given without
360 prefixed with a % character, but parameters are given without
361 parentheses or quotes.
361 parentheses or quotes.
362
362
363 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
363 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
364 exists.
364 exists.
365
365
366 If you have 'automagic' enabled (as it by default), you don't need
366 If you have 'automagic' enabled (as it by default), you don't need
367 to type in the % explicitly. IPython will scan its internal list of
367 to type in the % explicitly. IPython will scan its internal list of
368 magic functions and call one if it exists. With automagic on you can
368 magic functions and call one if it exists. With automagic on you can
369 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
369 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
370 system has the lowest possible precedence in name searches, so defining
370 system has the lowest possible precedence in name searches, so defining
371 an identifier with the same name as an existing magic function will
371 an identifier with the same name as an existing magic function will
372 shadow it for automagic use. You can still access the shadowed magic
372 shadow it for automagic use. You can still access the shadowed magic
373 function by explicitly using the % character at the beginning of the line.
373 function by explicitly using the % character at the beginning of the line.
374
374
375 An example (with automagic on) should clarify all this:
375 An example (with automagic on) should clarify all this:
376
376
377 .. sourcecode:: ipython
377 .. sourcecode:: ipython
378
378
379 In [1]: cd ipython # %cd is called by automagic
379 In [1]: cd ipython # %cd is called by automagic
380 /home/fperez/ipython
380 /home/fperez/ipython
381
381
382 In [2]: cd=1 # now cd is just a variable
382 In [2]: cd=1 # now cd is just a variable
383
383
384 In [3]: cd .. # and doesn't work as a function anymore
384 In [3]: cd .. # and doesn't work as a function anymore
385 File "<ipython-input-3-9fedb3aff56c>", line 1
385 File "<ipython-input-3-9fedb3aff56c>", line 1
386 cd ..
386 cd ..
387 ^
387 ^
388 SyntaxError: invalid syntax
388 SyntaxError: invalid syntax
389
389
390
390
391 In [4]: %cd .. # but %cd always works
391 In [4]: %cd .. # but %cd always works
392 /home/fperez
392 /home/fperez
393
393
394 In [5]: del cd # if you remove the cd variable, automagic works again
394 In [5]: del cd # if you remove the cd variable, automagic works again
395
395
396 In [6]: cd ipython
396 In [6]: cd ipython
397
397
398 /home/fperez/ipython
398 /home/fperez/ipython
399
399
400 You can define your own magic functions to extend the system. The
400 You can define your own magic functions to extend the system. The
401 following example defines a new magic command, %impall:
401 following example defines a new magic command, %impall:
402
402
403 .. sourcecode:: python
403 .. sourcecode:: python
404
404
405 ip = get_ipython()
405 ip = get_ipython()
406
406
407 def doimp(self, arg):
407 def doimp(self, arg):
408 ip = self.api
408 ip = self.api
409 ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) )
409 ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) )
410
410
411 ip.define_magic('impall', doimp)
411 ip.define_magic('impall', doimp)
412
412
413 Type ``%magic`` for more information, including a list of all available magic
413 Type ``%magic`` for more information, including a list of all available magic
414 functions at any time and their docstrings. You can also type
414 functions at any time and their docstrings. You can also type
415 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on
415 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on
416 the '?' system) to get information about any particular magic function you are
416 the '?' system) to get information about any particular magic function you are
417 interested in.
417 interested in.
418
418
419 The API documentation for the :mod:`IPython.core.magic` module contains the full
419 The API documentation for the :mod:`IPython.core.magic` module contains the full
420 docstrings of all currently available magic commands.
420 docstrings of all currently available magic commands.
421
421
422
422
423 Access to the standard Python help
423 Access to the standard Python help
424 ----------------------------------
424 ----------------------------------
425
425
426 Simply type ``help()`` to access Python's standard help system. You can
426 Simply type ``help()`` to access Python's standard help system. You can
427 also type ``help(object)`` for information about a given object, or
427 also type ``help(object)`` for information about a given object, or
428 ``help('keyword')`` for information on a keyword. You may need to configure your
428 ``help('keyword')`` for information on a keyword. You may need to configure your
429 PYTHONDOCS environment variable for this feature to work correctly.
429 PYTHONDOCS environment variable for this feature to work correctly.
430
430
431 .. _dynamic_object_info:
431 .. _dynamic_object_info:
432
432
433 Dynamic object information
433 Dynamic object information
434 --------------------------
434 --------------------------
435
435
436 Typing ``?word`` or ``word?`` prints detailed information about an object. If
436 Typing ``?word`` or ``word?`` prints detailed information about an object. If
437 certain strings in the object are too long (e.g. function signatures) they get
437 certain strings in the object are too long (e.g. function signatures) they get
438 snipped in the center for brevity. This system gives access variable types and
438 snipped in the center for brevity. This system gives access variable types and
439 values, docstrings, function prototypes and other useful information.
439 values, docstrings, function prototypes and other useful information.
440
440
441 If the information will not fit in the terminal, it is displayed in a pager
441 If the information will not fit in the terminal, it is displayed in a pager
442 (``less`` if available, otherwise a basic internal pager).
442 (``less`` if available, otherwise a basic internal pager).
443
443
444 Typing ``??word`` or ``word??`` gives access to the full information, including
444 Typing ``??word`` or ``word??`` gives access to the full information, including
445 the source code where possible. Long strings are not snipped.
445 the source code where possible. Long strings are not snipped.
446
446
447 The following magic functions are particularly useful for gathering
447 The following magic functions are particularly useful for gathering
448 information about your working environment. You can get more details by
448 information about your working environment. You can get more details by
449 typing ``%magic`` or querying them individually (``%function_name?``);
449 typing ``%magic`` or querying them individually (``%function_name?``);
450 this is just a summary:
450 this is just a summary:
451
451
452 * **%pdoc <object>**: Print (or run through a pager if too long) the
452 * **%pdoc <object>**: Print (or run through a pager if too long) the
453 docstring for an object. If the given object is a class, it will
453 docstring for an object. If the given object is a class, it will
454 print both the class and the constructor docstrings.
454 print both the class and the constructor docstrings.
455 * **%pdef <object>**: Print the definition header for any callable
455 * **%pdef <object>**: Print the definition header for any callable
456 object. If the object is a class, print the constructor information.
456 object. If the object is a class, print the constructor information.
457 * **%psource <object>**: Print (or run through a pager if too long)
457 * **%psource <object>**: Print (or run through a pager if too long)
458 the source code for an object.
458 the source code for an object.
459 * **%pfile <object>**: Show the entire source file where an object was
459 * **%pfile <object>**: Show the entire source file where an object was
460 defined via a pager, opening it at the line where the object
460 defined via a pager, opening it at the line where the object
461 definition begins.
461 definition begins.
462 * **%who/%whos**: These functions give information about identifiers
462 * **%who/%whos**: These functions give information about identifiers
463 you have defined interactively (not things you loaded or defined
463 you have defined interactively (not things you loaded or defined
464 in your configuration files). %who just prints a list of
464 in your configuration files). %who just prints a list of
465 identifiers and %whos prints a table with some basic details about
465 identifiers and %whos prints a table with some basic details about
466 each identifier.
466 each identifier.
467
467
468 Note that the dynamic object information functions (?/??, ``%pdoc``,
468 Note that the dynamic object information functions (?/??, ``%pdoc``,
469 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
469 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
470 directly on variables. For example, after doing ``import os``, you can use
470 directly on variables. For example, after doing ``import os``, you can use
471 ``os.path.abspath??``.
471 ``os.path.abspath??``.
472
472
473 .. _readline:
473 .. _readline:
474
474
475 Readline-based features
475 Readline-based features
476 -----------------------
476 -----------------------
477
477
478 These features require the GNU readline library, so they won't work if your
478 These features require the GNU readline library, so they won't work if your
479 Python installation lacks readline support. We will first describe the default
479 Python installation lacks readline support. We will first describe the default
480 behavior IPython uses, and then how to change it to suit your preferences.
480 behavior IPython uses, and then how to change it to suit your preferences.
481
481
482
482
483 Command line completion
483 Command line completion
484 +++++++++++++++++++++++
484 +++++++++++++++++++++++
485
485
486 At any time, hitting TAB will complete any available python commands or
486 At any time, hitting TAB will complete any available python commands or
487 variable names, and show you a list of the possible completions if
487 variable names, and show you a list of the possible completions if
488 there's no unambiguous one. It will also complete filenames in the
488 there's no unambiguous one. It will also complete filenames in the
489 current directory if no python names match what you've typed so far.
489 current directory if no python names match what you've typed so far.
490
490
491
491
492 Search command history
492 Search command history
493 ++++++++++++++++++++++
493 ++++++++++++++++++++++
494
494
495 IPython provides two ways for searching through previous input and thus
495 IPython provides two ways for searching through previous input and thus
496 reduce the need for repetitive typing:
496 reduce the need for repetitive typing:
497
497
498 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
498 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
499 (next,down) to search through only the history items that match
499 (next,down) to search through only the history items that match
500 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
500 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
501 prompt, they just behave like normal arrow keys.
501 prompt, they just behave like normal arrow keys.
502 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
502 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
503 searches your history for lines that contain what you've typed so
503 searches your history for lines that contain what you've typed so
504 far, completing as much as it can.
504 far, completing as much as it can.
505
505
506
506
507 Persistent command history across sessions
507 Persistent command history across sessions
508 ++++++++++++++++++++++++++++++++++++++++++
508 ++++++++++++++++++++++++++++++++++++++++++
509
509
510 IPython will save your input history when it leaves and reload it next
510 IPython will save your input history when it leaves and reload it next
511 time you restart it. By default, the history file is named
511 time you restart it. By default, the history file is named
512 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
512 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
513 separate histories related to various tasks: commands related to
513 separate histories related to various tasks: commands related to
514 numerical work will not be clobbered by a system shell history, for
514 numerical work will not be clobbered by a system shell history, for
515 example.
515 example.
516
516
517
517
518 Autoindent
518 Autoindent
519 ++++++++++
519 ++++++++++
520
520
521 IPython can recognize lines ending in ':' and indent the next line,
521 IPython can recognize lines ending in ':' and indent the next line,
522 while also un-indenting automatically after 'raise' or 'return'.
522 while also un-indenting automatically after 'raise' or 'return'.
523
523
524 This feature uses the readline library, so it will honor your
524 This feature uses the readline library, so it will honor your
525 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
525 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
526 to). Adding the following lines to your :file:`.inputrc` file can make
526 to). Adding the following lines to your :file:`.inputrc` file can make
527 indenting/unindenting more convenient (M-i indents, M-u unindents)::
527 indenting/unindenting more convenient (M-i indents, M-u unindents)::
528
528
529 $if Python
529 $if Python
530 "\M-i": " "
530 "\M-i": " "
531 "\M-u": "\d\d\d\d"
531 "\M-u": "\d\d\d\d"
532 $endif
532 $endif
533
533
534 Note that there are 4 spaces between the quote marks after "M-i" above.
534 Note that there are 4 spaces between the quote marks after "M-i" above.
535
535
536 .. warning::
536 .. warning::
537
537
538 Setting the above indents will cause problems with unicode text entry in
538 Setting the above indents will cause problems with unicode text entry in
539 the terminal.
539 the terminal.
540
540
541 .. warning::
541 .. warning::
542
542
543 Autoindent is ON by default, but it can cause problems with the pasting of
543 Autoindent is ON by default, but it can cause problems with the pasting of
544 multi-line indented code (the pasted code gets re-indented on each line). A
544 multi-line indented code (the pasted code gets re-indented on each line). A
545 magic function %autoindent allows you to toggle it on/off at runtime. You
545 magic function %autoindent allows you to toggle it on/off at runtime. You
546 can also disable it permanently on in your :file:`ipython_config.py` file
546 can also disable it permanently on in your :file:`ipython_config.py` file
547 (set TerminalInteractiveShell.autoindent=False).
547 (set TerminalInteractiveShell.autoindent=False).
548
548
549 If you want to paste multiple lines in the terminal, it is recommended that
549 If you want to paste multiple lines in the terminal, it is recommended that
550 you use ``%paste``.
550 you use ``%paste``.
551
551
552
552
553 Customizing readline behavior
553 Customizing readline behavior
554 +++++++++++++++++++++++++++++
554 +++++++++++++++++++++++++++++
555
555
556 All these features are based on the GNU readline library, which has an
556 All these features are based on the GNU readline library, which has an
557 extremely customizable interface. Normally, readline is configured via a
557 extremely customizable interface. Normally, readline is configured via a
558 file which defines the behavior of the library; the details of the
558 file which defines the behavior of the library; the details of the
559 syntax for this can be found in the readline documentation available
559 syntax for this can be found in the readline documentation available
560 with your system or on the Internet. IPython doesn't read this file (if
560 with your system or on the Internet. IPython doesn't read this file (if
561 it exists) directly, but it does support passing to readline valid
561 it exists) directly, but it does support passing to readline valid
562 options via a simple interface. In brief, you can customize readline by
562 options via a simple interface. In brief, you can customize readline by
563 setting the following options in your configuration file (note
563 setting the following options in your configuration file (note
564 that these options can not be specified at the command line):
564 that these options can not be specified at the command line):
565
565
566 * **readline_parse_and_bind**: this holds a list of strings to be executed
566 * **readline_parse_and_bind**: this holds a list of strings to be executed
567 via a readline.parse_and_bind() command. The syntax for valid commands
567 via a readline.parse_and_bind() command. The syntax for valid commands
568 of this kind can be found by reading the documentation for the GNU
568 of this kind can be found by reading the documentation for the GNU
569 readline library, as these commands are of the kind which readline
569 readline library, as these commands are of the kind which readline
570 accepts in its configuration file.
570 accepts in its configuration file.
571 * **readline_remove_delims**: a string of characters to be removed
571 * **readline_remove_delims**: a string of characters to be removed
572 from the default word-delimiters list used by readline, so that
572 from the default word-delimiters list used by readline, so that
573 completions may be performed on strings which contain them. Do not
573 completions may be performed on strings which contain them. Do not
574 change the default value unless you know what you're doing.
574 change the default value unless you know what you're doing.
575
575
576 You will find the default values in your configuration file.
576 You will find the default values in your configuration file.
577
577
578
578
579 Session logging and restoring
579 Session logging and restoring
580 -----------------------------
580 -----------------------------
581
581
582 You can log all input from a session either by starting IPython with the
582 You can log all input from a session either by starting IPython with the
583 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
583 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
584 or by activating the logging at any moment with the magic function %logstart.
584 or by activating the logging at any moment with the magic function %logstart.
585
585
586 Log files can later be reloaded by running them as scripts and IPython
586 Log files can later be reloaded by running them as scripts and IPython
587 will attempt to 'replay' the log by executing all the lines in it, thus
587 will attempt to 'replay' the log by executing all the lines in it, thus
588 restoring the state of a previous session. This feature is not quite
588 restoring the state of a previous session. This feature is not quite
589 perfect, but can still be useful in many cases.
589 perfect, but can still be useful in many cases.
590
590
591 The log files can also be used as a way to have a permanent record of
591 The log files can also be used as a way to have a permanent record of
592 any code you wrote while experimenting. Log files are regular text files
592 any code you wrote while experimenting. Log files are regular text files
593 which you can later open in your favorite text editor to extract code or
593 which you can later open in your favorite text editor to extract code or
594 to 'clean them up' before using them to replay a session.
594 to 'clean them up' before using them to replay a session.
595
595
596 The `%logstart` function for activating logging in mid-session is used as
596 The `%logstart` function for activating logging in mid-session is used as
597 follows::
597 follows::
598
598
599 %logstart [log_name [log_mode]]
599 %logstart [log_name [log_mode]]
600
600
601 If no name is given, it defaults to a file named 'ipython_log.py' in your
601 If no name is given, it defaults to a file named 'ipython_log.py' in your
602 current working directory, in 'rotate' mode (see below).
602 current working directory, in 'rotate' mode (see below).
603
603
604 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
604 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
605 history up to that point and then continues logging.
605 history up to that point and then continues logging.
606
606
607 %logstart takes a second optional parameter: logging mode. This can be
607 %logstart takes a second optional parameter: logging mode. This can be
608 one of (note that the modes are given unquoted):
608 one of (note that the modes are given unquoted):
609
609
610 * [over:] overwrite existing log_name.
610 * [over:] overwrite existing log_name.
611 * [backup:] rename (if exists) to log_name~ and start log_name.
611 * [backup:] rename (if exists) to log_name~ and start log_name.
612 * [append:] well, that says it.
612 * [append:] well, that says it.
613 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
613 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
614
614
615 The %logoff and %logon functions allow you to temporarily stop and
615 The %logoff and %logon functions allow you to temporarily stop and
616 resume logging to a file which had previously been started with
616 resume logging to a file which had previously been started with
617 %logstart. They will fail (with an explanation) if you try to use them
617 %logstart. They will fail (with an explanation) if you try to use them
618 before logging has been started.
618 before logging has been started.
619
619
620 .. _system_shell_access:
620 .. _system_shell_access:
621
621
622 System shell access
622 System shell access
623 -------------------
623 -------------------
624
624
625 Any input line beginning with a ! character is passed verbatim (minus
625 Any input line beginning with a ! character is passed verbatim (minus
626 the !, of course) to the underlying operating system. For example,
626 the !, of course) to the underlying operating system. For example,
627 typing ``!ls`` will run 'ls' in the current directory.
627 typing ``!ls`` will run 'ls' in the current directory.
628
628
629 Manual capture of command output
629 Manual capture of command output
630 --------------------------------
630 --------------------------------
631
631
632 You can assign the result of a system command to a Python variable with the
632 You can assign the result of a system command to a Python variable with the
633 syntax ``myfiles = !ls``. This gets machine readable output from stdout
633 syntax ``myfiles = !ls``. This gets machine readable output from stdout
634 (e.g. without colours), and splits on newlines. To explicitly get this sort of
634 (e.g. without colours), and splits on newlines. To explicitly get this sort of
635 output without assigning to a variable, use two exclamation marks (``!!ls``) or
635 output without assigning to a variable, use two exclamation marks (``!!ls``) or
636 the ``%sx`` magic command.
636 the ``%sx`` magic command.
637
637
638 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
638 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
639 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
639 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
640 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
640 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
641 See :ref:`string_lists` for details.
641 See :ref:`string_lists` for details.
642
642
643 IPython also allows you to expand the value of python variables when
643 IPython also allows you to expand the value of python variables when
644 making system calls. Wrap variables or expressions in {braces}::
644 making system calls. Wrap variables or expressions in {braces}::
645
645
646 In [1]: pyvar = 'Hello world'
646 In [1]: pyvar = 'Hello world'
647 In [2]: !echo "A python variable: {pyvar}"
647 In [2]: !echo "A python variable: {pyvar}"
648 A python variable: Hello world
648 A python variable: Hello world
649 In [3]: import math
649 In [3]: import math
650 In [4]: x = 8
650 In [4]: x = 8
651 In [5]: !echo {math.factorial(x)}
651 In [5]: !echo {math.factorial(x)}
652 40320
652 40320
653
653
654 For simple cases, you can alternatively prepend $ to a variable name::
654 For simple cases, you can alternatively prepend $ to a variable name::
655
655
656 In [6]: !echo $sys.argv
656 In [6]: !echo $sys.argv
657 [/home/fperez/usr/bin/ipython]
657 [/home/fperez/usr/bin/ipython]
658 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
658 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
659 A system variable: /home/fperez
659 A system variable: /home/fperez
660
660
661 System command aliases
661 System command aliases
662 ----------------------
662 ----------------------
663
663
664 The %alias magic function allows you to define magic functions which are in fact
664 The %alias magic function allows you to define magic functions which are in fact
665 system shell commands. These aliases can have parameters.
665 system shell commands. These aliases can have parameters.
666
666
667 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
667 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
668
668
669 Then, typing ``alias_name params`` will execute the system command 'cmd
669 Then, typing ``alias_name params`` will execute the system command 'cmd
670 params' (from your underlying operating system).
670 params' (from your underlying operating system).
671
671
672 You can also define aliases with parameters using %s specifiers (one per
672 You can also define aliases with parameters using %s specifiers (one per
673 parameter). The following example defines the parts function as an
673 parameter). The following example defines the parts function as an
674 alias to the command 'echo first %s second %s' where each %s will be
674 alias to the command 'echo first %s second %s' where each %s will be
675 replaced by a positional parameter to the call to %parts::
675 replaced by a positional parameter to the call to %parts::
676
676
677 In [1]: %alias parts echo first %s second %s
677 In [1]: %alias parts echo first %s second %s
678 In [2]: parts A B
678 In [2]: parts A B
679 first A second B
679 first A second B
680 In [3]: parts A
680 In [3]: parts A
681 ERROR: Alias <parts> requires 2 arguments, 1 given.
681 ERROR: Alias <parts> requires 2 arguments, 1 given.
682
682
683 If called with no parameters, %alias prints the table of currently
683 If called with no parameters, %alias prints the table of currently
684 defined aliases.
684 defined aliases.
685
685
686 The %rehashx magic allows you to load your entire $PATH as
686 The %rehashx magic allows you to load your entire $PATH as
687 ipython aliases. See its docstring for further details.
687 ipython aliases. See its docstring for further details.
688
688
689
689
690 .. _dreload:
690 .. _dreload:
691
691
692 Recursive reload
692 Recursive reload
693 ----------------
693 ----------------
694
694
695 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
695 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
696 module: changes made to any of its dependencies will be reloaded without
696 module: changes made to any of its dependencies will be reloaded without
697 having to exit. To start using it, do::
697 having to exit. To start using it, do::
698
698
699 from IPython.lib.deepreload import reload as dreload
699 from IPython.lib.deepreload import reload as dreload
700
700
701
701
702 Verbose and colored exception traceback printouts
702 Verbose and colored exception traceback printouts
703 -------------------------------------------------
703 -------------------------------------------------
704
704
705 IPython provides the option to see very detailed exception tracebacks,
705 IPython provides the option to see very detailed exception tracebacks,
706 which can be especially useful when debugging large programs. You can
706 which can be especially useful when debugging large programs. You can
707 run any Python file with the %run function to benefit from these
707 run any Python file with the %run function to benefit from these
708 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
708 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
709 be colored (if your terminal supports it) which makes them much easier
709 be colored (if your terminal supports it) which makes them much easier
710 to parse visually.
710 to parse visually.
711
711
712 See the magic xmode and colors functions for details (just type %magic).
712 See the magic xmode and colors functions for details (just type %magic).
713
713
714 These features are basically a terminal version of Ka-Ping Yee's cgitb
714 These features are basically a terminal version of Ka-Ping Yee's cgitb
715 module, now part of the standard Python library.
715 module, now part of the standard Python library.
716
716
717
717
718 .. _input_caching:
718 .. _input_caching:
719
719
720 Input caching system
720 Input caching system
721 --------------------
721 --------------------
722
722
723 IPython offers numbered prompts (In/Out) with input and output caching
723 IPython offers numbered prompts (In/Out) with input and output caching
724 (also referred to as 'input history'). All input is saved and can be
724 (also referred to as 'input history'). All input is saved and can be
725 retrieved as variables (besides the usual arrow key recall), in
725 retrieved as variables (besides the usual arrow key recall), in
726 addition to the %rep magic command that brings a history entry
726 addition to the %rep magic command that brings a history entry
727 up for editing on the next command line.
727 up for editing on the next command line.
728
728
729 The following GLOBAL variables always exist (so don't overwrite them!):
729 The following GLOBAL variables always exist (so don't overwrite them!):
730
730
731 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
731 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
732 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
732 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
733 overwrite In with a variable of your own, you can remake the assignment to the
733 overwrite In with a variable of your own, you can remake the assignment to the
734 internal list with a simple ``In=_ih``.
734 internal list with a simple ``In=_ih``.
735
735
736 Additionally, global variables named _i<n> are dynamically created (<n>
736 Additionally, global variables named _i<n> are dynamically created (<n>
737 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
737 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
738
738
739 For example, what you typed at prompt 14 is available as _i14, _ih[14]
739 For example, what you typed at prompt 14 is available as _i14, _ih[14]
740 and In[14].
740 and In[14].
741
741
742 This allows you to easily cut and paste multi line interactive prompts
742 This allows you to easily cut and paste multi line interactive prompts
743 by printing them out: they print like a clean string, without prompt
743 by printing them out: they print like a clean string, without prompt
744 characters. You can also manipulate them like regular variables (they
744 characters. You can also manipulate them like regular variables (they
745 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
745 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
746 contents of input prompt 9.
746 contents of input prompt 9.
747
747
748 You can also re-execute multiple lines of input easily by using the
748 You can also re-execute multiple lines of input easily by using the
749 magic %rerun or %macro functions. The macro system also allows you to re-execute
749 magic %rerun or %macro functions. The macro system also allows you to re-execute
750 previous lines which include magic function calls (which require special
750 previous lines which include magic function calls (which require special
751 processing). Type %macro? for more details on the macro system.
751 processing). Type %macro? for more details on the macro system.
752
752
753 A history function %hist allows you to see any part of your input
753 A history function %hist allows you to see any part of your input
754 history by printing a range of the _i variables.
754 history by printing a range of the _i variables.
755
755
756 You can also search ('grep') through your history by typing
756 You can also search ('grep') through your history by typing
757 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
757 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
758 etc. You can bring history entries listed by '%hist -g' up for editing
758 etc. You can bring history entries listed by '%hist -g' up for editing
759 with the %recall command, or run them immediately with %rerun.
759 with the %recall command, or run them immediately with %rerun.
760
760
761 .. _output_caching:
761 .. _output_caching:
762
762
763 Output caching system
763 Output caching system
764 ---------------------
764 ---------------------
765
765
766 For output that is returned from actions, a system similar to the input
766 For output that is returned from actions, a system similar to the input
767 cache exists but using _ instead of _i. Only actions that produce a
767 cache exists but using _ instead of _i. Only actions that produce a
768 result (NOT assignments, for example) are cached. If you are familiar
768 result (NOT assignments, for example) are cached. If you are familiar
769 with Mathematica, IPython's _ variables behave exactly like
769 with Mathematica, IPython's _ variables behave exactly like
770 Mathematica's % variables.
770 Mathematica's % variables.
771
771
772 The following GLOBAL variables always exist (so don't overwrite them!):
772 The following GLOBAL variables always exist (so don't overwrite them!):
773
773
774 * [_] (a single underscore) : stores previous output, like Python's
774 * [_] (a single underscore) : stores previous output, like Python's
775 default interpreter.
775 default interpreter.
776 * [__] (two underscores): next previous.
776 * [__] (two underscores): next previous.
777 * [___] (three underscores): next-next previous.
777 * [___] (three underscores): next-next previous.
778
778
779 Additionally, global variables named _<n> are dynamically created (<n>
779 Additionally, global variables named _<n> are dynamically created (<n>
780 being the prompt counter), such that the result of output <n> is always
780 being the prompt counter), such that the result of output <n> is always
781 available as _<n> (don't use the angle brackets, just the number, e.g.
781 available as _<n> (don't use the angle brackets, just the number, e.g.
782 _21).
782 _21).
783
783
784 These variables are also stored in a global dictionary (not a
784 These variables are also stored in a global dictionary (not a
785 list, since it only has entries for lines which returned a result)
785 list, since it only has entries for lines which returned a result)
786 available under the names _oh and Out (similar to _ih and In). So the
786 available under the names _oh and Out (similar to _ih and In). So the
787 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
787 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
788 accidentally overwrite the Out variable you can recover it by typing
788 accidentally overwrite the Out variable you can recover it by typing
789 'Out=_oh' at the prompt.
789 'Out=_oh' at the prompt.
790
790
791 This system obviously can potentially put heavy memory demands on your
791 This system obviously can potentially put heavy memory demands on your
792 system, since it prevents Python's garbage collector from removing any
792 system, since it prevents Python's garbage collector from removing any
793 previously computed results. You can control how many results are kept
793 previously computed results. You can control how many results are kept
794 in memory with the option (at the command line or in your configuration
794 in memory with the option (at the command line or in your configuration
795 file) cache_size. If you set it to 0, the whole system is completely
795 file) cache_size. If you set it to 0, the whole system is completely
796 disabled and the prompts revert to the classic '>>>' of normal Python.
796 disabled and the prompts revert to the classic '>>>' of normal Python.
797
797
798
798
799 Directory history
799 Directory history
800 -----------------
800 -----------------
801
801
802 Your history of visited directories is kept in the global list _dh, and
802 Your history of visited directories is kept in the global list _dh, and
803 the magic %cd command can be used to go to any entry in that list. The
803 the magic %cd command can be used to go to any entry in that list. The
804 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
804 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
805 conveniently view the directory history.
805 conveniently view the directory history.
806
806
807
807
808 Automatic parentheses and quotes
808 Automatic parentheses and quotes
809 --------------------------------
809 --------------------------------
810
810
811 These features were adapted from Nathan Gray's LazyPython. They are
811 These features were adapted from Nathan Gray's LazyPython. They are
812 meant to allow less typing for common situations.
812 meant to allow less typing for common situations.
813
813
814
814
815 Automatic parentheses
815 Automatic parentheses
816 +++++++++++++++++++++
816 +++++++++++++++++++++
817
817
818 Callable objects (i.e. functions, methods, etc) can be invoked like this
818 Callable objects (i.e. functions, methods, etc) can be invoked like this
819 (notice the commas between the arguments)::
819 (notice the commas between the arguments)::
820
820
821 In [1]: callable_ob arg1, arg2, arg3
821 In [1]: callable_ob arg1, arg2, arg3
822 ------> callable_ob(arg1, arg2, arg3)
822 ------> callable_ob(arg1, arg2, arg3)
823
823
824 You can force automatic parentheses by using '/' as the first character
824 You can force automatic parentheses by using '/' as the first character
825 of a line. For example::
825 of a line. For example::
826
826
827 In [2]: /globals # becomes 'globals()'
827 In [2]: /globals # becomes 'globals()'
828
828
829 Note that the '/' MUST be the first character on the line! This won't work::
829 Note that the '/' MUST be the first character on the line! This won't work::
830
830
831 In [3]: print /globals # syntax error
831 In [3]: print /globals # syntax error
832
832
833 In most cases the automatic algorithm should work, so you should rarely
833 In most cases the automatic algorithm should work, so you should rarely
834 need to explicitly invoke /. One notable exception is if you are trying
834 need to explicitly invoke /. One notable exception is if you are trying
835 to call a function with a list of tuples as arguments (the parenthesis
835 to call a function with a list of tuples as arguments (the parenthesis
836 will confuse IPython)::
836 will confuse IPython)::
837
837
838 In [4]: zip (1,2,3),(4,5,6) # won't work
838 In [4]: zip (1,2,3),(4,5,6) # won't work
839
839
840 but this will work::
840 but this will work::
841
841
842 In [5]: /zip (1,2,3),(4,5,6)
842 In [5]: /zip (1,2,3),(4,5,6)
843 ------> zip ((1,2,3),(4,5,6))
843 ------> zip ((1,2,3),(4,5,6))
844 Out[5]: [(1, 4), (2, 5), (3, 6)]
844 Out[5]: [(1, 4), (2, 5), (3, 6)]
845
845
846 IPython tells you that it has altered your command line by displaying
846 IPython tells you that it has altered your command line by displaying
847 the new command line preceded by ->. e.g.::
847 the new command line preceded by ->. e.g.::
848
848
849 In [6]: callable list
849 In [6]: callable list
850 ------> callable(list)
850 ------> callable(list)
851
851
852
852
853 Automatic quoting
853 Automatic quoting
854 +++++++++++++++++
854 +++++++++++++++++
855
855
856 You can force automatic quoting of a function's arguments by using ','
856 You can force automatic quoting of a function's arguments by using ','
857 or ';' as the first character of a line. For example::
857 or ';' as the first character of a line. For example::
858
858
859 In [1]: ,my_function /home/me # becomes my_function("/home/me")
859 In [1]: ,my_function /home/me # becomes my_function("/home/me")
860
860
861 If you use ';' the whole argument is quoted as a single string, while ',' splits
861 If you use ';' the whole argument is quoted as a single string, while ',' splits
862 on whitespace::
862 on whitespace::
863
863
864 In [2]: ,my_function a b c # becomes my_function("a","b","c")
864 In [2]: ,my_function a b c # becomes my_function("a","b","c")
865
865
866 In [3]: ;my_function a b c # becomes my_function("a b c")
866 In [3]: ;my_function a b c # becomes my_function("a b c")
867
867
868 Note that the ',' or ';' MUST be the first character on the line! This
868 Note that the ',' or ';' MUST be the first character on the line! This
869 won't work::
869 won't work::
870
870
871 In [4]: x = ,my_function /home/me # syntax error
871 In [4]: x = ,my_function /home/me # syntax error
872
872
873 IPython as your default Python environment
873 IPython as your default Python environment
874 ==========================================
874 ==========================================
875
875
876 Python honors the environment variable PYTHONSTARTUP and will execute at
876 Python honors the environment variable PYTHONSTARTUP and will execute at
877 startup the file referenced by this variable. If you put the following code at
877 startup the file referenced by this variable. If you put the following code at
878 the end of that file, then IPython will be your working environment anytime you
878 the end of that file, then IPython will be your working environment anytime you
879 start Python::
879 start Python::
880
880
881 from IPython.frontend.terminal.ipapp import launch_new_instance
881 from IPython.frontend.terminal.ipapp import launch_new_instance
882 launch_new_instance()
882 launch_new_instance()
883 raise SystemExit
883 raise SystemExit
884
884
885 The ``raise SystemExit`` is needed to exit Python when
885 The ``raise SystemExit`` is needed to exit Python when
886 it finishes, otherwise you'll be back at the normal Python '>>>'
886 it finishes, otherwise you'll be back at the normal Python '>>>'
887 prompt.
887 prompt.
888
888
889 This is probably useful to developers who manage multiple Python
889 This is probably useful to developers who manage multiple Python
890 versions and don't want to have correspondingly multiple IPython
890 versions and don't want to have correspondingly multiple IPython
891 versions. Note that in this mode, there is no way to pass IPython any
891 versions. Note that in this mode, there is no way to pass IPython any
892 command-line options, as those are trapped first by Python itself.
892 command-line options, as those are trapped first by Python itself.
893
893
894 .. _Embedding:
894 .. _Embedding:
895
895
896 Embedding IPython
896 Embedding IPython
897 =================
897 =================
898
898
899 It is possible to start an IPython instance inside your own Python
899 It is possible to start an IPython instance inside your own Python
900 programs. This allows you to evaluate dynamically the state of your
900 programs. This allows you to evaluate dynamically the state of your
901 code, operate with your variables, analyze them, etc. Note however that
901 code, operate with your variables, analyze them, etc. Note however that
902 any changes you make to values while in the shell do not propagate back
902 any changes you make to values while in the shell do not propagate back
903 to the running code, so it is safe to modify your values because you
903 to the running code, so it is safe to modify your values because you
904 won't break your code in bizarre ways by doing so.
904 won't break your code in bizarre ways by doing so.
905
905
906 .. note::
906 .. note::
907
907
908 At present, trying to embed IPython from inside IPython causes problems. Run
908 At present, trying to embed IPython from inside IPython causes problems. Run
909 the code samples below outside IPython.
909 the code samples below outside IPython.
910
910
911 This feature allows you to easily have a fully functional python
911 This feature allows you to easily have a fully functional python
912 environment for doing object introspection anywhere in your code with a
912 environment for doing object introspection anywhere in your code with a
913 simple function call. In some cases a simple print statement is enough,
913 simple function call. In some cases a simple print statement is enough,
914 but if you need to do more detailed analysis of a code fragment this
914 but if you need to do more detailed analysis of a code fragment this
915 feature can be very valuable.
915 feature can be very valuable.
916
916
917 It can also be useful in scientific computing situations where it is
917 It can also be useful in scientific computing situations where it is
918 common to need to do some automatic, computationally intensive part and
918 common to need to do some automatic, computationally intensive part and
919 then stop to look at data, plots, etc.
919 then stop to look at data, plots, etc.
920 Opening an IPython instance will give you full access to your data and
920 Opening an IPython instance will give you full access to your data and
921 functions, and you can resume program execution once you are done with
921 functions, and you can resume program execution once you are done with
922 the interactive part (perhaps to stop again later, as many times as
922 the interactive part (perhaps to stop again later, as many times as
923 needed).
923 needed).
924
924
925 The following code snippet is the bare minimum you need to include in
925 The following code snippet is the bare minimum you need to include in
926 your Python programs for this to work (detailed examples follow later)::
926 your Python programs for this to work (detailed examples follow later)::
927
927
928 from IPython import embed
928 from IPython import embed
929
929
930 embed() # this call anywhere in your program will start IPython
930 embed() # this call anywhere in your program will start IPython
931
931
932 You can run embedded instances even in code which is itself being run at
932 You can run embedded instances even in code which is itself being run at
933 the IPython interactive prompt with '%run <filename>'. Since it's easy
933 the IPython interactive prompt with '%run <filename>'. Since it's easy
934 to get lost as to where you are (in your top-level IPython or in your
934 to get lost as to where you are (in your top-level IPython or in your
935 embedded one), it's a good idea in such cases to set the in/out prompts
935 embedded one), it's a good idea in such cases to set the in/out prompts
936 to something different for the embedded instances. The code examples
936 to something different for the embedded instances. The code examples
937 below illustrate this.
937 below illustrate this.
938
938
939 You can also have multiple IPython instances in your program and open
939 You can also have multiple IPython instances in your program and open
940 them separately, for example with different options for data
940 them separately, for example with different options for data
941 presentation. If you close and open the same instance multiple times,
941 presentation. If you close and open the same instance multiple times,
942 its prompt counters simply continue from each execution to the next.
942 its prompt counters simply continue from each execution to the next.
943
943
944 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
944 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
945 module for more details on the use of this system.
945 module for more details on the use of this system.
946
946
947 The following sample file illustrating how to use the embedding
947 The following sample file illustrating how to use the embedding
948 functionality is provided in the examples directory as example-embed.py.
948 functionality is provided in the examples directory as example-embed.py.
949 It should be fairly self-explanatory:
949 It should be fairly self-explanatory:
950
950
951 .. literalinclude:: ../../examples/core/example-embed.py
951 .. literalinclude:: ../../examples/core/example-embed.py
952 :language: python
952 :language: python
953
953
954 Once you understand how the system functions, you can use the following
954 Once you understand how the system functions, you can use the following
955 code fragments in your programs which are ready for cut and paste:
955 code fragments in your programs which are ready for cut and paste:
956
956
957 .. literalinclude:: ../../examples/core/example-embed-short.py
957 .. literalinclude:: ../../examples/core/example-embed-short.py
958 :language: python
958 :language: python
959
959
960 Using the Python debugger (pdb)
960 Using the Python debugger (pdb)
961 ===============================
961 ===============================
962
962
963 Running entire programs via pdb
963 Running entire programs via pdb
964 -------------------------------
964 -------------------------------
965
965
966 pdb, the Python debugger, is a powerful interactive debugger which
966 pdb, the Python debugger, is a powerful interactive debugger which
967 allows you to step through code, set breakpoints, watch variables,
967 allows you to step through code, set breakpoints, watch variables,
968 etc. IPython makes it very easy to start any script under the control
968 etc. IPython makes it very easy to start any script under the control
969 of pdb, regardless of whether you have wrapped it into a 'main()'
969 of pdb, regardless of whether you have wrapped it into a 'main()'
970 function or not. For this, simply type '%run -d myscript' at an
970 function or not. For this, simply type '%run -d myscript' at an
971 IPython prompt. See the %run command's documentation (via '%run?' or
971 IPython prompt. See the %run command's documentation (via '%run?' or
972 in Sec. magic_ for more details, including how to control where pdb
972 in Sec. magic_ for more details, including how to control where pdb
973 will stop execution first.
973 will stop execution first.
974
974
975 For more information on the use of the pdb debugger, read the included
975 For more information on the use of the pdb debugger, read the included
976 pdb.doc file (part of the standard Python distribution). On a stock
976 pdb.doc file (part of the standard Python distribution). On a stock
977 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
977 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
978 easiest way to read it is by using the help() function of the pdb module
978 easiest way to read it is by using the help() function of the pdb module
979 as follows (in an IPython prompt)::
979 as follows (in an IPython prompt)::
980
980
981 In [1]: import pdb
981 In [1]: import pdb
982 In [2]: pdb.help()
982 In [2]: pdb.help()
983
983
984 This will load the pdb.doc document in a file viewer for you automatically.
984 This will load the pdb.doc document in a file viewer for you automatically.
985
985
986
986
987 Automatic invocation of pdb on exceptions
987 Automatic invocation of pdb on exceptions
988 -----------------------------------------
988 -----------------------------------------
989
989
990 IPython, if started with the ``--pdb`` option (or if the option is set in
990 IPython, if started with the ``--pdb`` option (or if the option is set in
991 your config file) can call the Python pdb debugger every time your code
991 your config file) can call the Python pdb debugger every time your code
992 triggers an uncaught exception. This feature
992 triggers an uncaught exception. This feature
993 can also be toggled at any time with the %pdb magic command. This can be
993 can also be toggled at any time with the %pdb magic command. This can be
994 extremely useful in order to find the origin of subtle bugs, because pdb
994 extremely useful in order to find the origin of subtle bugs, because pdb
995 opens up at the point in your code which triggered the exception, and
995 opens up at the point in your code which triggered the exception, and
996 while your program is at this point 'dead', all the data is still
996 while your program is at this point 'dead', all the data is still
997 available and you can walk up and down the stack frame and understand
997 available and you can walk up and down the stack frame and understand
998 the origin of the problem.
998 the origin of the problem.
999
999
1000 Furthermore, you can use these debugging facilities both with the
1000 Furthermore, you can use these debugging facilities both with the
1001 embedded IPython mode and without IPython at all. For an embedded shell
1001 embedded IPython mode and without IPython at all. For an embedded shell
1002 (see sec. Embedding_), simply call the constructor with
1002 (see sec. Embedding_), simply call the constructor with
1003 ``--pdb`` in the argument string and pdb will automatically be called if an
1003 ``--pdb`` in the argument string and pdb will automatically be called if an
1004 uncaught exception is triggered by your code.
1004 uncaught exception is triggered by your code.
1005
1005
1006 For stand-alone use of the feature in your programs which do not use
1006 For stand-alone use of the feature in your programs which do not use
1007 IPython at all, put the following lines toward the top of your 'main'
1007 IPython at all, put the following lines toward the top of your 'main'
1008 routine::
1008 routine::
1009
1009
1010 import sys
1010 import sys
1011 from IPython.core import ultratb
1011 from IPython.core import ultratb
1012 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1012 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1013 color_scheme='Linux', call_pdb=1)
1013 color_scheme='Linux', call_pdb=1)
1014
1014
1015 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1015 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1016 detailed or normal tracebacks respectively. The color_scheme keyword can
1016 detailed or normal tracebacks respectively. The color_scheme keyword can
1017 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1017 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1018 options which can be set in IPython with ``--colors`` and ``--xmode``.
1018 options which can be set in IPython with ``--colors`` and ``--xmode``.
1019
1019
1020 This will give any of your programs detailed, colored tracebacks with
1020 This will give any of your programs detailed, colored tracebacks with
1021 automatic invocation of pdb.
1021 automatic invocation of pdb.
1022
1022
1023
1023
1024 Extensions for syntax processing
1024 Extensions for syntax processing
1025 ================================
1025 ================================
1026
1026
1027 This isn't for the faint of heart, because the potential for breaking
1027 This isn't for the faint of heart, because the potential for breaking
1028 things is quite high. But it can be a very powerful and useful feature.
1028 things is quite high. But it can be a very powerful and useful feature.
1029 In a nutshell, you can redefine the way IPython processes the user input
1029 In a nutshell, you can redefine the way IPython processes the user input
1030 line to accept new, special extensions to the syntax without needing to
1030 line to accept new, special extensions to the syntax without needing to
1031 change any of IPython's own code.
1031 change any of IPython's own code.
1032
1032
1033 In the IPython/extensions directory you will find some examples
1033 In the IPython/extensions directory you will find some examples
1034 supplied, which we will briefly describe now. These can be used 'as is'
1034 supplied, which we will briefly describe now. These can be used 'as is'
1035 (and both provide very useful functionality), or you can use them as a
1035 (and both provide very useful functionality), or you can use them as a
1036 starting point for writing your own extensions.
1036 starting point for writing your own extensions.
1037
1037
1038 .. _pasting_with_prompts:
1038 .. _pasting_with_prompts:
1039
1039
1040 Pasting of code starting with Python or IPython prompts
1040 Pasting of code starting with Python or IPython prompts
1041 -------------------------------------------------------
1041 -------------------------------------------------------
1042
1042
1043 IPython is smart enough to filter out input prompts, be they plain Python ones
1043 IPython is smart enough to filter out input prompts, be they plain Python ones
1044 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can
1044 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can
1045 therefore copy and paste from existing interactive sessions without worry.
1045 therefore copy and paste from existing interactive sessions without worry.
1046
1046
1047 The following is a 'screenshot' of how things work, copying an example from the
1047 The following is a 'screenshot' of how things work, copying an example from the
1048 standard Python tutorial::
1048 standard Python tutorial::
1049
1049
1050 In [1]: >>> # Fibonacci series:
1050 In [1]: >>> # Fibonacci series:
1051
1051
1052 In [2]: ... # the sum of two elements defines the next
1052 In [2]: ... # the sum of two elements defines the next
1053
1053
1054 In [3]: ... a, b = 0, 1
1054 In [3]: ... a, b = 0, 1
1055
1055
1056 In [4]: >>> while b < 10:
1056 In [4]: >>> while b < 10:
1057 ...: ... print b
1057 ...: ... print b
1058 ...: ... a, b = b, a+b
1058 ...: ... a, b = b, a+b
1059 ...:
1059 ...:
1060 1
1060 1
1061 1
1061 1
1062 2
1062 2
1063 3
1063 3
1064 5
1064 5
1065 8
1065 8
1066
1066
1067 And pasting from IPython sessions works equally well::
1067 And pasting from IPython sessions works equally well::
1068
1068
1069 In [1]: In [5]: def f(x):
1069 In [1]: In [5]: def f(x):
1070 ...: ...: "A simple function"
1070 ...: ...: "A simple function"
1071 ...: ...: return x**2
1071 ...: ...: return x**2
1072 ...: ...:
1072 ...: ...:
1073
1073
1074 In [2]: f(3)
1074 In [2]: f(3)
1075 Out[2]: 9
1075 Out[2]: 9
1076
1076
1077 .. _gui_support:
1077 .. _gui_support:
1078
1078
1079 GUI event loop support
1079 GUI event loop support
1080 ======================
1080 ======================
1081
1081
1082 .. versionadded:: 0.11
1082 .. versionadded:: 0.11
1083 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1083 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1084
1084
1085 IPython has excellent support for working interactively with Graphical User
1085 IPython has excellent support for working interactively with Graphical User
1086 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
1086 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
1087 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1087 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1088 is extremely robust compared to our previous thread-based version. The
1088 is extremely robust compared to our previous thread-based version. The
1089 advantages of this are:
1089 advantages of this are:
1090
1090
1091 * GUIs can be enabled and disabled dynamically at runtime.
1091 * GUIs can be enabled and disabled dynamically at runtime.
1092 * The active GUI can be switched dynamically at runtime.
1092 * The active GUI can be switched dynamically at runtime.
1093 * In some cases, multiple GUIs can run simultaneously with no problems.
1093 * In some cases, multiple GUIs can run simultaneously with no problems.
1094 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1094 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1095 all of these things.
1095 all of these things.
1096
1096
1097 For users, enabling GUI event loop integration is simple. You simple use the
1097 For users, enabling GUI event loop integration is simple. You simple use the
1098 ``%gui`` magic as follows::
1098 ``%gui`` magic as follows::
1099
1099
1100 %gui [GUINAME]
1100 %gui [GUINAME]
1101
1101
1102 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1102 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1103 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1103 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1104
1104
1105 Thus, to use wxPython interactively and create a running :class:`wx.App`
1105 Thus, to use wxPython interactively and create a running :class:`wx.App`
1106 object, do::
1106 object, do::
1107
1107
1108 %gui wx
1108 %gui wx
1109
1109
1110 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1110 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1111 see :ref:`this section <matplotlib_support>`.
1111 see :ref:`this section <matplotlib_support>`.
1112
1112
1113 For developers that want to use IPython's GUI event loop integration in the
1113 For developers that want to use IPython's GUI event loop integration in the
1114 form of a library, these capabilities are exposed in library form in the
1114 form of a library, these capabilities are exposed in library form in the
1115 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1115 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1116 Interested developers should see the module docstrings for more information,
1116 Interested developers should see the module docstrings for more information,
1117 but there are a few points that should be mentioned here.
1117 but there are a few points that should be mentioned here.
1118
1118
1119 First, the ``PyOSInputHook`` approach only works in command line settings
1119 First, the ``PyOSInputHook`` approach only works in command line settings
1120 where readline is activated. The integration with various eventloops
1120 where readline is activated. The integration with various eventloops
1121 is handled somewhat differently (and more simply) when using the standalone
1121 is handled somewhat differently (and more simply) when using the standalone
1122 kernel, as in the qtconsole and notebook.
1122 kernel, as in the qtconsole and notebook.
1123
1123
1124 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1124 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1125 *not* start its event loop. Instead all of this is handled by the
1125 *not* start its event loop. Instead all of this is handled by the
1126 ``PyOSInputHook``. This means that applications that are meant to be used both
1126 ``PyOSInputHook``. This means that applications that are meant to be used both
1127 in IPython and as standalone apps need to have special code to detects how the
1127 in IPython and as standalone apps need to have special code to detects how the
1128 application is being run. We highly recommend using IPython's support for this.
1128 application is being run. We highly recommend using IPython's support for this.
1129 Since the details vary slightly between toolkits, we point you to the various
1129 Since the details vary slightly between toolkits, we point you to the various
1130 examples in our source directory :file:`docs/examples/lib` that demonstrate
1130 examples in our source directory :file:`docs/examples/lib` that demonstrate
1131 these capabilities.
1131 these capabilities.
1132
1132
1133 .. warning::
1133 .. warning::
1134
1134
1135 The WX version of this is currently broken. While ``--pylab=wx`` works
1135 The WX version of this is currently broken. While ``--pylab=wx`` works
1136 fine, standalone WX apps do not. See
1136 fine, standalone WX apps do not. See
1137 https://github.com/ipython/ipython/issues/645 for details of our progress on
1137 https://github.com/ipython/ipython/issues/645 for details of our progress on
1138 this issue.
1138 this issue.
1139
1139
1140
1140
1141 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1141 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1142 them with no-ops) the event loops. This is done to allow applications that
1142 them with no-ops) the event loops. This is done to allow applications that
1143 actually need to run the real event loops to do so. This is often needed to
1143 actually need to run the real event loops to do so. This is often needed to
1144 process pending events at critical points.
1144 process pending events at critical points.
1145
1145
1146 Finally, we also have a number of examples in our source directory
1146 Finally, we also have a number of examples in our source directory
1147 :file:`docs/examples/lib` that demonstrate these capabilities.
1147 :file:`docs/examples/lib` that demonstrate these capabilities.
1148
1148
1149 PyQt and PySide
1149 PyQt and PySide
1150 ---------------
1150 ---------------
1151
1151
1152 .. attempt at explanation of the complete mess that is Qt support
1152 .. attempt at explanation of the complete mess that is Qt support
1153
1153
1154 When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either
1154 When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either
1155 PyQt4 or PySide. There are three options for configuration here, because
1155 PyQt4 or PySide. There are three options for configuration here, because
1156 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1156 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1157 Python 2, and the more natural v2, which is the only API supported by PySide.
1157 Python 2, and the more natural v2, which is the only API supported by PySide.
1158 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1158 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1159 uses v2, but you can still use any interface in your code, since the
1159 uses v2, but you can still use any interface in your code, since the
1160 Qt frontend is in a different process.
1160 Qt frontend is in a different process.
1161
1161
1162 The default will be to import PyQt4 without configuration of the APIs, thus
1162 The default will be to import PyQt4 without configuration of the APIs, thus
1163 matching what most applications would expect. It will fall back of PySide if
1163 matching what most applications would expect. It will fall back of PySide if
1164 PyQt4 is unavailable.
1164 PyQt4 is unavailable.
1165
1165
1166 If specified, IPython will respect the environment variable ``QT_API`` used
1166 If specified, IPython will respect the environment variable ``QT_API`` used
1167 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1167 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1168 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1168 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1169 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1169 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1170 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1170 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1171
1171
1172 If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython
1172 If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython
1173 will ask matplotlib which Qt library to use (only if QT_API is *not set*), via
1173 will ask matplotlib which Qt library to use (only if QT_API is *not set*), via
1174 the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then
1174 the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then
1175 IPython will always use PyQt4 without setting the v2 APIs, since neither v2
1175 IPython will always use PyQt4 without setting the v2 APIs, since neither v2
1176 PyQt nor PySide work.
1176 PyQt nor PySide work.
1177
1177
1178 .. warning::
1178 .. warning::
1179
1179
1180 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1180 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1181 to work with IPython's qt integration, because otherwise PyQt4 will be
1181 to work with IPython's qt integration, because otherwise PyQt4 will be
1182 loaded in an incompatible mode.
1182 loaded in an incompatible mode.
1183
1183
1184 It also means that you must *not* have ``QT_API`` set if you want to
1184 It also means that you must *not* have ``QT_API`` set if you want to
1185 use ``--gui=qt`` with code that requires PyQt4 API v1.
1185 use ``--gui=qt`` with code that requires PyQt4 API v1.
1186
1186
1187
1187
1188 .. _matplotlib_support:
1188 .. _matplotlib_support:
1189
1189
1190 Plotting with matplotlib
1190 Plotting with matplotlib
1191 ========================
1191 ========================
1192
1192
1193 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
1193 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
1194 can produce plots on screen using a variety of GUI toolkits, including Tk,
1194 can produce plots on screen using a variety of GUI toolkits, including Tk,
1195 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1195 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1196 scientific computing, all with a syntax compatible with that of the popular
1196 scientific computing, all with a syntax compatible with that of the popular
1197 Matlab program.
1197 Matlab program.
1198
1198
1199 To start IPython with matplotlib support, use the ``--pylab`` switch. If no
1199 To start IPython with matplotlib support, use the ``--pylab`` switch. If no
1200 arguments are given, IPython will automatically detect your choice of
1200 arguments are given, IPython will automatically detect your choice of
1201 matplotlib backend. You can also request a specific backend with
1201 matplotlib backend. You can also request a specific backend with
1202 ``--pylab=backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk',
1202 ``--pylab=backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk',
1203 'osx'.
1203 'osx'.
1204
1204
1205 .. _Matplotlib: http://matplotlib.sourceforge.net
1205 .. _Matplotlib: http://matplotlib.sourceforge.net
1206
1206
1207 .. _interactive_demos:
1207 .. _interactive_demos:
1208
1208
1209 Interactive demos with IPython
1209 Interactive demos with IPython
1210 ==============================
1210 ==============================
1211
1211
1212 IPython ships with a basic system for running scripts interactively in
1212 IPython ships with a basic system for running scripts interactively in
1213 sections, useful when presenting code to audiences. A few tags embedded
1213 sections, useful when presenting code to audiences. A few tags embedded
1214 in comments (so that the script remains valid Python code) divide a file
1214 in comments (so that the script remains valid Python code) divide a file
1215 into separate blocks, and the demo can be run one block at a time, with
1215 into separate blocks, and the demo can be run one block at a time, with
1216 IPython printing (with syntax highlighting) the block before executing
1216 IPython printing (with syntax highlighting) the block before executing
1217 it, and returning to the interactive prompt after each block. The
1217 it, and returning to the interactive prompt after each block. The
1218 interactive namespace is updated after each block is run with the
1218 interactive namespace is updated after each block is run with the
1219 contents of the demo's namespace.
1219 contents of the demo's namespace.
1220
1220
1221 This allows you to show a piece of code, run it and then execute
1221 This allows you to show a piece of code, run it and then execute
1222 interactively commands based on the variables just created. Once you
1222 interactively commands based on the variables just created. Once you
1223 want to continue, you simply execute the next block of the demo. The
1223 want to continue, you simply execute the next block of the demo. The
1224 following listing shows the markup necessary for dividing a script into
1224 following listing shows the markup necessary for dividing a script into
1225 sections for execution as a demo:
1225 sections for execution as a demo:
1226
1226
1227 .. literalinclude:: ../../examples/lib/example-demo.py
1227 .. literalinclude:: ../../examples/lib/example-demo.py
1228 :language: python
1228 :language: python
1229
1229
1230 In order to run a file as a demo, you must first make a Demo object out
1230 In order to run a file as a demo, you must first make a Demo object out
1231 of it. If the file is named myscript.py, the following code will make a
1231 of it. If the file is named myscript.py, the following code will make a
1232 demo::
1232 demo::
1233
1233
1234 from IPython.lib.demo import Demo
1234 from IPython.lib.demo import Demo
1235
1235
1236 mydemo = Demo('myscript.py')
1236 mydemo = Demo('myscript.py')
1237
1237
1238 This creates the mydemo object, whose blocks you run one at a time by
1238 This creates the mydemo object, whose blocks you run one at a time by
1239 simply calling the object with no arguments. If you have autocall active
1239 simply calling the object with no arguments. If you have autocall active
1240 in IPython (the default), all you need to do is type::
1240 in IPython (the default), all you need to do is type::
1241
1241
1242 mydemo
1242 mydemo
1243
1243
1244 and IPython will call it, executing each block. Demo objects can be
1244 and IPython will call it, executing each block. Demo objects can be
1245 restarted, you can move forward or back skipping blocks, re-execute the
1245 restarted, you can move forward or back skipping blocks, re-execute the
1246 last block, etc. Simply use the Tab key on a demo object to see its
1246 last block, etc. Simply use the Tab key on a demo object to see its
1247 methods, and call '?' on them to see their docstrings for more usage
1247 methods, and call '?' on them to see their docstrings for more usage
1248 details. In addition, the demo module itself contains a comprehensive
1248 details. In addition, the demo module itself contains a comprehensive
1249 docstring, which you can access via::
1249 docstring, which you can access via::
1250
1250
1251 from IPython.lib import demo
1251 from IPython.lib import demo
1252
1252
1253 demo?
1253 demo?
1254
1254
1255 Limitations: It is important to note that these demos are limited to
1255 Limitations: It is important to note that these demos are limited to
1256 fairly simple uses. In particular, you cannot break up sections within
1256 fairly simple uses. In particular, you cannot break up sections within
1257 indented code (loops, if statements, function definitions, etc.)
1257 indented code (loops, if statements, function definitions, etc.)
1258 Supporting something like this would basically require tracking the
1258 Supporting something like this would basically require tracking the
1259 internal execution state of the Python interpreter, so only top-level
1259 internal execution state of the Python interpreter, so only top-level
1260 divisions are allowed. If you want to be able to open an IPython
1260 divisions are allowed. If you want to be able to open an IPython
1261 instance at an arbitrary point in a program, you can use IPython's
1261 instance at an arbitrary point in a program, you can use IPython's
1262 embedding facilities, see :func:`IPython.embed` for details.
1262 embedding facilities, see :func:`IPython.embed` for details.
1263
1263
@@ -1,293 +1,293 b''
1 .. _ipython_as_shell:
1 .. _ipython_as_shell:
2
2
3 =========================
3 =========================
4 IPython as a system shell
4 IPython as a system shell
5 =========================
5 =========================
6
6
7 .. warning::
7 .. warning::
8
8
9 As of the 0.11 version of IPython, most of the APIs used by the shell
9 As of the 0.11 version of IPython, most of the APIs used by the shell
10 profile have been changed, so the profile currently does very little
10 profile have been changed, so the profile currently does very little
11 beyond changing the IPython prompt. To help restore the shell
11 beyond changing the IPython prompt. To help restore the shell
12 profile to past functionality described here, the old code is found in
12 profile to past functionality described here, the old code is found in
13 :file:`IPython/deathrow`, which needs to be updated to use the
13 :file:`IPython/deathrow`, which needs to be updated to use the
14 APIs in 0.11.
14 APIs in 0.11.
15
15
16 Overview
16 Overview
17 ========
17 ========
18
18
19 The 'sh' profile optimizes IPython for system shell usage. Apart from
19 The 'sh' profile optimizes IPython for system shell usage. Apart from
20 certain job control functionality that is present in unix (ctrl+z does
20 certain job control functionality that is present in unix (ctrl+z does
21 "suspend"), the sh profile should provide you with most of the
21 "suspend"), the sh profile should provide you with most of the
22 functionality you use daily in system shell, and more. Invoke IPython
22 functionality you use daily in system shell, and more. Invoke IPython
23 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
23 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
24 the "pysh" shortcut in start menu.
24 the "pysh" shortcut in start menu.
25
25
26 If you want to use the features of sh profile as your defaults (which
26 If you want to use the features of sh profile as your defaults (which
27 might be a good idea if you use other profiles a lot of the time but
27 might be a good idea if you use other profiles a lot of the time but
28 still want the convenience of sh profile), add ``import ipy_profile_sh``
28 still want the convenience of sh profile), add ``import ipy_profile_sh``
29 to your $IPYTHON_DIR/ipy_user_conf.py.
29 to your $IPYTHON_DIR/ipy_user_conf.py.
30
30
31 The 'sh' profile is different from the default profile in that:
31 The 'sh' profile is different from the default profile in that:
32
32
33 * Prompt shows the current directory
33 * Prompt shows the current directory
34 * Spacing between prompts and input is more compact (no padding with
34 * Spacing between prompts and input is more compact (no padding with
35 empty lines). The startup banner is more compact as well.
35 empty lines). The startup banner is more compact as well.
36 * System commands are directly available (in alias table) without
36 * System commands are directly available (in alias table) without
37 requesting %rehashx - however, if you install new programs along
37 requesting %rehashx - however, if you install new programs along
38 your PATH, you might want to run %rehashx to update the persistent
38 your PATH, you might want to run %rehashx to update the persistent
39 alias table
39 alias table
40 * Macros are stored in raw format by default. That is, instead of
40 * Macros are stored in raw format by default. That is, instead of
41 '_ip.system("cat foo"), the macro will contain text 'cat foo')
41 '_ip.system("cat foo"), the macro will contain text 'cat foo')
42 * Autocall is in full mode
42 * Autocall is in full mode
43 * Calling "up" does "cd .."
43 * Calling "up" does "cd .."
44
44
45 The 'sh' profile is different from the now-obsolete (and unavailable)
45 The 'sh' profile is different from the now-obsolete (and unavailable)
46 'pysh' profile in that the ``$$var = command`` and ``$var = command`` syntax is
46 'pysh' profile in that the ``$$var = command`` and ``$var = command`` syntax is
47 not supported anymore. Use ``var = !command`` instead (which is available in all
47 not supported anymore. Use ``var = !command`` instead (which is available in all
48 IPython profiles).
48 IPython profiles).
49
49
50 Aliases
50 Aliases
51 =======
51 =======
52
52
53 All of your $PATH has been loaded as IPython aliases, so you should be
53 All of your $PATH has been loaded as IPython aliases, so you should be
54 able to type any normal system command and have it executed. See
54 able to type any normal system command and have it executed. See
55 %alias? and %unalias? for details on the alias facilities. See also
55 %alias? and %unalias? for details on the alias facilities. See also
56 %rehashx? for details on the mechanism used to load $PATH.
56 %rehashx? for details on the mechanism used to load $PATH.
57
57
58
58
59 Directory management
59 Directory management
60 ====================
60 ====================
61
61
62 Since each command passed by ipython to the underlying system is executed
62 Since each command passed by ipython to the underlying system is executed
63 in a subshell which exits immediately, you can NOT use !cd to navigate
63 in a subshell which exits immediately, you can NOT use !cd to navigate
64 the filesystem.
64 the filesystem.
65
65
66 IPython provides its own builtin '%cd' magic command to move in the
66 IPython provides its own builtin '%cd' magic command to move in the
67 filesystem (the % is not required with automagic on). It also maintains
67 filesystem (the % is not required with automagic on). It also maintains
68 a list of visited directories (use %dhist to see it) and allows direct
68 a list of visited directories (use %dhist to see it) and allows direct
69 switching to any of them. Type 'cd?' for more details.
69 switching to any of them. Type 'cd?' for more details.
70
70
71 %pushd, %popd and %dirs are provided for directory stack handling.
71 %pushd, %popd and %dirs are provided for directory stack handling.
72
72
73
73
74 Enabled extensions
74 Enabled extensions
75 ==================
75 ==================
76
76
77 Some extensions, listed below, are enabled as default in this profile.
77 Some extensions, listed below, are enabled as default in this profile.
78
78
79 envpersist
79 envpersist
80 ----------
80 ----------
81
81
82 %env can be used to "remember" environment variable manipulations. Examples::
82 %env can be used to "remember" environment variable manipulations. Examples::
83
83
84 %env - Show all environment variables
84 %env - Show all environment variables
85 %env VISUAL=jed - set VISUAL to jed
85 %env VISUAL=jed - set VISUAL to jed
86 %env PATH+=;/foo - append ;foo to PATH
86 %env PATH+=;/foo - append ;foo to PATH
87 %env PATH+=;/bar - also append ;bar to PATH
87 %env PATH+=;/bar - also append ;bar to PATH
88 %env PATH-=/wbin; - prepend /wbin; to PATH
88 %env PATH-=/wbin; - prepend /wbin; to PATH
89 %env -d VISUAL - forget VISUAL persistent val
89 %env -d VISUAL - forget VISUAL persistent val
90 %env -p - print all persistent env modifications
90 %env -p - print all persistent env modifications
91
91
92 ipy_which
92 ipy_which
93 ---------
93 ---------
94
94
95 %which magic command. Like 'which' in unix, but knows about ipython aliases.
95 %which magic command. Like 'which' in unix, but knows about ipython aliases.
96
96
97 Example::
97 Example::
98
98
99 [C:/ipython]|14> %which st
99 [C:/ipython]|14> %which st
100 st -> start .
100 st -> start .
101 [C:/ipython]|15> %which d
101 [C:/ipython]|15> %which d
102 d -> dir /w /og /on
102 d -> dir /w /og /on
103 [C:/ipython]|16> %which cp
103 [C:/ipython]|16> %which cp
104 cp -> cp
104 cp -> cp
105 == c:\bin\cp.exe
105 == c:\bin\cp.exe
106 c:\bin\cp.exe
106 c:\bin\cp.exe
107
107
108 ipy_app_completers
108 ipy_app_completers
109 ------------------
109 ------------------
110
110
111 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
111 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
112
112
113 ipy_rehashdir
113 ipy_rehashdir
114 -------------
114 -------------
115
115
116 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
116 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
117
117
118 [~]|22> cd c:/opt/PuTTY/
118 [~]|22> cd c:/opt/PuTTY/
119 [c:opt/PuTTY]|23> rehashdir .
119 [c:opt/PuTTY]|23> rehashdir .
120 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
120 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
121
121
122 Now, you can execute any of those commams directly::
122 Now, you can execute any of those commams directly::
123
123
124 [c:opt/PuTTY]|24> cd
124 [c:opt/PuTTY]|24> cd
125 [~]|25> putty
125 [~]|25> putty
126
126
127 (the putty window opens).
127 (the putty window opens).
128
128
129 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
129 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
130
130
131 [~]|27> for a in _23:
131 [~]|27> for a in _23:
132 |..> %store $a
132 |..> %store $a
133 |..>
133 |..>
134 |..>
134 |..>
135 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
135 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
136 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
136 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
137 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
137 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
138 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
138 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
139 ...
139 ...
140
140
141 mglob
141 mglob
142 -----
142 -----
143
143
144 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
144 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
145
145
146 [c:/ipython]|9> mglob *.py
146 [c:/ipython]|9> mglob *.py
147 [c:/ipython]|10> mglob *.py rec:*.txt
147 [c:/ipython]|10> mglob *.py rec:*.txt
148 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
148 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
149
149
150 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
150 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
151
151
152
152
153 Prompt customization
153 Prompt customization
154 ====================
154 ====================
155
155
156 The sh profile uses the following prompt configurations::
156 The sh profile uses the following prompt configurations::
157
157
158 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>'
158 o.PromptManager.in_template= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>'
159 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>'
159 o.PromptManager.in2_template= r'\C_Green|\C_LightGreen\D\C_Green>'
160
160
161 You can change the prompt configuration to your liking by editing
161 You can change the prompt configuration to your liking by editing
162 ipython_config.py.
162 ipython_config.py.
163
163
164 .. _string_lists:
164 .. _string_lists:
165
165
166 String lists
166 String lists
167 ============
167 ============
168
168
169 String lists (IPython.utils.text.SList) are handy way to process output
169 String lists (IPython.utils.text.SList) are handy way to process output
170 from system commands. They are produced by ``var = !cmd`` syntax.
170 from system commands. They are produced by ``var = !cmd`` syntax.
171
171
172 First, we acquire the output of 'ls -l'::
172 First, we acquire the output of 'ls -l'::
173
173
174 [Q:doc/examples]|2> lines = !ls -l
174 [Q:doc/examples]|2> lines = !ls -l
175 ==
175 ==
176 ['total 23',
176 ['total 23',
177 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
177 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
178 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
178 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
179 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
179 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
180 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
180 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
181 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
181 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
182 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
182 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
183 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
183 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
184
184
185 Now, let's take a look at the contents of 'lines' (the first number is
185 Now, let's take a look at the contents of 'lines' (the first number is
186 the list element number)::
186 the list element number)::
187
187
188 [Q:doc/examples]|3> lines
188 [Q:doc/examples]|3> lines
189 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
189 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
190
190
191 0: total 23
191 0: total 23
192 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
192 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
193 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
193 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
194 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
194 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
195 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
195 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
196 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
196 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
197 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
197 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
198 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
198 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
199
199
200 Now, let's filter out the 'embed' lines::
200 Now, let's filter out the 'embed' lines::
201
201
202 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
202 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
203 [Q:doc/examples]|5> l2
203 [Q:doc/examples]|5> l2
204 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
204 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
205
205
206 0: total 23
206 0: total 23
207 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
207 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
208 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
208 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
209 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
209 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
210 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
210 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
211 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
211 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
212
212
213 Now, we want strings having just file names and permissions::
213 Now, we want strings having just file names and permissions::
214
214
215 [Q:doc/examples]|6> l2.fields(8,0)
215 [Q:doc/examples]|6> l2.fields(8,0)
216 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
216 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
217
217
218 0: total
218 0: total
219 1: example-demo.py -rw-rw-rw-
219 1: example-demo.py -rw-rw-rw-
220 2: example-gnuplot.py -rwxrwxrwx
220 2: example-gnuplot.py -rwxrwxrwx
221 3: extension.py -rwxrwxrwx
221 3: extension.py -rwxrwxrwx
222 4: seteditor.py -rwxrwxrwx
222 4: seteditor.py -rwxrwxrwx
223 5: seteditor.pyc -rwxrwxrwx
223 5: seteditor.pyc -rwxrwxrwx
224
224
225 Note how the line with 'total' does not raise IndexError.
225 Note how the line with 'total' does not raise IndexError.
226
226
227 If you want to split these (yielding lists), call fields() without
227 If you want to split these (yielding lists), call fields() without
228 arguments::
228 arguments::
229
229
230 [Q:doc/examples]|7> _.fields()
230 [Q:doc/examples]|7> _.fields()
231 <7>
231 <7>
232 [['total'],
232 [['total'],
233 ['example-demo.py', '-rw-rw-rw-'],
233 ['example-demo.py', '-rw-rw-rw-'],
234 ['example-gnuplot.py', '-rwxrwxrwx'],
234 ['example-gnuplot.py', '-rwxrwxrwx'],
235 ['extension.py', '-rwxrwxrwx'],
235 ['extension.py', '-rwxrwxrwx'],
236 ['seteditor.py', '-rwxrwxrwx'],
236 ['seteditor.py', '-rwxrwxrwx'],
237 ['seteditor.pyc', '-rwxrwxrwx']]
237 ['seteditor.pyc', '-rwxrwxrwx']]
238
238
239 If you want to pass these separated with spaces to a command (typical
239 If you want to pass these separated with spaces to a command (typical
240 for lists if files), use the .s property::
240 for lists if files), use the .s property::
241
241
242
242
243 [Q:doc/examples]|13> files = l2.fields(8).s
243 [Q:doc/examples]|13> files = l2.fields(8).s
244 [Q:doc/examples]|14> files
244 [Q:doc/examples]|14> files
245 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
245 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
246 [Q:doc/examples]|15> ls $files
246 [Q:doc/examples]|15> ls $files
247 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
247 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
248
248
249 SLists are inherited from normal python lists, so every list method is
249 SLists are inherited from normal python lists, so every list method is
250 available::
250 available::
251
251
252 [Q:doc/examples]|21> lines.append('hey')
252 [Q:doc/examples]|21> lines.append('hey')
253
253
254
254
255 Real world example: remove all files outside version control
255 Real world example: remove all files outside version control
256 ------------------------------------------------------------
256 ------------------------------------------------------------
257
257
258 First, capture output of "hg status"::
258 First, capture output of "hg status"::
259
259
260 [Q:/ipython]|28> out = !hg status
260 [Q:/ipython]|28> out = !hg status
261 ==
261 ==
262 ['M IPython\\extensions\\ipy_kitcfg.py',
262 ['M IPython\\extensions\\ipy_kitcfg.py',
263 'M IPython\\extensions\\ipy_rehashdir.py',
263 'M IPython\\extensions\\ipy_rehashdir.py',
264 ...
264 ...
265 '? build\\lib\\IPython\\Debugger.py',
265 '? build\\lib\\IPython\\Debugger.py',
266 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
266 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
267 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
267 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
268 ...
268 ...
269
269
270 (lines starting with ? are not under version control).
270 (lines starting with ? are not under version control).
271
271
272 ::
272 ::
273
273
274 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
274 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
275 [Q:/ipython]|36> junk
275 [Q:/ipython]|36> junk
276 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
276 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
277 ...
277 ...
278 10: build\bdist.win32\winexe\temp\_ctypes.py
278 10: build\bdist.win32\winexe\temp\_ctypes.py
279 11: build\bdist.win32\winexe\temp\_hashlib.py
279 11: build\bdist.win32\winexe\temp\_hashlib.py
280 12: build\bdist.win32\winexe\temp\_socket.py
280 12: build\bdist.win32\winexe\temp\_socket.py
281
281
282 Now we can just remove these files by doing 'rm $junk.s'.
282 Now we can just remove these files by doing 'rm $junk.s'.
283
283
284 The .s, .n, .p properties
284 The .s, .n, .p properties
285 -------------------------
285 -------------------------
286
286
287 The ``.s`` property returns one string where lines are separated by
287 The ``.s`` property returns one string where lines are separated by
288 single space (for convenient passing to system commands). The ``.n``
288 single space (for convenient passing to system commands). The ``.n``
289 property return one string where the lines are separated by a newline
289 property return one string where the lines are separated by a newline
290 (i.e. the original output of the function). If the items in string
290 (i.e. the original output of the function). If the items in string
291 list are file names, ``.p`` can be used to get a list of "path" objects
291 list are file names, ``.p`` can be used to get a list of "path" objects
292 for convenient file manipulation.
292 for convenient file manipulation.
293
293
General Comments 0
You need to be logged in to leave comments. Login now