##// END OF EJS Templates
Merge pull request #1083 from takluyver/prompts...
Fernando Perez -
r5556:4b8920a5 merge
parent child Browse files
Show More
@@ -1,2707 +1,2741 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
349 show_rewritten_input = CBool(True, config=True,
350 help="Show rewritten input, e.g. for autocall."
351 )
352
322 quiet = CBool(False, config=True)
353 quiet = CBool(False, config=True)
323
354
324 history_length = Integer(10000, config=True)
355 history_length = Integer(10000, config=True)
325
356
326 # The readline stuff will eventually be moved to the terminal subclass
357 # 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.
358 # but for now, we can't do that as readline is welded in everywhere.
328 readline_use = CBool(True, config=True)
359 readline_use = CBool(True, config=True)
329 readline_remove_delims = Unicode('-/~', config=True)
360 readline_remove_delims = Unicode('-/~', config=True)
330 # don't use \M- bindings by default, because they
361 # don't use \M- bindings by default, because they
331 # conflict with 8-bit encodings. See gh-58,gh-88
362 # conflict with 8-bit encodings. See gh-58,gh-88
332 readline_parse_and_bind = List([
363 readline_parse_and_bind = List([
333 'tab: complete',
364 'tab: complete',
334 '"\C-l": clear-screen',
365 '"\C-l": clear-screen',
335 'set show-all-if-ambiguous on',
366 'set show-all-if-ambiguous on',
336 '"\C-o": tab-insert',
367 '"\C-o": tab-insert',
337 '"\C-r": reverse-search-history',
368 '"\C-r": reverse-search-history',
338 '"\C-s": forward-search-history',
369 '"\C-s": forward-search-history',
339 '"\C-p": history-search-backward',
370 '"\C-p": history-search-backward',
340 '"\C-n": history-search-forward',
371 '"\C-n": history-search-forward',
341 '"\e[A": history-search-backward',
372 '"\e[A": history-search-backward',
342 '"\e[B": history-search-forward',
373 '"\e[B": history-search-forward',
343 '"\C-k": kill-line',
374 '"\C-k": kill-line',
344 '"\C-u": unix-line-discard',
375 '"\C-u": unix-line-discard',
345 ], allow_none=False, config=True)
376 ], allow_none=False, config=True)
346
377
347 # TODO: this part of prompt management should be moved to the frontends.
378 # TODO: this part of prompt management should be moved to the frontends.
348 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
379 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
349 separate_in = SeparateUnicode('\n', config=True)
380 separate_in = SeparateUnicode('\n', config=True)
350 separate_out = SeparateUnicode('', config=True)
381 separate_out = SeparateUnicode('', config=True)
351 separate_out2 = SeparateUnicode('', config=True)
382 separate_out2 = SeparateUnicode('', config=True)
352 wildcards_case_sensitive = CBool(True, config=True)
383 wildcards_case_sensitive = CBool(True, config=True)
353 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
384 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
354 default_value='Context', config=True)
385 default_value='Context', config=True)
355
386
356 # Subcomponents of InteractiveShell
387 # Subcomponents of InteractiveShell
357 alias_manager = Instance('IPython.core.alias.AliasManager')
388 alias_manager = Instance('IPython.core.alias.AliasManager')
358 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
389 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
359 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
390 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
360 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
391 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
361 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
392 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
362 plugin_manager = Instance('IPython.core.plugin.PluginManager')
393 plugin_manager = Instance('IPython.core.plugin.PluginManager')
363 payload_manager = Instance('IPython.core.payload.PayloadManager')
394 payload_manager = Instance('IPython.core.payload.PayloadManager')
364 history_manager = Instance('IPython.core.history.HistoryManager')
395 history_manager = Instance('IPython.core.history.HistoryManager')
365
396
366 profile_dir = Instance('IPython.core.application.ProfileDir')
397 profile_dir = Instance('IPython.core.application.ProfileDir')
367 @property
398 @property
368 def profile(self):
399 def profile(self):
369 if self.profile_dir is not None:
400 if self.profile_dir is not None:
370 name = os.path.basename(self.profile_dir.location)
401 name = os.path.basename(self.profile_dir.location)
371 return name.replace('profile_','')
402 return name.replace('profile_','')
372
403
373
404
374 # Private interface
405 # Private interface
375 _post_execute = Instance(dict)
406 _post_execute = Instance(dict)
376
407
377 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
408 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
378 user_module=None, user_ns=None,
409 user_module=None, user_ns=None,
379 custom_exceptions=((), None)):
410 custom_exceptions=((), None)):
380
411
381 # This is where traits with a config_key argument are updated
412 # This is where traits with a config_key argument are updated
382 # from the values on config.
413 # from the values on config.
383 super(InteractiveShell, self).__init__(config=config)
414 super(InteractiveShell, self).__init__(config=config)
384 self.configurables = [self]
415 self.configurables = [self]
385
416
386 # These are relatively independent and stateless
417 # These are relatively independent and stateless
387 self.init_ipython_dir(ipython_dir)
418 self.init_ipython_dir(ipython_dir)
388 self.init_profile_dir(profile_dir)
419 self.init_profile_dir(profile_dir)
389 self.init_instance_attrs()
420 self.init_instance_attrs()
390 self.init_environment()
421 self.init_environment()
391
422
392 # Create namespaces (user_ns, user_global_ns, etc.)
423 # Create namespaces (user_ns, user_global_ns, etc.)
393 self.init_create_namespaces(user_module, user_ns)
424 self.init_create_namespaces(user_module, user_ns)
394 # This has to be done after init_create_namespaces because it uses
425 # This has to be done after init_create_namespaces because it uses
395 # something in self.user_ns, but before init_sys_modules, which
426 # something in self.user_ns, but before init_sys_modules, which
396 # is the first thing to modify sys.
427 # is the first thing to modify sys.
397 # TODO: When we override sys.stdout and sys.stderr before this class
428 # 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
429 # is created, we are saving the overridden ones here. Not sure if this
399 # is what we want to do.
430 # is what we want to do.
400 self.save_sys_module_state()
431 self.save_sys_module_state()
401 self.init_sys_modules()
432 self.init_sys_modules()
402
433
403 # While we're trying to have each part of the code directly access what
434 # 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
435 # it needs without keeping redundant references to objects, we have too
405 # much legacy code that expects ip.db to exist.
436 # much legacy code that expects ip.db to exist.
406 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
437 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
407
438
408 self.init_history()
439 self.init_history()
409 self.init_encoding()
440 self.init_encoding()
410 self.init_prefilter()
441 self.init_prefilter()
411
442
412 Magic.__init__(self, self)
443 Magic.__init__(self, self)
413
444
414 self.init_syntax_highlighting()
445 self.init_syntax_highlighting()
415 self.init_hooks()
446 self.init_hooks()
416 self.init_pushd_popd_magic()
447 self.init_pushd_popd_magic()
417 # self.init_traceback_handlers use to be here, but we moved it below
448 # 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.
449 # because it and init_io have to come after init_readline.
419 self.init_user_ns()
450 self.init_user_ns()
420 self.init_logger()
451 self.init_logger()
421 self.init_alias()
452 self.init_alias()
422 self.init_builtins()
453 self.init_builtins()
423
454
424 # pre_config_initialization
455 # pre_config_initialization
425
456
426 # The next section should contain everything that was in ipmaker.
457 # The next section should contain everything that was in ipmaker.
427 self.init_logstart()
458 self.init_logstart()
428
459
429 # The following was in post_config_initialization
460 # The following was in post_config_initialization
430 self.init_inspector()
461 self.init_inspector()
431 # init_readline() must come before init_io(), because init_io uses
462 # init_readline() must come before init_io(), because init_io uses
432 # readline related things.
463 # readline related things.
433 self.init_readline()
464 self.init_readline()
434 # We save this here in case user code replaces raw_input, but it needs
465 # 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
466 # to be after init_readline(), because PyPy's readline works by replacing
436 # raw_input.
467 # raw_input.
437 if py3compat.PY3:
468 if py3compat.PY3:
438 self.raw_input_original = input
469 self.raw_input_original = input
439 else:
470 else:
440 self.raw_input_original = raw_input
471 self.raw_input_original = raw_input
441 # init_completer must come after init_readline, because it needs to
472 # init_completer must come after init_readline, because it needs to
442 # know whether readline is present or not system-wide to configure the
473 # know whether readline is present or not system-wide to configure the
443 # completers, since the completion machinery can now operate
474 # completers, since the completion machinery can now operate
444 # independently of readline (e.g. over the network)
475 # independently of readline (e.g. over the network)
445 self.init_completer()
476 self.init_completer()
446 # TODO: init_io() needs to happen before init_traceback handlers
477 # TODO: init_io() needs to happen before init_traceback handlers
447 # because the traceback handlers hardcode the stdout/stderr streams.
478 # because the traceback handlers hardcode the stdout/stderr streams.
448 # This logic in in debugger.Pdb and should eventually be changed.
479 # This logic in in debugger.Pdb and should eventually be changed.
449 self.init_io()
480 self.init_io()
450 self.init_traceback_handlers(custom_exceptions)
481 self.init_traceback_handlers(custom_exceptions)
451 self.init_prompts()
482 self.init_prompts()
452 self.init_display_formatter()
483 self.init_display_formatter()
453 self.init_display_pub()
484 self.init_display_pub()
454 self.init_displayhook()
485 self.init_displayhook()
455 self.init_reload_doctest()
486 self.init_reload_doctest()
456 self.init_magics()
487 self.init_magics()
457 self.init_pdb()
488 self.init_pdb()
458 self.init_extension_manager()
489 self.init_extension_manager()
459 self.init_plugin_manager()
490 self.init_plugin_manager()
460 self.init_payload()
491 self.init_payload()
461 self.hooks.late_startup_hook()
492 self.hooks.late_startup_hook()
462 atexit.register(self.atexit_operations)
493 atexit.register(self.atexit_operations)
463
494
464 def get_ipython(self):
495 def get_ipython(self):
465 """Return the currently running IPython instance."""
496 """Return the currently running IPython instance."""
466 return self
497 return self
467
498
468 #-------------------------------------------------------------------------
499 #-------------------------------------------------------------------------
469 # Trait changed handlers
500 # Trait changed handlers
470 #-------------------------------------------------------------------------
501 #-------------------------------------------------------------------------
471
502
472 def _ipython_dir_changed(self, name, new):
503 def _ipython_dir_changed(self, name, new):
473 if not os.path.isdir(new):
504 if not os.path.isdir(new):
474 os.makedirs(new, mode = 0777)
505 os.makedirs(new, mode = 0777)
475
506
476 def set_autoindent(self,value=None):
507 def set_autoindent(self,value=None):
477 """Set the autoindent flag, checking for readline support.
508 """Set the autoindent flag, checking for readline support.
478
509
479 If called with no arguments, it acts as a toggle."""
510 If called with no arguments, it acts as a toggle."""
480
511
481 if value != 0 and not self.has_readline:
512 if value != 0 and not self.has_readline:
482 if os.name == 'posix':
513 if os.name == 'posix':
483 warn("The auto-indent feature requires the readline library")
514 warn("The auto-indent feature requires the readline library")
484 self.autoindent = 0
515 self.autoindent = 0
485 return
516 return
486 if value is None:
517 if value is None:
487 self.autoindent = not self.autoindent
518 self.autoindent = not self.autoindent
488 else:
519 else:
489 self.autoindent = value
520 self.autoindent = value
490
521
491 #-------------------------------------------------------------------------
522 #-------------------------------------------------------------------------
492 # init_* methods called by __init__
523 # init_* methods called by __init__
493 #-------------------------------------------------------------------------
524 #-------------------------------------------------------------------------
494
525
495 def init_ipython_dir(self, ipython_dir):
526 def init_ipython_dir(self, ipython_dir):
496 if ipython_dir is not None:
527 if ipython_dir is not None:
497 self.ipython_dir = ipython_dir
528 self.ipython_dir = ipython_dir
498 return
529 return
499
530
500 self.ipython_dir = get_ipython_dir()
531 self.ipython_dir = get_ipython_dir()
501
532
502 def init_profile_dir(self, profile_dir):
533 def init_profile_dir(self, profile_dir):
503 if profile_dir is not None:
534 if profile_dir is not None:
504 self.profile_dir = profile_dir
535 self.profile_dir = profile_dir
505 return
536 return
506 self.profile_dir =\
537 self.profile_dir =\
507 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
538 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
508
539
509 def init_instance_attrs(self):
540 def init_instance_attrs(self):
510 self.more = False
541 self.more = False
511
542
512 # command compiler
543 # command compiler
513 self.compile = CachingCompiler()
544 self.compile = CachingCompiler()
514
545
515 # Make an empty namespace, which extension writers can rely on both
546 # Make an empty namespace, which extension writers can rely on both
516 # existing and NEVER being used by ipython itself. This gives them a
547 # existing and NEVER being used by ipython itself. This gives them a
517 # convenient location for storing additional information and state
548 # convenient location for storing additional information and state
518 # their extensions may require, without fear of collisions with other
549 # their extensions may require, without fear of collisions with other
519 # ipython names that may develop later.
550 # ipython names that may develop later.
520 self.meta = Struct()
551 self.meta = Struct()
521
552
522 # Temporary files used for various purposes. Deleted at exit.
553 # Temporary files used for various purposes. Deleted at exit.
523 self.tempfiles = []
554 self.tempfiles = []
524
555
525 # Keep track of readline usage (later set by init_readline)
556 # Keep track of readline usage (later set by init_readline)
526 self.has_readline = False
557 self.has_readline = False
527
558
528 # keep track of where we started running (mainly for crash post-mortem)
559 # keep track of where we started running (mainly for crash post-mortem)
529 # This is not being used anywhere currently.
560 # This is not being used anywhere currently.
530 self.starting_dir = os.getcwdu()
561 self.starting_dir = os.getcwdu()
531
562
532 # Indentation management
563 # Indentation management
533 self.indent_current_nsp = 0
564 self.indent_current_nsp = 0
534
565
535 # Dict to track post-execution functions that have been registered
566 # Dict to track post-execution functions that have been registered
536 self._post_execute = {}
567 self._post_execute = {}
537
568
538 def init_environment(self):
569 def init_environment(self):
539 """Any changes we need to make to the user's environment."""
570 """Any changes we need to make to the user's environment."""
540 pass
571 pass
541
572
542 def init_encoding(self):
573 def init_encoding(self):
543 # Get system encoding at startup time. Certain terminals (like Emacs
574 # 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
575 # under Win32 have it set to None, and we need to have a known valid
545 # encoding to use in the raw_input() method
576 # encoding to use in the raw_input() method
546 try:
577 try:
547 self.stdin_encoding = sys.stdin.encoding or 'ascii'
578 self.stdin_encoding = sys.stdin.encoding or 'ascii'
548 except AttributeError:
579 except AttributeError:
549 self.stdin_encoding = 'ascii'
580 self.stdin_encoding = 'ascii'
550
581
551 def init_syntax_highlighting(self):
582 def init_syntax_highlighting(self):
552 # Python source parser/formatter for syntax highlighting
583 # Python source parser/formatter for syntax highlighting
553 pyformat = PyColorize.Parser().format
584 pyformat = PyColorize.Parser().format
554 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
585 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
555
586
556 def init_pushd_popd_magic(self):
587 def init_pushd_popd_magic(self):
557 # for pushd/popd management
588 # for pushd/popd management
558 self.home_dir = get_home_dir()
589 self.home_dir = get_home_dir()
559
590
560 self.dir_stack = []
591 self.dir_stack = []
561
592
562 def init_logger(self):
593 def init_logger(self):
563 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
594 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
564 logmode='rotate')
595 logmode='rotate')
565
596
566 def init_logstart(self):
597 def init_logstart(self):
567 """Initialize logging in case it was requested at the command line.
598 """Initialize logging in case it was requested at the command line.
568 """
599 """
569 if self.logappend:
600 if self.logappend:
570 self.magic_logstart(self.logappend + ' append')
601 self.magic_logstart(self.logappend + ' append')
571 elif self.logfile:
602 elif self.logfile:
572 self.magic_logstart(self.logfile)
603 self.magic_logstart(self.logfile)
573 elif self.logstart:
604 elif self.logstart:
574 self.magic_logstart()
605 self.magic_logstart()
575
606
576 def init_builtins(self):
607 def init_builtins(self):
577 self.builtin_trap = BuiltinTrap(shell=self)
608 self.builtin_trap = BuiltinTrap(shell=self)
578
609
579 def init_inspector(self):
610 def init_inspector(self):
580 # Object inspector
611 # Object inspector
581 self.inspector = oinspect.Inspector(oinspect.InspectColors,
612 self.inspector = oinspect.Inspector(oinspect.InspectColors,
582 PyColorize.ANSICodeColors,
613 PyColorize.ANSICodeColors,
583 'NoColor',
614 'NoColor',
584 self.object_info_string_level)
615 self.object_info_string_level)
585
616
586 def init_io(self):
617 def init_io(self):
587 # This will just use sys.stdout and sys.stderr. If you want to
618 # 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
619 # override sys.stdout and sys.stderr themselves, you need to do that
589 # *before* instantiating this class, because io holds onto
620 # *before* instantiating this class, because io holds onto
590 # references to the underlying streams.
621 # references to the underlying streams.
591 if sys.platform == 'win32' and self.has_readline:
622 if sys.platform == 'win32' and self.has_readline:
592 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
623 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
593 else:
624 else:
594 io.stdout = io.IOStream(sys.stdout)
625 io.stdout = io.IOStream(sys.stdout)
595 io.stderr = io.IOStream(sys.stderr)
626 io.stderr = io.IOStream(sys.stderr)
596
627
597 def init_prompts(self):
628 def init_prompts(self):
598 self.prompt_manager = PromptManager(shell=self, config=self.config)
629 self.prompt_manager = PromptManager(shell=self, config=self.config)
599 self.configurables.append(self.prompt_manager)
630 self.configurables.append(self.prompt_manager)
600
631
601 def init_display_formatter(self):
632 def init_display_formatter(self):
602 self.display_formatter = DisplayFormatter(config=self.config)
633 self.display_formatter = DisplayFormatter(config=self.config)
603 self.configurables.append(self.display_formatter)
634 self.configurables.append(self.display_formatter)
604
635
605 def init_display_pub(self):
636 def init_display_pub(self):
606 self.display_pub = self.display_pub_class(config=self.config)
637 self.display_pub = self.display_pub_class(config=self.config)
607 self.configurables.append(self.display_pub)
638 self.configurables.append(self.display_pub)
608
639
609 def init_displayhook(self):
640 def init_displayhook(self):
610 # Initialize displayhook, set in/out prompts and printing system
641 # Initialize displayhook, set in/out prompts and printing system
611 self.displayhook = self.displayhook_class(
642 self.displayhook = self.displayhook_class(
612 config=self.config,
643 config=self.config,
613 shell=self,
644 shell=self,
614 cache_size=self.cache_size,
645 cache_size=self.cache_size,
615 )
646 )
616 self.configurables.append(self.displayhook)
647 self.configurables.append(self.displayhook)
617 # This is a context manager that installs/revmoes the displayhook at
648 # This is a context manager that installs/revmoes the displayhook at
618 # the appropriate time.
649 # the appropriate time.
619 self.display_trap = DisplayTrap(hook=self.displayhook)
650 self.display_trap = DisplayTrap(hook=self.displayhook)
620
651
621 def init_reload_doctest(self):
652 def init_reload_doctest(self):
622 # Do a proper resetting of doctest, including the necessary displayhook
653 # Do a proper resetting of doctest, including the necessary displayhook
623 # monkeypatching
654 # monkeypatching
624 try:
655 try:
625 doctest_reload()
656 doctest_reload()
626 except ImportError:
657 except ImportError:
627 warn("doctest module does not exist.")
658 warn("doctest module does not exist.")
628
659
629 #-------------------------------------------------------------------------
660 #-------------------------------------------------------------------------
630 # Things related to injections into the sys module
661 # Things related to injections into the sys module
631 #-------------------------------------------------------------------------
662 #-------------------------------------------------------------------------
632
663
633 def save_sys_module_state(self):
664 def save_sys_module_state(self):
634 """Save the state of hooks in the sys module.
665 """Save the state of hooks in the sys module.
635
666
636 This has to be called after self.user_module is created.
667 This has to be called after self.user_module is created.
637 """
668 """
638 self._orig_sys_module_state = {}
669 self._orig_sys_module_state = {}
639 self._orig_sys_module_state['stdin'] = sys.stdin
670 self._orig_sys_module_state['stdin'] = sys.stdin
640 self._orig_sys_module_state['stdout'] = sys.stdout
671 self._orig_sys_module_state['stdout'] = sys.stdout
641 self._orig_sys_module_state['stderr'] = sys.stderr
672 self._orig_sys_module_state['stderr'] = sys.stderr
642 self._orig_sys_module_state['excepthook'] = sys.excepthook
673 self._orig_sys_module_state['excepthook'] = sys.excepthook
643 self._orig_sys_modules_main_name = self.user_module.__name__
674 self._orig_sys_modules_main_name = self.user_module.__name__
644
675
645 def restore_sys_module_state(self):
676 def restore_sys_module_state(self):
646 """Restore the state of the sys module."""
677 """Restore the state of the sys module."""
647 try:
678 try:
648 for k, v in self._orig_sys_module_state.iteritems():
679 for k, v in self._orig_sys_module_state.iteritems():
649 setattr(sys, k, v)
680 setattr(sys, k, v)
650 except AttributeError:
681 except AttributeError:
651 pass
682 pass
652 # Reset what what done in self.init_sys_modules
683 # Reset what what done in self.init_sys_modules
653 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
684 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
654
685
655 #-------------------------------------------------------------------------
686 #-------------------------------------------------------------------------
656 # Things related to hooks
687 # Things related to hooks
657 #-------------------------------------------------------------------------
688 #-------------------------------------------------------------------------
658
689
659 def init_hooks(self):
690 def init_hooks(self):
660 # hooks holds pointers used for user-side customizations
691 # hooks holds pointers used for user-side customizations
661 self.hooks = Struct()
692 self.hooks = Struct()
662
693
663 self.strdispatchers = {}
694 self.strdispatchers = {}
664
695
665 # Set all default hooks, defined in the IPython.hooks module.
696 # Set all default hooks, defined in the IPython.hooks module.
666 hooks = IPython.core.hooks
697 hooks = IPython.core.hooks
667 for hook_name in hooks.__all__:
698 for hook_name in hooks.__all__:
668 # default hooks have priority 100, i.e. low; user hooks should have
699 # default hooks have priority 100, i.e. low; user hooks should have
669 # 0-100 priority
700 # 0-100 priority
670 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
701 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
671
702
672 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
703 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
673 """set_hook(name,hook) -> sets an internal IPython hook.
704 """set_hook(name,hook) -> sets an internal IPython hook.
674
705
675 IPython exposes some of its internal API as user-modifiable hooks. By
706 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
707 adding your function to one of these hooks, you can modify IPython's
677 behavior to call at runtime your own routines."""
708 behavior to call at runtime your own routines."""
678
709
679 # At some point in the future, this should validate the hook before it
710 # 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
711 # accepts it. Probably at least check that the hook takes the number
681 # of args it's supposed to.
712 # of args it's supposed to.
682
713
683 f = types.MethodType(hook,self)
714 f = types.MethodType(hook,self)
684
715
685 # check if the hook is for strdispatcher first
716 # check if the hook is for strdispatcher first
686 if str_key is not None:
717 if str_key is not None:
687 sdp = self.strdispatchers.get(name, StrDispatch())
718 sdp = self.strdispatchers.get(name, StrDispatch())
688 sdp.add_s(str_key, f, priority )
719 sdp.add_s(str_key, f, priority )
689 self.strdispatchers[name] = sdp
720 self.strdispatchers[name] = sdp
690 return
721 return
691 if re_key is not None:
722 if re_key is not None:
692 sdp = self.strdispatchers.get(name, StrDispatch())
723 sdp = self.strdispatchers.get(name, StrDispatch())
693 sdp.add_re(re.compile(re_key), f, priority )
724 sdp.add_re(re.compile(re_key), f, priority )
694 self.strdispatchers[name] = sdp
725 self.strdispatchers[name] = sdp
695 return
726 return
696
727
697 dp = getattr(self.hooks, name, None)
728 dp = getattr(self.hooks, name, None)
698 if name not in IPython.core.hooks.__all__:
729 if name not in IPython.core.hooks.__all__:
699 print "Warning! Hook '%s' is not one of %s" % \
730 print "Warning! Hook '%s' is not one of %s" % \
700 (name, IPython.core.hooks.__all__ )
731 (name, IPython.core.hooks.__all__ )
701 if not dp:
732 if not dp:
702 dp = IPython.core.hooks.CommandChainDispatcher()
733 dp = IPython.core.hooks.CommandChainDispatcher()
703
734
704 try:
735 try:
705 dp.add(f,priority)
736 dp.add(f,priority)
706 except AttributeError:
737 except AttributeError:
707 # it was not commandchain, plain old func - replace
738 # it was not commandchain, plain old func - replace
708 dp = f
739 dp = f
709
740
710 setattr(self.hooks,name, dp)
741 setattr(self.hooks,name, dp)
711
742
712 def register_post_execute(self, func):
743 def register_post_execute(self, func):
713 """Register a function for calling after code execution.
744 """Register a function for calling after code execution.
714 """
745 """
715 if not callable(func):
746 if not callable(func):
716 raise ValueError('argument %s must be callable' % func)
747 raise ValueError('argument %s must be callable' % func)
717 self._post_execute[func] = True
748 self._post_execute[func] = True
718
749
719 #-------------------------------------------------------------------------
750 #-------------------------------------------------------------------------
720 # Things related to the "main" module
751 # Things related to the "main" module
721 #-------------------------------------------------------------------------
752 #-------------------------------------------------------------------------
722
753
723 def new_main_mod(self,ns=None):
754 def new_main_mod(self,ns=None):
724 """Return a new 'main' module object for user code execution.
755 """Return a new 'main' module object for user code execution.
725 """
756 """
726 main_mod = self._user_main_module
757 main_mod = self._user_main_module
727 init_fakemod_dict(main_mod,ns)
758 init_fakemod_dict(main_mod,ns)
728 return main_mod
759 return main_mod
729
760
730 def cache_main_mod(self,ns,fname):
761 def cache_main_mod(self,ns,fname):
731 """Cache a main module's namespace.
762 """Cache a main module's namespace.
732
763
733 When scripts are executed via %run, we must keep a reference to the
764 When scripts are executed via %run, we must keep a reference to the
734 namespace of their __main__ module (a FakeModule instance) around so
765 namespace of their __main__ module (a FakeModule instance) around so
735 that Python doesn't clear it, rendering objects defined therein
766 that Python doesn't clear it, rendering objects defined therein
736 useless.
767 useless.
737
768
738 This method keeps said reference in a private dict, keyed by the
769 This method keeps said reference in a private dict, keyed by the
739 absolute path of the module object (which corresponds to the script
770 absolute path of the module object (which corresponds to the script
740 path). This way, for multiple executions of the same script we only
771 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
772 keep one copy of the namespace (the last one), thus preventing memory
742 leaks from old references while allowing the objects from the last
773 leaks from old references while allowing the objects from the last
743 execution to be accessible.
774 execution to be accessible.
744
775
745 Note: we can not allow the actual FakeModule instances to be deleted,
776 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
777 because of how Python tears down modules (it hard-sets all their
747 references to None without regard for reference counts). This method
778 references to None without regard for reference counts). This method
748 must therefore make a *copy* of the given namespace, to allow the
779 must therefore make a *copy* of the given namespace, to allow the
749 original module's __dict__ to be cleared and reused.
780 original module's __dict__ to be cleared and reused.
750
781
751
782
752 Parameters
783 Parameters
753 ----------
784 ----------
754 ns : a namespace (a dict, typically)
785 ns : a namespace (a dict, typically)
755
786
756 fname : str
787 fname : str
757 Filename associated with the namespace.
788 Filename associated with the namespace.
758
789
759 Examples
790 Examples
760 --------
791 --------
761
792
762 In [10]: import IPython
793 In [10]: import IPython
763
794
764 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
795 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
765
796
766 In [12]: IPython.__file__ in _ip._main_ns_cache
797 In [12]: IPython.__file__ in _ip._main_ns_cache
767 Out[12]: True
798 Out[12]: True
768 """
799 """
769 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
800 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
770
801
771 def clear_main_mod_cache(self):
802 def clear_main_mod_cache(self):
772 """Clear the cache of main modules.
803 """Clear the cache of main modules.
773
804
774 Mainly for use by utilities like %reset.
805 Mainly for use by utilities like %reset.
775
806
776 Examples
807 Examples
777 --------
808 --------
778
809
779 In [15]: import IPython
810 In [15]: import IPython
780
811
781 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
812 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
782
813
783 In [17]: len(_ip._main_ns_cache) > 0
814 In [17]: len(_ip._main_ns_cache) > 0
784 Out[17]: True
815 Out[17]: True
785
816
786 In [18]: _ip.clear_main_mod_cache()
817 In [18]: _ip.clear_main_mod_cache()
787
818
788 In [19]: len(_ip._main_ns_cache) == 0
819 In [19]: len(_ip._main_ns_cache) == 0
789 Out[19]: True
820 Out[19]: True
790 """
821 """
791 self._main_ns_cache.clear()
822 self._main_ns_cache.clear()
792
823
793 #-------------------------------------------------------------------------
824 #-------------------------------------------------------------------------
794 # Things related to debugging
825 # Things related to debugging
795 #-------------------------------------------------------------------------
826 #-------------------------------------------------------------------------
796
827
797 def init_pdb(self):
828 def init_pdb(self):
798 # Set calling of pdb on exceptions
829 # Set calling of pdb on exceptions
799 # self.call_pdb is a property
830 # self.call_pdb is a property
800 self.call_pdb = self.pdb
831 self.call_pdb = self.pdb
801
832
802 def _get_call_pdb(self):
833 def _get_call_pdb(self):
803 return self._call_pdb
834 return self._call_pdb
804
835
805 def _set_call_pdb(self,val):
836 def _set_call_pdb(self,val):
806
837
807 if val not in (0,1,False,True):
838 if val not in (0,1,False,True):
808 raise ValueError,'new call_pdb value must be boolean'
839 raise ValueError,'new call_pdb value must be boolean'
809
840
810 # store value in instance
841 # store value in instance
811 self._call_pdb = val
842 self._call_pdb = val
812
843
813 # notify the actual exception handlers
844 # notify the actual exception handlers
814 self.InteractiveTB.call_pdb = val
845 self.InteractiveTB.call_pdb = val
815
846
816 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
847 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
817 'Control auto-activation of pdb at exceptions')
848 'Control auto-activation of pdb at exceptions')
818
849
819 def debugger(self,force=False):
850 def debugger(self,force=False):
820 """Call the pydb/pdb debugger.
851 """Call the pydb/pdb debugger.
821
852
822 Keywords:
853 Keywords:
823
854
824 - force(False): by default, this routine checks the instance call_pdb
855 - 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.
856 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
857 The 'force' option forces the debugger to activate even if the flag
827 is false.
858 is false.
828 """
859 """
829
860
830 if not (force or self.call_pdb):
861 if not (force or self.call_pdb):
831 return
862 return
832
863
833 if not hasattr(sys,'last_traceback'):
864 if not hasattr(sys,'last_traceback'):
834 error('No traceback has been produced, nothing to debug.')
865 error('No traceback has been produced, nothing to debug.')
835 return
866 return
836
867
837 # use pydb if available
868 # use pydb if available
838 if debugger.has_pydb:
869 if debugger.has_pydb:
839 from pydb import pm
870 from pydb import pm
840 else:
871 else:
841 # fallback to our internal debugger
872 # fallback to our internal debugger
842 pm = lambda : self.InteractiveTB.debugger(force=True)
873 pm = lambda : self.InteractiveTB.debugger(force=True)
843
874
844 with self.readline_no_record:
875 with self.readline_no_record:
845 pm()
876 pm()
846
877
847 #-------------------------------------------------------------------------
878 #-------------------------------------------------------------------------
848 # Things related to IPython's various namespaces
879 # Things related to IPython's various namespaces
849 #-------------------------------------------------------------------------
880 #-------------------------------------------------------------------------
850
881
851 def init_create_namespaces(self, user_module=None, user_ns=None):
882 def init_create_namespaces(self, user_module=None, user_ns=None):
852 # Create the namespace where the user will operate. user_ns is
883 # 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
884 # 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
885 # the locals argument. But we do carry a user_global_ns namespace
855 # given as the exec 'globals' argument, This is useful in embedding
886 # given as the exec 'globals' argument, This is useful in embedding
856 # situations where the ipython shell opens in a context where the
887 # situations where the ipython shell opens in a context where the
857 # distinction between locals and globals is meaningful. For
888 # distinction between locals and globals is meaningful. For
858 # non-embedded contexts, it is just the same object as the user_ns dict.
889 # non-embedded contexts, it is just the same object as the user_ns dict.
859
890
860 # FIXME. For some strange reason, __builtins__ is showing up at user
891 # 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
892 # 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
893 # should really track down where the problem is coming from. Alex
863 # Schmolck reported this problem first.
894 # Schmolck reported this problem first.
864
895
865 # A useful post by Alex Martelli on this topic:
896 # A useful post by Alex Martelli on this topic:
866 # Re: inconsistent value from __builtins__
897 # Re: inconsistent value from __builtins__
867 # Von: Alex Martelli <aleaxit@yahoo.com>
898 # Von: Alex Martelli <aleaxit@yahoo.com>
868 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
899 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
869 # Gruppen: comp.lang.python
900 # Gruppen: comp.lang.python
870
901
871 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
902 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
872 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
903 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
873 # > <type 'dict'>
904 # > <type 'dict'>
874 # > >>> print type(__builtins__)
905 # > >>> print type(__builtins__)
875 # > <type 'module'>
906 # > <type 'module'>
876 # > Is this difference in return value intentional?
907 # > Is this difference in return value intentional?
877
908
878 # Well, it's documented that '__builtins__' can be either a dictionary
909 # 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
910 # 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
911 # 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
912 # that if you need to access the built-in namespace directly, you
882 # should start with "import __builtin__" (note, no 's') which will
913 # should start with "import __builtin__" (note, no 's') which will
883 # definitely give you a module. Yeah, it's somewhat confusing:-(.
914 # definitely give you a module. Yeah, it's somewhat confusing:-(.
884
915
885 # These routines return a properly built module and dict as needed by
916 # 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
917 # the rest of the code, and can also be used by extension writers to
887 # generate properly initialized namespaces.
918 # generate properly initialized namespaces.
888 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
919 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
889
920
890 # A record of hidden variables we have added to the user namespace, so
921 # 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.
922 # we can list later only variables defined in actual interactive use.
892 self.user_ns_hidden = set()
923 self.user_ns_hidden = set()
893
924
894 # Now that FakeModule produces a real module, we've run into a nasty
925 # 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
926 # 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
927 # code ran is deleted. Now that this object is a true module (needed
897 # so docetst and other tools work correctly), the Python module
928 # so docetst and other tools work correctly), the Python module
898 # teardown mechanism runs over it, and sets to None every variable
929 # teardown mechanism runs over it, and sets to None every variable
899 # present in that module. Top-level references to objects from the
930 # present in that module. Top-level references to objects from the
900 # script survive, because the user_ns is updated with them. However,
931 # script survive, because the user_ns is updated with them. However,
901 # calling functions defined in the script that use other things from
932 # calling functions defined in the script that use other things from
902 # the script will fail, because the function's closure had references
933 # 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
934 # to the original objects, which are now all None. So we must protect
904 # these modules from deletion by keeping a cache.
935 # these modules from deletion by keeping a cache.
905 #
936 #
906 # To avoid keeping stale modules around (we only need the one from the
937 # 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
938 # 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,
939 # only the last version of the module is held in the cache. Note,
909 # however, that we must cache the module *namespace contents* (their
940 # however, that we must cache the module *namespace contents* (their
910 # __dict__). Because if we try to cache the actual modules, old ones
941 # __dict__). Because if we try to cache the actual modules, old ones
911 # (uncached) could be destroyed while still holding references (such as
942 # (uncached) could be destroyed while still holding references (such as
912 # those held by GUI objects that tend to be long-lived)>
943 # those held by GUI objects that tend to be long-lived)>
913 #
944 #
914 # The %reset command will flush this cache. See the cache_main_mod()
945 # The %reset command will flush this cache. See the cache_main_mod()
915 # and clear_main_mod_cache() methods for details on use.
946 # and clear_main_mod_cache() methods for details on use.
916
947
917 # This is the cache used for 'main' namespaces
948 # This is the cache used for 'main' namespaces
918 self._main_ns_cache = {}
949 self._main_ns_cache = {}
919 # And this is the single instance of FakeModule whose __dict__ we keep
950 # And this is the single instance of FakeModule whose __dict__ we keep
920 # copying and clearing for reuse on each %run
951 # copying and clearing for reuse on each %run
921 self._user_main_module = FakeModule()
952 self._user_main_module = FakeModule()
922
953
923 # A table holding all the namespaces IPython deals with, so that
954 # A table holding all the namespaces IPython deals with, so that
924 # introspection facilities can search easily.
955 # introspection facilities can search easily.
925 self.ns_table = {'user_global':self.user_module.__dict__,
956 self.ns_table = {'user_global':self.user_module.__dict__,
926 'user_local':self.user_ns,
957 'user_local':self.user_ns,
927 'builtin':builtin_mod.__dict__
958 'builtin':builtin_mod.__dict__
928 }
959 }
929
960
930 @property
961 @property
931 def user_global_ns(self):
962 def user_global_ns(self):
932 return self.user_module.__dict__
963 return self.user_module.__dict__
933
964
934 def prepare_user_module(self, user_module=None, user_ns=None):
965 def prepare_user_module(self, user_module=None, user_ns=None):
935 """Prepare the module and namespace in which user code will be run.
966 """Prepare the module and namespace in which user code will be run.
936
967
937 When IPython is started normally, both parameters are None: a new module
968 When IPython is started normally, both parameters are None: a new module
938 is created automatically, and its __dict__ used as the namespace.
969 is created automatically, and its __dict__ used as the namespace.
939
970
940 If only user_module is provided, its __dict__ is used as the namespace.
971 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
972 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
973 becomes the global namespace. If both are provided (as they may be
943 when embedding), user_ns is the local namespace, and user_module
974 when embedding), user_ns is the local namespace, and user_module
944 provides the global namespace.
975 provides the global namespace.
945
976
946 Parameters
977 Parameters
947 ----------
978 ----------
948 user_module : module, optional
979 user_module : module, optional
949 The current user module in which IPython is being run. If None,
980 The current user module in which IPython is being run. If None,
950 a clean module will be created.
981 a clean module will be created.
951 user_ns : dict, optional
982 user_ns : dict, optional
952 A namespace in which to run interactive commands.
983 A namespace in which to run interactive commands.
953
984
954 Returns
985 Returns
955 -------
986 -------
956 A tuple of user_module and user_ns, each properly initialised.
987 A tuple of user_module and user_ns, each properly initialised.
957 """
988 """
958 if user_module is None and user_ns is not None:
989 if user_module is None and user_ns is not None:
959 user_ns.setdefault("__name__", "__main__")
990 user_ns.setdefault("__name__", "__main__")
960 class DummyMod(object):
991 class DummyMod(object):
961 "A dummy module used for IPython's interactive namespace."
992 "A dummy module used for IPython's interactive namespace."
962 pass
993 pass
963 user_module = DummyMod()
994 user_module = DummyMod()
964 user_module.__dict__ = user_ns
995 user_module.__dict__ = user_ns
965
996
966 if user_module is None:
997 if user_module is None:
967 user_module = types.ModuleType("__main__",
998 user_module = types.ModuleType("__main__",
968 doc="Automatically created module for IPython interactive environment")
999 doc="Automatically created module for IPython interactive environment")
969
1000
970 # We must ensure that __builtin__ (without the final 's') is always
1001 # We must ensure that __builtin__ (without the final 's') is always
971 # available and pointing to the __builtin__ *module*. For more details:
1002 # available and pointing to the __builtin__ *module*. For more details:
972 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1003 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
973 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1004 user_module.__dict__.setdefault('__builtin__', builtin_mod)
974 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1005 user_module.__dict__.setdefault('__builtins__', builtin_mod)
975
1006
976 if user_ns is None:
1007 if user_ns is None:
977 user_ns = user_module.__dict__
1008 user_ns = user_module.__dict__
978
1009
979 return user_module, user_ns
1010 return user_module, user_ns
980
1011
981 def init_sys_modules(self):
1012 def init_sys_modules(self):
982 # We need to insert into sys.modules something that looks like a
1013 # We need to insert into sys.modules something that looks like a
983 # module but which accesses the IPython namespace, for shelve and
1014 # module but which accesses the IPython namespace, for shelve and
984 # pickle to work interactively. Normally they rely on getting
1015 # pickle to work interactively. Normally they rely on getting
985 # everything out of __main__, but for embedding purposes each IPython
1016 # everything out of __main__, but for embedding purposes each IPython
986 # instance has its own private namespace, so we can't go shoving
1017 # instance has its own private namespace, so we can't go shoving
987 # everything into __main__.
1018 # everything into __main__.
988
1019
989 # note, however, that we should only do this for non-embedded
1020 # note, however, that we should only do this for non-embedded
990 # ipythons, which really mimic the __main__.__dict__ with their own
1021 # ipythons, which really mimic the __main__.__dict__ with their own
991 # namespace. Embedded instances, on the other hand, should not do
1022 # namespace. Embedded instances, on the other hand, should not do
992 # this because they need to manage the user local/global namespaces
1023 # this because they need to manage the user local/global namespaces
993 # only, but they live within a 'normal' __main__ (meaning, they
1024 # only, but they live within a 'normal' __main__ (meaning, they
994 # shouldn't overtake the execution environment of the script they're
1025 # shouldn't overtake the execution environment of the script they're
995 # embedded in).
1026 # embedded in).
996
1027
997 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1028 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
998 main_name = self.user_module.__name__
1029 main_name = self.user_module.__name__
999 sys.modules[main_name] = self.user_module
1030 sys.modules[main_name] = self.user_module
1000
1031
1001 def init_user_ns(self):
1032 def init_user_ns(self):
1002 """Initialize all user-visible namespaces to their minimum defaults.
1033 """Initialize all user-visible namespaces to their minimum defaults.
1003
1034
1004 Certain history lists are also initialized here, as they effectively
1035 Certain history lists are also initialized here, as they effectively
1005 act as user namespaces.
1036 act as user namespaces.
1006
1037
1007 Notes
1038 Notes
1008 -----
1039 -----
1009 All data structures here are only filled in, they are NOT reset by this
1040 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
1041 method. If they were not empty before, data will simply be added to
1011 therm.
1042 therm.
1012 """
1043 """
1013 # This function works in two parts: first we put a few things in
1044 # 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
1045 # 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
1046 # 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
1047 # 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)
1048 # session (probably nothing, so theye really only see their own stuff)
1018
1049
1019 # The user dict must *always* have a __builtin__ reference to the
1050 # The user dict must *always* have a __builtin__ reference to the
1020 # Python standard __builtin__ namespace, which must be imported.
1051 # Python standard __builtin__ namespace, which must be imported.
1021 # This is so that certain operations in prompt evaluation can be
1052 # This is so that certain operations in prompt evaluation can be
1022 # reliably executed with builtins. Note that we can NOT use
1053 # reliably executed with builtins. Note that we can NOT use
1023 # __builtins__ (note the 's'), because that can either be a dict or a
1054 # __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
1055 # module, and can even mutate at runtime, depending on the context
1025 # (Python makes no guarantees on it). In contrast, __builtin__ is
1056 # (Python makes no guarantees on it). In contrast, __builtin__ is
1026 # always a module object, though it must be explicitly imported.
1057 # always a module object, though it must be explicitly imported.
1027
1058
1028 # For more details:
1059 # For more details:
1029 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1060 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1030 ns = dict()
1061 ns = dict()
1031
1062
1032 # Put 'help' in the user namespace
1063 # Put 'help' in the user namespace
1033 try:
1064 try:
1034 from site import _Helper
1065 from site import _Helper
1035 ns['help'] = _Helper()
1066 ns['help'] = _Helper()
1036 except ImportError:
1067 except ImportError:
1037 warn('help() not available - check site.py')
1068 warn('help() not available - check site.py')
1038
1069
1039 # make global variables for user access to the histories
1070 # make global variables for user access to the histories
1040 ns['_ih'] = self.history_manager.input_hist_parsed
1071 ns['_ih'] = self.history_manager.input_hist_parsed
1041 ns['_oh'] = self.history_manager.output_hist
1072 ns['_oh'] = self.history_manager.output_hist
1042 ns['_dh'] = self.history_manager.dir_hist
1073 ns['_dh'] = self.history_manager.dir_hist
1043
1074
1044 ns['_sh'] = shadowns
1075 ns['_sh'] = shadowns
1045
1076
1046 # user aliases to input and output histories. These shouldn't show up
1077 # user aliases to input and output histories. These shouldn't show up
1047 # in %who, as they can have very large reprs.
1078 # in %who, as they can have very large reprs.
1048 ns['In'] = self.history_manager.input_hist_parsed
1079 ns['In'] = self.history_manager.input_hist_parsed
1049 ns['Out'] = self.history_manager.output_hist
1080 ns['Out'] = self.history_manager.output_hist
1050
1081
1051 # Store myself as the public api!!!
1082 # Store myself as the public api!!!
1052 ns['get_ipython'] = self.get_ipython
1083 ns['get_ipython'] = self.get_ipython
1053
1084
1054 ns['exit'] = self.exiter
1085 ns['exit'] = self.exiter
1055 ns['quit'] = self.exiter
1086 ns['quit'] = self.exiter
1056
1087
1057 # Sync what we've added so far to user_ns_hidden so these aren't seen
1088 # Sync what we've added so far to user_ns_hidden so these aren't seen
1058 # by %who
1089 # by %who
1059 self.user_ns_hidden.update(ns)
1090 self.user_ns_hidden.update(ns)
1060
1091
1061 # Anything put into ns now would show up in %who. Think twice before
1092 # 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
1093 # putting anything here, as we really want %who to show the user their
1063 # stuff, not our variables.
1094 # stuff, not our variables.
1064
1095
1065 # Finally, update the real user's namespace
1096 # Finally, update the real user's namespace
1066 self.user_ns.update(ns)
1097 self.user_ns.update(ns)
1067
1098
1068 @property
1099 @property
1069 def all_ns_refs(self):
1100 def all_ns_refs(self):
1070 """Get a list of references to all the namespace dictionaries in which
1101 """Get a list of references to all the namespace dictionaries in which
1071 IPython might store a user-created object.
1102 IPython might store a user-created object.
1072
1103
1073 Note that this does not include the displayhook, which also caches
1104 Note that this does not include the displayhook, which also caches
1074 objects from the output."""
1105 objects from the output."""
1075 return [self.user_ns, self.user_global_ns,
1106 return [self.user_ns, self.user_global_ns,
1076 self._user_main_module.__dict__] + self._main_ns_cache.values()
1107 self._user_main_module.__dict__] + self._main_ns_cache.values()
1077
1108
1078 def reset(self, new_session=True):
1109 def reset(self, new_session=True):
1079 """Clear all internal namespaces, and attempt to release references to
1110 """Clear all internal namespaces, and attempt to release references to
1080 user objects.
1111 user objects.
1081
1112
1082 If new_session is True, a new history session will be opened.
1113 If new_session is True, a new history session will be opened.
1083 """
1114 """
1084 # Clear histories
1115 # Clear histories
1085 self.history_manager.reset(new_session)
1116 self.history_manager.reset(new_session)
1086 # Reset counter used to index all histories
1117 # Reset counter used to index all histories
1087 if new_session:
1118 if new_session:
1088 self.execution_count = 1
1119 self.execution_count = 1
1089
1120
1090 # Flush cached output items
1121 # Flush cached output items
1091 if self.displayhook.do_full_cache:
1122 if self.displayhook.do_full_cache:
1092 self.displayhook.flush()
1123 self.displayhook.flush()
1093
1124
1094 # The main execution namespaces must be cleared very carefully,
1125 # The main execution namespaces must be cleared very carefully,
1095 # skipping the deletion of the builtin-related keys, because doing so
1126 # skipping the deletion of the builtin-related keys, because doing so
1096 # would cause errors in many object's __del__ methods.
1127 # would cause errors in many object's __del__ methods.
1097 if self.user_ns is not self.user_global_ns:
1128 if self.user_ns is not self.user_global_ns:
1098 self.user_ns.clear()
1129 self.user_ns.clear()
1099 ns = self.user_global_ns
1130 ns = self.user_global_ns
1100 drop_keys = set(ns.keys())
1131 drop_keys = set(ns.keys())
1101 drop_keys.discard('__builtin__')
1132 drop_keys.discard('__builtin__')
1102 drop_keys.discard('__builtins__')
1133 drop_keys.discard('__builtins__')
1103 drop_keys.discard('__name__')
1134 drop_keys.discard('__name__')
1104 for k in drop_keys:
1135 for k in drop_keys:
1105 del ns[k]
1136 del ns[k]
1106
1137
1107 self.user_ns_hidden.clear()
1138 self.user_ns_hidden.clear()
1108
1139
1109 # Restore the user namespaces to minimal usability
1140 # Restore the user namespaces to minimal usability
1110 self.init_user_ns()
1141 self.init_user_ns()
1111
1142
1112 # Restore the default and user aliases
1143 # Restore the default and user aliases
1113 self.alias_manager.clear_aliases()
1144 self.alias_manager.clear_aliases()
1114 self.alias_manager.init_aliases()
1145 self.alias_manager.init_aliases()
1115
1146
1116 # Flush the private list of module references kept for script
1147 # Flush the private list of module references kept for script
1117 # execution protection
1148 # execution protection
1118 self.clear_main_mod_cache()
1149 self.clear_main_mod_cache()
1119
1150
1120 # Clear out the namespace from the last %run
1151 # Clear out the namespace from the last %run
1121 self.new_main_mod()
1152 self.new_main_mod()
1122
1153
1123 def del_var(self, varname, by_name=False):
1154 def del_var(self, varname, by_name=False):
1124 """Delete a variable from the various namespaces, so that, as
1155 """Delete a variable from the various namespaces, so that, as
1125 far as possible, we're not keeping any hidden references to it.
1156 far as possible, we're not keeping any hidden references to it.
1126
1157
1127 Parameters
1158 Parameters
1128 ----------
1159 ----------
1129 varname : str
1160 varname : str
1130 The name of the variable to delete.
1161 The name of the variable to delete.
1131 by_name : bool
1162 by_name : bool
1132 If True, delete variables with the given name in each
1163 If True, delete variables with the given name in each
1133 namespace. If False (default), find the variable in the user
1164 namespace. If False (default), find the variable in the user
1134 namespace, and delete references to it.
1165 namespace, and delete references to it.
1135 """
1166 """
1136 if varname in ('__builtin__', '__builtins__'):
1167 if varname in ('__builtin__', '__builtins__'):
1137 raise ValueError("Refusing to delete %s" % varname)
1168 raise ValueError("Refusing to delete %s" % varname)
1138
1169
1139 ns_refs = self.all_ns_refs
1170 ns_refs = self.all_ns_refs
1140
1171
1141 if by_name: # Delete by name
1172 if by_name: # Delete by name
1142 for ns in ns_refs:
1173 for ns in ns_refs:
1143 try:
1174 try:
1144 del ns[varname]
1175 del ns[varname]
1145 except KeyError:
1176 except KeyError:
1146 pass
1177 pass
1147 else: # Delete by object
1178 else: # Delete by object
1148 try:
1179 try:
1149 obj = self.user_ns[varname]
1180 obj = self.user_ns[varname]
1150 except KeyError:
1181 except KeyError:
1151 raise NameError("name '%s' is not defined" % varname)
1182 raise NameError("name '%s' is not defined" % varname)
1152 # Also check in output history
1183 # Also check in output history
1153 ns_refs.append(self.history_manager.output_hist)
1184 ns_refs.append(self.history_manager.output_hist)
1154 for ns in ns_refs:
1185 for ns in ns_refs:
1155 to_delete = [n for n, o in ns.iteritems() if o is obj]
1186 to_delete = [n for n, o in ns.iteritems() if o is obj]
1156 for name in to_delete:
1187 for name in to_delete:
1157 del ns[name]
1188 del ns[name]
1158
1189
1159 # displayhook keeps extra references, but not in a dictionary
1190 # displayhook keeps extra references, but not in a dictionary
1160 for name in ('_', '__', '___'):
1191 for name in ('_', '__', '___'):
1161 if getattr(self.displayhook, name) is obj:
1192 if getattr(self.displayhook, name) is obj:
1162 setattr(self.displayhook, name, None)
1193 setattr(self.displayhook, name, None)
1163
1194
1164 def reset_selective(self, regex=None):
1195 def reset_selective(self, regex=None):
1165 """Clear selective variables from internal namespaces based on a
1196 """Clear selective variables from internal namespaces based on a
1166 specified regular expression.
1197 specified regular expression.
1167
1198
1168 Parameters
1199 Parameters
1169 ----------
1200 ----------
1170 regex : string or compiled pattern, optional
1201 regex : string or compiled pattern, optional
1171 A regular expression pattern that will be used in searching
1202 A regular expression pattern that will be used in searching
1172 variable names in the users namespaces.
1203 variable names in the users namespaces.
1173 """
1204 """
1174 if regex is not None:
1205 if regex is not None:
1175 try:
1206 try:
1176 m = re.compile(regex)
1207 m = re.compile(regex)
1177 except TypeError:
1208 except TypeError:
1178 raise TypeError('regex must be a string or compiled pattern')
1209 raise TypeError('regex must be a string or compiled pattern')
1179 # Search for keys in each namespace that match the given regex
1210 # Search for keys in each namespace that match the given regex
1180 # If a match is found, delete the key/value pair.
1211 # If a match is found, delete the key/value pair.
1181 for ns in self.all_ns_refs:
1212 for ns in self.all_ns_refs:
1182 for var in ns:
1213 for var in ns:
1183 if m.search(var):
1214 if m.search(var):
1184 del ns[var]
1215 del ns[var]
1185
1216
1186 def push(self, variables, interactive=True):
1217 def push(self, variables, interactive=True):
1187 """Inject a group of variables into the IPython user namespace.
1218 """Inject a group of variables into the IPython user namespace.
1188
1219
1189 Parameters
1220 Parameters
1190 ----------
1221 ----------
1191 variables : dict, str or list/tuple of str
1222 variables : dict, str or list/tuple of str
1192 The variables to inject into the user's namespace. If a dict, a
1223 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
1224 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
1225 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
1226 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
1227 give (list/tuple/str) then the variable values looked up in the
1197 callers frame.
1228 callers frame.
1198 interactive : bool
1229 interactive : bool
1199 If True (default), the variables will be listed with the ``who``
1230 If True (default), the variables will be listed with the ``who``
1200 magic.
1231 magic.
1201 """
1232 """
1202 vdict = None
1233 vdict = None
1203
1234
1204 # We need a dict of name/value pairs to do namespace updates.
1235 # We need a dict of name/value pairs to do namespace updates.
1205 if isinstance(variables, dict):
1236 if isinstance(variables, dict):
1206 vdict = variables
1237 vdict = variables
1207 elif isinstance(variables, (basestring, list, tuple)):
1238 elif isinstance(variables, (basestring, list, tuple)):
1208 if isinstance(variables, basestring):
1239 if isinstance(variables, basestring):
1209 vlist = variables.split()
1240 vlist = variables.split()
1210 else:
1241 else:
1211 vlist = variables
1242 vlist = variables
1212 vdict = {}
1243 vdict = {}
1213 cf = sys._getframe(1)
1244 cf = sys._getframe(1)
1214 for name in vlist:
1245 for name in vlist:
1215 try:
1246 try:
1216 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1247 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1217 except:
1248 except:
1218 print ('Could not get variable %s from %s' %
1249 print ('Could not get variable %s from %s' %
1219 (name,cf.f_code.co_name))
1250 (name,cf.f_code.co_name))
1220 else:
1251 else:
1221 raise ValueError('variables must be a dict/str/list/tuple')
1252 raise ValueError('variables must be a dict/str/list/tuple')
1222
1253
1223 # Propagate variables to user namespace
1254 # Propagate variables to user namespace
1224 self.user_ns.update(vdict)
1255 self.user_ns.update(vdict)
1225
1256
1226 # And configure interactive visibility
1257 # And configure interactive visibility
1227 user_ns_hidden = self.user_ns_hidden
1258 user_ns_hidden = self.user_ns_hidden
1228 if interactive:
1259 if interactive:
1229 user_ns_hidden.difference_update(vdict)
1260 user_ns_hidden.difference_update(vdict)
1230 else:
1261 else:
1231 user_ns_hidden.update(vdict)
1262 user_ns_hidden.update(vdict)
1232
1263
1233 def drop_by_id(self, variables):
1264 def drop_by_id(self, variables):
1234 """Remove a dict of variables from the user namespace, if they are the
1265 """Remove a dict of variables from the user namespace, if they are the
1235 same as the values in the dictionary.
1266 same as the values in the dictionary.
1236
1267
1237 This is intended for use by extensions: variables that they've added can
1268 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
1269 be taken back out if they are unloaded, without removing any that the
1239 user has overwritten.
1270 user has overwritten.
1240
1271
1241 Parameters
1272 Parameters
1242 ----------
1273 ----------
1243 variables : dict
1274 variables : dict
1244 A dictionary mapping object names (as strings) to the objects.
1275 A dictionary mapping object names (as strings) to the objects.
1245 """
1276 """
1246 for name, obj in variables.iteritems():
1277 for name, obj in variables.iteritems():
1247 if name in self.user_ns and self.user_ns[name] is obj:
1278 if name in self.user_ns and self.user_ns[name] is obj:
1248 del self.user_ns[name]
1279 del self.user_ns[name]
1249 self.user_ns_hidden.discard(name)
1280 self.user_ns_hidden.discard(name)
1250
1281
1251 #-------------------------------------------------------------------------
1282 #-------------------------------------------------------------------------
1252 # Things related to object introspection
1283 # Things related to object introspection
1253 #-------------------------------------------------------------------------
1284 #-------------------------------------------------------------------------
1254
1285
1255 def _ofind(self, oname, namespaces=None):
1286 def _ofind(self, oname, namespaces=None):
1256 """Find an object in the available namespaces.
1287 """Find an object in the available namespaces.
1257
1288
1258 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1289 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1259
1290
1260 Has special code to detect magic functions.
1291 Has special code to detect magic functions.
1261 """
1292 """
1262 oname = oname.strip()
1293 oname = oname.strip()
1263 #print '1- oname: <%r>' % oname # dbg
1294 #print '1- oname: <%r>' % oname # dbg
1264 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1295 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1265 return dict(found=False)
1296 return dict(found=False)
1266
1297
1267 alias_ns = None
1298 alias_ns = None
1268 if namespaces is None:
1299 if namespaces is None:
1269 # Namespaces to search in:
1300 # Namespaces to search in:
1270 # Put them in a list. The order is important so that we
1301 # Put them in a list. The order is important so that we
1271 # find things in the same order that Python finds them.
1302 # find things in the same order that Python finds them.
1272 namespaces = [ ('Interactive', self.user_ns),
1303 namespaces = [ ('Interactive', self.user_ns),
1273 ('Interactive (global)', self.user_global_ns),
1304 ('Interactive (global)', self.user_global_ns),
1274 ('Python builtin', builtin_mod.__dict__),
1305 ('Python builtin', builtin_mod.__dict__),
1275 ('Alias', self.alias_manager.alias_table),
1306 ('Alias', self.alias_manager.alias_table),
1276 ]
1307 ]
1277 alias_ns = self.alias_manager.alias_table
1308 alias_ns = self.alias_manager.alias_table
1278
1309
1279 # initialize results to 'null'
1310 # initialize results to 'null'
1280 found = False; obj = None; ospace = None; ds = None;
1311 found = False; obj = None; ospace = None; ds = None;
1281 ismagic = False; isalias = False; parent = None
1312 ismagic = False; isalias = False; parent = None
1282
1313
1283 # We need to special-case 'print', which as of python2.6 registers as a
1314 # 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
1315 # function but should only be treated as one if print_function was
1285 # loaded with a future import. In this case, just bail.
1316 # loaded with a future import. In this case, just bail.
1286 if (oname == 'print' and not py3compat.PY3 and not \
1317 if (oname == 'print' and not py3compat.PY3 and not \
1287 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1318 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1288 return {'found':found, 'obj':obj, 'namespace':ospace,
1319 return {'found':found, 'obj':obj, 'namespace':ospace,
1289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1320 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1290
1321
1291 # Look for the given name by splitting it in parts. If the head is
1322 # 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
1323 # found, then we look for all the remaining parts as members, and only
1293 # declare success if we can find them all.
1324 # declare success if we can find them all.
1294 oname_parts = oname.split('.')
1325 oname_parts = oname.split('.')
1295 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1326 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1296 for nsname,ns in namespaces:
1327 for nsname,ns in namespaces:
1297 try:
1328 try:
1298 obj = ns[oname_head]
1329 obj = ns[oname_head]
1299 except KeyError:
1330 except KeyError:
1300 continue
1331 continue
1301 else:
1332 else:
1302 #print 'oname_rest:', oname_rest # dbg
1333 #print 'oname_rest:', oname_rest # dbg
1303 for part in oname_rest:
1334 for part in oname_rest:
1304 try:
1335 try:
1305 parent = obj
1336 parent = obj
1306 obj = getattr(obj,part)
1337 obj = getattr(obj,part)
1307 except:
1338 except:
1308 # Blanket except b/c some badly implemented objects
1339 # Blanket except b/c some badly implemented objects
1309 # allow __getattr__ to raise exceptions other than
1340 # allow __getattr__ to raise exceptions other than
1310 # AttributeError, which then crashes IPython.
1341 # AttributeError, which then crashes IPython.
1311 break
1342 break
1312 else:
1343 else:
1313 # If we finish the for loop (no break), we got all members
1344 # If we finish the for loop (no break), we got all members
1314 found = True
1345 found = True
1315 ospace = nsname
1346 ospace = nsname
1316 if ns == alias_ns:
1347 if ns == alias_ns:
1317 isalias = True
1348 isalias = True
1318 break # namespace loop
1349 break # namespace loop
1319
1350
1320 # Try to see if it's magic
1351 # Try to see if it's magic
1321 if not found:
1352 if not found:
1322 if oname.startswith(ESC_MAGIC):
1353 if oname.startswith(ESC_MAGIC):
1323 oname = oname[1:]
1354 oname = oname[1:]
1324 obj = getattr(self,'magic_'+oname,None)
1355 obj = getattr(self,'magic_'+oname,None)
1325 if obj is not None:
1356 if obj is not None:
1326 found = True
1357 found = True
1327 ospace = 'IPython internal'
1358 ospace = 'IPython internal'
1328 ismagic = True
1359 ismagic = True
1329
1360
1330 # Last try: special-case some literals like '', [], {}, etc:
1361 # Last try: special-case some literals like '', [], {}, etc:
1331 if not found and oname_head in ["''",'""','[]','{}','()']:
1362 if not found and oname_head in ["''",'""','[]','{}','()']:
1332 obj = eval(oname_head)
1363 obj = eval(oname_head)
1333 found = True
1364 found = True
1334 ospace = 'Interactive'
1365 ospace = 'Interactive'
1335
1366
1336 return {'found':found, 'obj':obj, 'namespace':ospace,
1367 return {'found':found, 'obj':obj, 'namespace':ospace,
1337 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1368 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1338
1369
1339 def _ofind_property(self, oname, info):
1370 def _ofind_property(self, oname, info):
1340 """Second part of object finding, to look for property details."""
1371 """Second part of object finding, to look for property details."""
1341 if info.found:
1372 if info.found:
1342 # Get the docstring of the class property if it exists.
1373 # Get the docstring of the class property if it exists.
1343 path = oname.split('.')
1374 path = oname.split('.')
1344 root = '.'.join(path[:-1])
1375 root = '.'.join(path[:-1])
1345 if info.parent is not None:
1376 if info.parent is not None:
1346 try:
1377 try:
1347 target = getattr(info.parent, '__class__')
1378 target = getattr(info.parent, '__class__')
1348 # The object belongs to a class instance.
1379 # The object belongs to a class instance.
1349 try:
1380 try:
1350 target = getattr(target, path[-1])
1381 target = getattr(target, path[-1])
1351 # The class defines the object.
1382 # The class defines the object.
1352 if isinstance(target, property):
1383 if isinstance(target, property):
1353 oname = root + '.__class__.' + path[-1]
1384 oname = root + '.__class__.' + path[-1]
1354 info = Struct(self._ofind(oname))
1385 info = Struct(self._ofind(oname))
1355 except AttributeError: pass
1386 except AttributeError: pass
1356 except AttributeError: pass
1387 except AttributeError: pass
1357
1388
1358 # We return either the new info or the unmodified input if the object
1389 # We return either the new info or the unmodified input if the object
1359 # hadn't been found
1390 # hadn't been found
1360 return info
1391 return info
1361
1392
1362 def _object_find(self, oname, namespaces=None):
1393 def _object_find(self, oname, namespaces=None):
1363 """Find an object and return a struct with info about it."""
1394 """Find an object and return a struct with info about it."""
1364 inf = Struct(self._ofind(oname, namespaces))
1395 inf = Struct(self._ofind(oname, namespaces))
1365 return Struct(self._ofind_property(oname, inf))
1396 return Struct(self._ofind_property(oname, inf))
1366
1397
1367 def _inspect(self, meth, oname, namespaces=None, **kw):
1398 def _inspect(self, meth, oname, namespaces=None, **kw):
1368 """Generic interface to the inspector system.
1399 """Generic interface to the inspector system.
1369
1400
1370 This function is meant to be called by pdef, pdoc & friends."""
1401 This function is meant to be called by pdef, pdoc & friends."""
1371 info = self._object_find(oname)
1402 info = self._object_find(oname)
1372 if info.found:
1403 if info.found:
1373 pmethod = getattr(self.inspector, meth)
1404 pmethod = getattr(self.inspector, meth)
1374 formatter = format_screen if info.ismagic else None
1405 formatter = format_screen if info.ismagic else None
1375 if meth == 'pdoc':
1406 if meth == 'pdoc':
1376 pmethod(info.obj, oname, formatter)
1407 pmethod(info.obj, oname, formatter)
1377 elif meth == 'pinfo':
1408 elif meth == 'pinfo':
1378 pmethod(info.obj, oname, formatter, info, **kw)
1409 pmethod(info.obj, oname, formatter, info, **kw)
1379 else:
1410 else:
1380 pmethod(info.obj, oname)
1411 pmethod(info.obj, oname)
1381 else:
1412 else:
1382 print 'Object `%s` not found.' % oname
1413 print 'Object `%s` not found.' % oname
1383 return 'not found' # so callers can take other action
1414 return 'not found' # so callers can take other action
1384
1415
1385 def object_inspect(self, oname):
1416 def object_inspect(self, oname):
1386 with self.builtin_trap:
1417 with self.builtin_trap:
1387 info = self._object_find(oname)
1418 info = self._object_find(oname)
1388 if info.found:
1419 if info.found:
1389 return self.inspector.info(info.obj, oname, info=info)
1420 return self.inspector.info(info.obj, oname, info=info)
1390 else:
1421 else:
1391 return oinspect.object_info(name=oname, found=False)
1422 return oinspect.object_info(name=oname, found=False)
1392
1423
1393 #-------------------------------------------------------------------------
1424 #-------------------------------------------------------------------------
1394 # Things related to history management
1425 # Things related to history management
1395 #-------------------------------------------------------------------------
1426 #-------------------------------------------------------------------------
1396
1427
1397 def init_history(self):
1428 def init_history(self):
1398 """Sets up the command history, and starts regular autosaves."""
1429 """Sets up the command history, and starts regular autosaves."""
1399 self.history_manager = HistoryManager(shell=self, config=self.config)
1430 self.history_manager = HistoryManager(shell=self, config=self.config)
1400 self.configurables.append(self.history_manager)
1431 self.configurables.append(self.history_manager)
1401
1432
1402 #-------------------------------------------------------------------------
1433 #-------------------------------------------------------------------------
1403 # Things related to exception handling and tracebacks (not debugging)
1434 # Things related to exception handling and tracebacks (not debugging)
1404 #-------------------------------------------------------------------------
1435 #-------------------------------------------------------------------------
1405
1436
1406 def init_traceback_handlers(self, custom_exceptions):
1437 def init_traceback_handlers(self, custom_exceptions):
1407 # Syntax error handler.
1438 # Syntax error handler.
1408 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1439 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1409
1440
1410 # The interactive one is initialized with an offset, meaning we always
1441 # 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
1442 # want to remove the topmost item in the traceback, which is our own
1412 # internal code. Valid modes: ['Plain','Context','Verbose']
1443 # internal code. Valid modes: ['Plain','Context','Verbose']
1413 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1444 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1414 color_scheme='NoColor',
1445 color_scheme='NoColor',
1415 tb_offset = 1,
1446 tb_offset = 1,
1416 check_cache=self.compile.check_cache)
1447 check_cache=self.compile.check_cache)
1417
1448
1418 # The instance will store a pointer to the system-wide exception hook,
1449 # 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
1450 # so that runtime code (such as magics) can access it. This is because
1420 # during the read-eval loop, it may get temporarily overwritten.
1451 # during the read-eval loop, it may get temporarily overwritten.
1421 self.sys_excepthook = sys.excepthook
1452 self.sys_excepthook = sys.excepthook
1422
1453
1423 # and add any custom exception handlers the user may have specified
1454 # and add any custom exception handlers the user may have specified
1424 self.set_custom_exc(*custom_exceptions)
1455 self.set_custom_exc(*custom_exceptions)
1425
1456
1426 # Set the exception mode
1457 # Set the exception mode
1427 self.InteractiveTB.set_mode(mode=self.xmode)
1458 self.InteractiveTB.set_mode(mode=self.xmode)
1428
1459
1429 def set_custom_exc(self, exc_tuple, handler):
1460 def set_custom_exc(self, exc_tuple, handler):
1430 """set_custom_exc(exc_tuple,handler)
1461 """set_custom_exc(exc_tuple,handler)
1431
1462
1432 Set a custom exception handler, which will be called if any of the
1463 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
1464 exceptions in exc_tuple occur in the mainloop (specifically, in the
1434 run_code() method).
1465 run_code() method).
1435
1466
1436 Parameters
1467 Parameters
1437 ----------
1468 ----------
1438
1469
1439 exc_tuple : tuple of exception classes
1470 exc_tuple : tuple of exception classes
1440 A *tuple* of exception classes, for which to call the defined
1471 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
1472 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
1473 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::
1474 you only want to trap a single exception, use a singleton tuple::
1444
1475
1445 exc_tuple == (MyCustomException,)
1476 exc_tuple == (MyCustomException,)
1446
1477
1447 handler : callable
1478 handler : callable
1448 handler must have the following signature::
1479 handler must have the following signature::
1449
1480
1450 def my_handler(self, etype, value, tb, tb_offset=None):
1481 def my_handler(self, etype, value, tb, tb_offset=None):
1451 ...
1482 ...
1452 return structured_traceback
1483 return structured_traceback
1453
1484
1454 Your handler must return a structured traceback (a list of strings),
1485 Your handler must return a structured traceback (a list of strings),
1455 or None.
1486 or None.
1456
1487
1457 This will be made into an instance method (via types.MethodType)
1488 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
1489 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
1490 listed in the exc_tuple are caught. If the handler is None, an
1460 internal basic one is used, which just prints basic info.
1491 internal basic one is used, which just prints basic info.
1461
1492
1462 To protect IPython from crashes, if your handler ever raises an
1493 To protect IPython from crashes, if your handler ever raises an
1463 exception or returns an invalid result, it will be immediately
1494 exception or returns an invalid result, it will be immediately
1464 disabled.
1495 disabled.
1465
1496
1466 WARNING: by putting in your own exception handler into IPython's main
1497 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
1498 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."""
1499 facility should only be used if you really know what you are doing."""
1469
1500
1470 assert type(exc_tuple)==type(()) , \
1501 assert type(exc_tuple)==type(()) , \
1471 "The custom exceptions must be given AS A TUPLE."
1502 "The custom exceptions must be given AS A TUPLE."
1472
1503
1473 def dummy_handler(self,etype,value,tb,tb_offset=None):
1504 def dummy_handler(self,etype,value,tb,tb_offset=None):
1474 print '*** Simple custom exception handler ***'
1505 print '*** Simple custom exception handler ***'
1475 print 'Exception type :',etype
1506 print 'Exception type :',etype
1476 print 'Exception value:',value
1507 print 'Exception value:',value
1477 print 'Traceback :',tb
1508 print 'Traceback :',tb
1478 #print 'Source code :','\n'.join(self.buffer)
1509 #print 'Source code :','\n'.join(self.buffer)
1479
1510
1480 def validate_stb(stb):
1511 def validate_stb(stb):
1481 """validate structured traceback return type
1512 """validate structured traceback return type
1482
1513
1483 return type of CustomTB *should* be a list of strings, but allow
1514 return type of CustomTB *should* be a list of strings, but allow
1484 single strings or None, which are harmless.
1515 single strings or None, which are harmless.
1485
1516
1486 This function will *always* return a list of strings,
1517 This function will *always* return a list of strings,
1487 and will raise a TypeError if stb is inappropriate.
1518 and will raise a TypeError if stb is inappropriate.
1488 """
1519 """
1489 msg = "CustomTB must return list of strings, not %r" % stb
1520 msg = "CustomTB must return list of strings, not %r" % stb
1490 if stb is None:
1521 if stb is None:
1491 return []
1522 return []
1492 elif isinstance(stb, basestring):
1523 elif isinstance(stb, basestring):
1493 return [stb]
1524 return [stb]
1494 elif not isinstance(stb, list):
1525 elif not isinstance(stb, list):
1495 raise TypeError(msg)
1526 raise TypeError(msg)
1496 # it's a list
1527 # it's a list
1497 for line in stb:
1528 for line in stb:
1498 # check every element
1529 # check every element
1499 if not isinstance(line, basestring):
1530 if not isinstance(line, basestring):
1500 raise TypeError(msg)
1531 raise TypeError(msg)
1501 return stb
1532 return stb
1502
1533
1503 if handler is None:
1534 if handler is None:
1504 wrapped = dummy_handler
1535 wrapped = dummy_handler
1505 else:
1536 else:
1506 def wrapped(self,etype,value,tb,tb_offset=None):
1537 def wrapped(self,etype,value,tb,tb_offset=None):
1507 """wrap CustomTB handler, to protect IPython from user code
1538 """wrap CustomTB handler, to protect IPython from user code
1508
1539
1509 This makes it harder (but not impossible) for custom exception
1540 This makes it harder (but not impossible) for custom exception
1510 handlers to crash IPython.
1541 handlers to crash IPython.
1511 """
1542 """
1512 try:
1543 try:
1513 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1544 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1514 return validate_stb(stb)
1545 return validate_stb(stb)
1515 except:
1546 except:
1516 # clear custom handler immediately
1547 # clear custom handler immediately
1517 self.set_custom_exc((), None)
1548 self.set_custom_exc((), None)
1518 print >> io.stderr, "Custom TB Handler failed, unregistering"
1549 print >> io.stderr, "Custom TB Handler failed, unregistering"
1519 # show the exception in handler first
1550 # show the exception in handler first
1520 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1551 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1521 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1552 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1522 print >> io.stdout, "The original exception:"
1553 print >> io.stdout, "The original exception:"
1523 stb = self.InteractiveTB.structured_traceback(
1554 stb = self.InteractiveTB.structured_traceback(
1524 (etype,value,tb), tb_offset=tb_offset
1555 (etype,value,tb), tb_offset=tb_offset
1525 )
1556 )
1526 return stb
1557 return stb
1527
1558
1528 self.CustomTB = types.MethodType(wrapped,self)
1559 self.CustomTB = types.MethodType(wrapped,self)
1529 self.custom_exceptions = exc_tuple
1560 self.custom_exceptions = exc_tuple
1530
1561
1531 def excepthook(self, etype, value, tb):
1562 def excepthook(self, etype, value, tb):
1532 """One more defense for GUI apps that call sys.excepthook.
1563 """One more defense for GUI apps that call sys.excepthook.
1533
1564
1534 GUI frameworks like wxPython trap exceptions and call
1565 GUI frameworks like wxPython trap exceptions and call
1535 sys.excepthook themselves. I guess this is a feature that
1566 sys.excepthook themselves. I guess this is a feature that
1536 enables them to keep running after exceptions that would
1567 enables them to keep running after exceptions that would
1537 otherwise kill their mainloop. This is a bother for IPython
1568 otherwise kill their mainloop. This is a bother for IPython
1538 which excepts to catch all of the program exceptions with a try:
1569 which excepts to catch all of the program exceptions with a try:
1539 except: statement.
1570 except: statement.
1540
1571
1541 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1572 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
1573 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
1574 IPython crashed. In order to work around this, we can disable the
1544 CrashHandler and replace it with this excepthook instead, which prints a
1575 CrashHandler and replace it with this excepthook instead, which prints a
1545 regular traceback using our InteractiveTB. In this fashion, apps which
1576 regular traceback using our InteractiveTB. In this fashion, apps which
1546 call sys.excepthook will generate a regular-looking exception from
1577 call sys.excepthook will generate a regular-looking exception from
1547 IPython, and the CrashHandler will only be triggered by real IPython
1578 IPython, and the CrashHandler will only be triggered by real IPython
1548 crashes.
1579 crashes.
1549
1580
1550 This hook should be used sparingly, only in places which are not likely
1581 This hook should be used sparingly, only in places which are not likely
1551 to be true IPython errors.
1582 to be true IPython errors.
1552 """
1583 """
1553 self.showtraceback((etype,value,tb),tb_offset=0)
1584 self.showtraceback((etype,value,tb),tb_offset=0)
1554
1585
1555 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1586 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1556 exception_only=False):
1587 exception_only=False):
1557 """Display the exception that just occurred.
1588 """Display the exception that just occurred.
1558
1589
1559 If nothing is known about the exception, this is the method which
1590 If nothing is known about the exception, this is the method which
1560 should be used throughout the code for presenting user tracebacks,
1591 should be used throughout the code for presenting user tracebacks,
1561 rather than directly invoking the InteractiveTB object.
1592 rather than directly invoking the InteractiveTB object.
1562
1593
1563 A specific showsyntaxerror() also exists, but this method can take
1594 A specific showsyntaxerror() also exists, but this method can take
1564 care of calling it if needed, so unless you are explicitly catching a
1595 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
1596 SyntaxError exception, don't try to analyze the stack manually and
1566 simply call this method."""
1597 simply call this method."""
1567
1598
1568 try:
1599 try:
1569 if exc_tuple is None:
1600 if exc_tuple is None:
1570 etype, value, tb = sys.exc_info()
1601 etype, value, tb = sys.exc_info()
1571 else:
1602 else:
1572 etype, value, tb = exc_tuple
1603 etype, value, tb = exc_tuple
1573
1604
1574 if etype is None:
1605 if etype is None:
1575 if hasattr(sys, 'last_type'):
1606 if hasattr(sys, 'last_type'):
1576 etype, value, tb = sys.last_type, sys.last_value, \
1607 etype, value, tb = sys.last_type, sys.last_value, \
1577 sys.last_traceback
1608 sys.last_traceback
1578 else:
1609 else:
1579 self.write_err('No traceback available to show.\n')
1610 self.write_err('No traceback available to show.\n')
1580 return
1611 return
1581
1612
1582 if etype is SyntaxError:
1613 if etype is SyntaxError:
1583 # Though this won't be called by syntax errors in the input
1614 # Though this won't be called by syntax errors in the input
1584 # line, there may be SyntaxError cases with imported code.
1615 # line, there may be SyntaxError cases with imported code.
1585 self.showsyntaxerror(filename)
1616 self.showsyntaxerror(filename)
1586 elif etype is UsageError:
1617 elif etype is UsageError:
1587 self.write_err("UsageError: %s" % value)
1618 self.write_err("UsageError: %s" % value)
1588 else:
1619 else:
1589 # WARNING: these variables are somewhat deprecated and not
1620 # WARNING: these variables are somewhat deprecated and not
1590 # necessarily safe to use in a threaded environment, but tools
1621 # necessarily safe to use in a threaded environment, but tools
1591 # like pdb depend on their existence, so let's set them. If we
1622 # 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.
1623 # find problems in the field, we'll need to revisit their use.
1593 sys.last_type = etype
1624 sys.last_type = etype
1594 sys.last_value = value
1625 sys.last_value = value
1595 sys.last_traceback = tb
1626 sys.last_traceback = tb
1596 if etype in self.custom_exceptions:
1627 if etype in self.custom_exceptions:
1597 stb = self.CustomTB(etype, value, tb, tb_offset)
1628 stb = self.CustomTB(etype, value, tb, tb_offset)
1598 else:
1629 else:
1599 if exception_only:
1630 if exception_only:
1600 stb = ['An exception has occurred, use %tb to see '
1631 stb = ['An exception has occurred, use %tb to see '
1601 'the full traceback.\n']
1632 'the full traceback.\n']
1602 stb.extend(self.InteractiveTB.get_exception_only(etype,
1633 stb.extend(self.InteractiveTB.get_exception_only(etype,
1603 value))
1634 value))
1604 else:
1635 else:
1605 stb = self.InteractiveTB.structured_traceback(etype,
1636 stb = self.InteractiveTB.structured_traceback(etype,
1606 value, tb, tb_offset=tb_offset)
1637 value, tb, tb_offset=tb_offset)
1607
1638
1608 self._showtraceback(etype, value, stb)
1639 self._showtraceback(etype, value, stb)
1609 if self.call_pdb:
1640 if self.call_pdb:
1610 # drop into debugger
1641 # drop into debugger
1611 self.debugger(force=True)
1642 self.debugger(force=True)
1612 return
1643 return
1613
1644
1614 # Actually show the traceback
1645 # Actually show the traceback
1615 self._showtraceback(etype, value, stb)
1646 self._showtraceback(etype, value, stb)
1616
1647
1617 except KeyboardInterrupt:
1648 except KeyboardInterrupt:
1618 self.write_err("\nKeyboardInterrupt\n")
1649 self.write_err("\nKeyboardInterrupt\n")
1619
1650
1620 def _showtraceback(self, etype, evalue, stb):
1651 def _showtraceback(self, etype, evalue, stb):
1621 """Actually show a traceback.
1652 """Actually show a traceback.
1622
1653
1623 Subclasses may override this method to put the traceback on a different
1654 Subclasses may override this method to put the traceback on a different
1624 place, like a side channel.
1655 place, like a side channel.
1625 """
1656 """
1626 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1657 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1627
1658
1628 def showsyntaxerror(self, filename=None):
1659 def showsyntaxerror(self, filename=None):
1629 """Display the syntax error that just occurred.
1660 """Display the syntax error that just occurred.
1630
1661
1631 This doesn't display a stack trace because there isn't one.
1662 This doesn't display a stack trace because there isn't one.
1632
1663
1633 If a filename is given, it is stuffed in the exception instead
1664 If a filename is given, it is stuffed in the exception instead
1634 of what was there before (because Python's parser always uses
1665 of what was there before (because Python's parser always uses
1635 "<string>" when reading from a string).
1666 "<string>" when reading from a string).
1636 """
1667 """
1637 etype, value, last_traceback = sys.exc_info()
1668 etype, value, last_traceback = sys.exc_info()
1638
1669
1639 # See note about these variables in showtraceback() above
1670 # See note about these variables in showtraceback() above
1640 sys.last_type = etype
1671 sys.last_type = etype
1641 sys.last_value = value
1672 sys.last_value = value
1642 sys.last_traceback = last_traceback
1673 sys.last_traceback = last_traceback
1643
1674
1644 if filename and etype is SyntaxError:
1675 if filename and etype is SyntaxError:
1645 # Work hard to stuff the correct filename in the exception
1676 # Work hard to stuff the correct filename in the exception
1646 try:
1677 try:
1647 msg, (dummy_filename, lineno, offset, line) = value
1678 msg, (dummy_filename, lineno, offset, line) = value
1648 except:
1679 except:
1649 # Not the format we expect; leave it alone
1680 # Not the format we expect; leave it alone
1650 pass
1681 pass
1651 else:
1682 else:
1652 # Stuff in the right filename
1683 # Stuff in the right filename
1653 try:
1684 try:
1654 # Assume SyntaxError is a class exception
1685 # Assume SyntaxError is a class exception
1655 value = SyntaxError(msg, (filename, lineno, offset, line))
1686 value = SyntaxError(msg, (filename, lineno, offset, line))
1656 except:
1687 except:
1657 # If that failed, assume SyntaxError is a string
1688 # If that failed, assume SyntaxError is a string
1658 value = msg, (filename, lineno, offset, line)
1689 value = msg, (filename, lineno, offset, line)
1659 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1690 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1660 self._showtraceback(etype, value, stb)
1691 self._showtraceback(etype, value, stb)
1661
1692
1662 # This is overridden in TerminalInteractiveShell to show a message about
1693 # This is overridden in TerminalInteractiveShell to show a message about
1663 # the %paste magic.
1694 # the %paste magic.
1664 def showindentationerror(self):
1695 def showindentationerror(self):
1665 """Called by run_cell when there's an IndentationError in code entered
1696 """Called by run_cell when there's an IndentationError in code entered
1666 at the prompt.
1697 at the prompt.
1667
1698
1668 This is overridden in TerminalInteractiveShell to show a message about
1699 This is overridden in TerminalInteractiveShell to show a message about
1669 the %paste magic."""
1700 the %paste magic."""
1670 self.showsyntaxerror()
1701 self.showsyntaxerror()
1671
1702
1672 #-------------------------------------------------------------------------
1703 #-------------------------------------------------------------------------
1673 # Things related to readline
1704 # Things related to readline
1674 #-------------------------------------------------------------------------
1705 #-------------------------------------------------------------------------
1675
1706
1676 def init_readline(self):
1707 def init_readline(self):
1677 """Command history completion/saving/reloading."""
1708 """Command history completion/saving/reloading."""
1678
1709
1679 if self.readline_use:
1710 if self.readline_use:
1680 import IPython.utils.rlineimpl as readline
1711 import IPython.utils.rlineimpl as readline
1681
1712
1682 self.rl_next_input = None
1713 self.rl_next_input = None
1683 self.rl_do_indent = False
1714 self.rl_do_indent = False
1684
1715
1685 if not self.readline_use or not readline.have_readline:
1716 if not self.readline_use or not readline.have_readline:
1686 self.has_readline = False
1717 self.has_readline = False
1687 self.readline = None
1718 self.readline = None
1688 # Set a number of methods that depend on readline to be no-op
1719 # Set a number of methods that depend on readline to be no-op
1689 self.readline_no_record = no_op_context
1720 self.readline_no_record = no_op_context
1690 self.set_readline_completer = no_op
1721 self.set_readline_completer = no_op
1691 self.set_custom_completer = no_op
1722 self.set_custom_completer = no_op
1692 self.set_completer_frame = no_op
1723 self.set_completer_frame = no_op
1693 if self.readline_use:
1724 if self.readline_use:
1694 warn('Readline services not available or not loaded.')
1725 warn('Readline services not available or not loaded.')
1695 else:
1726 else:
1696 self.has_readline = True
1727 self.has_readline = True
1697 self.readline = readline
1728 self.readline = readline
1698 sys.modules['readline'] = readline
1729 sys.modules['readline'] = readline
1699
1730
1700 # Platform-specific configuration
1731 # Platform-specific configuration
1701 if os.name == 'nt':
1732 if os.name == 'nt':
1702 # FIXME - check with Frederick to see if we can harmonize
1733 # FIXME - check with Frederick to see if we can harmonize
1703 # naming conventions with pyreadline to avoid this
1734 # naming conventions with pyreadline to avoid this
1704 # platform-dependent check
1735 # platform-dependent check
1705 self.readline_startup_hook = readline.set_pre_input_hook
1736 self.readline_startup_hook = readline.set_pre_input_hook
1706 else:
1737 else:
1707 self.readline_startup_hook = readline.set_startup_hook
1738 self.readline_startup_hook = readline.set_startup_hook
1708
1739
1709 # Load user's initrc file (readline config)
1740 # Load user's initrc file (readline config)
1710 # Or if libedit is used, load editrc.
1741 # Or if libedit is used, load editrc.
1711 inputrc_name = os.environ.get('INPUTRC')
1742 inputrc_name = os.environ.get('INPUTRC')
1712 if inputrc_name is None:
1743 if inputrc_name is None:
1713 inputrc_name = '.inputrc'
1744 inputrc_name = '.inputrc'
1714 if readline.uses_libedit:
1745 if readline.uses_libedit:
1715 inputrc_name = '.editrc'
1746 inputrc_name = '.editrc'
1716 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1747 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1717 if os.path.isfile(inputrc_name):
1748 if os.path.isfile(inputrc_name):
1718 try:
1749 try:
1719 readline.read_init_file(inputrc_name)
1750 readline.read_init_file(inputrc_name)
1720 except:
1751 except:
1721 warn('Problems reading readline initialization file <%s>'
1752 warn('Problems reading readline initialization file <%s>'
1722 % inputrc_name)
1753 % inputrc_name)
1723
1754
1724 # Configure readline according to user's prefs
1755 # Configure readline according to user's prefs
1725 # This is only done if GNU readline is being used. If libedit
1756 # This is only done if GNU readline is being used. If libedit
1726 # is being used (as on Leopard) the readline config is
1757 # is being used (as on Leopard) the readline config is
1727 # not run as the syntax for libedit is different.
1758 # not run as the syntax for libedit is different.
1728 if not readline.uses_libedit:
1759 if not readline.uses_libedit:
1729 for rlcommand in self.readline_parse_and_bind:
1760 for rlcommand in self.readline_parse_and_bind:
1730 #print "loading rl:",rlcommand # dbg
1761 #print "loading rl:",rlcommand # dbg
1731 readline.parse_and_bind(rlcommand)
1762 readline.parse_and_bind(rlcommand)
1732
1763
1733 # Remove some chars from the delimiters list. If we encounter
1764 # Remove some chars from the delimiters list. If we encounter
1734 # unicode chars, discard them.
1765 # unicode chars, discard them.
1735 delims = readline.get_completer_delims()
1766 delims = readline.get_completer_delims()
1736 if not py3compat.PY3:
1767 if not py3compat.PY3:
1737 delims = delims.encode("ascii", "ignore")
1768 delims = delims.encode("ascii", "ignore")
1738 for d in self.readline_remove_delims:
1769 for d in self.readline_remove_delims:
1739 delims = delims.replace(d, "")
1770 delims = delims.replace(d, "")
1740 delims = delims.replace(ESC_MAGIC, '')
1771 delims = delims.replace(ESC_MAGIC, '')
1741 readline.set_completer_delims(delims)
1772 readline.set_completer_delims(delims)
1742 # otherwise we end up with a monster history after a while:
1773 # otherwise we end up with a monster history after a while:
1743 readline.set_history_length(self.history_length)
1774 readline.set_history_length(self.history_length)
1744
1775
1745 self.refill_readline_hist()
1776 self.refill_readline_hist()
1746 self.readline_no_record = ReadlineNoRecord(self)
1777 self.readline_no_record = ReadlineNoRecord(self)
1747
1778
1748 # Configure auto-indent for all platforms
1779 # Configure auto-indent for all platforms
1749 self.set_autoindent(self.autoindent)
1780 self.set_autoindent(self.autoindent)
1750
1781
1751 def refill_readline_hist(self):
1782 def refill_readline_hist(self):
1752 # Load the last 1000 lines from history
1783 # Load the last 1000 lines from history
1753 self.readline.clear_history()
1784 self.readline.clear_history()
1754 stdin_encoding = sys.stdin.encoding or "utf-8"
1785 stdin_encoding = sys.stdin.encoding or "utf-8"
1755 last_cell = u""
1786 last_cell = u""
1756 for _, _, cell in self.history_manager.get_tail(1000,
1787 for _, _, cell in self.history_manager.get_tail(1000,
1757 include_latest=True):
1788 include_latest=True):
1758 # Ignore blank lines and consecutive duplicates
1789 # Ignore blank lines and consecutive duplicates
1759 cell = cell.rstrip()
1790 cell = cell.rstrip()
1760 if cell and (cell != last_cell):
1791 if cell and (cell != last_cell):
1761 if self.multiline_history:
1792 if self.multiline_history:
1762 self.readline.add_history(py3compat.unicode_to_str(cell,
1793 self.readline.add_history(py3compat.unicode_to_str(cell,
1763 stdin_encoding))
1794 stdin_encoding))
1764 else:
1795 else:
1765 for line in cell.splitlines():
1796 for line in cell.splitlines():
1766 self.readline.add_history(py3compat.unicode_to_str(line,
1797 self.readline.add_history(py3compat.unicode_to_str(line,
1767 stdin_encoding))
1798 stdin_encoding))
1768 last_cell = cell
1799 last_cell = cell
1769
1800
1770 def set_next_input(self, s):
1801 def set_next_input(self, s):
1771 """ Sets the 'default' input string for the next command line.
1802 """ Sets the 'default' input string for the next command line.
1772
1803
1773 Requires readline.
1804 Requires readline.
1774
1805
1775 Example:
1806 Example:
1776
1807
1777 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1808 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1778 [D:\ipython]|2> Hello Word_ # cursor is here
1809 [D:\ipython]|2> Hello Word_ # cursor is here
1779 """
1810 """
1780 self.rl_next_input = py3compat.cast_bytes_py2(s)
1811 self.rl_next_input = py3compat.cast_bytes_py2(s)
1781
1812
1782 # Maybe move this to the terminal subclass?
1813 # Maybe move this to the terminal subclass?
1783 def pre_readline(self):
1814 def pre_readline(self):
1784 """readline hook to be used at the start of each line.
1815 """readline hook to be used at the start of each line.
1785
1816
1786 Currently it handles auto-indent only."""
1817 Currently it handles auto-indent only."""
1787
1818
1788 if self.rl_do_indent:
1819 if self.rl_do_indent:
1789 self.readline.insert_text(self._indent_current_str())
1820 self.readline.insert_text(self._indent_current_str())
1790 if self.rl_next_input is not None:
1821 if self.rl_next_input is not None:
1791 self.readline.insert_text(self.rl_next_input)
1822 self.readline.insert_text(self.rl_next_input)
1792 self.rl_next_input = None
1823 self.rl_next_input = None
1793
1824
1794 def _indent_current_str(self):
1825 def _indent_current_str(self):
1795 """return the current level of indentation as a string"""
1826 """return the current level of indentation as a string"""
1796 return self.input_splitter.indent_spaces * ' '
1827 return self.input_splitter.indent_spaces * ' '
1797
1828
1798 #-------------------------------------------------------------------------
1829 #-------------------------------------------------------------------------
1799 # Things related to text completion
1830 # Things related to text completion
1800 #-------------------------------------------------------------------------
1831 #-------------------------------------------------------------------------
1801
1832
1802 def init_completer(self):
1833 def init_completer(self):
1803 """Initialize the completion machinery.
1834 """Initialize the completion machinery.
1804
1835
1805 This creates completion machinery that can be used by client code,
1836 This creates completion machinery that can be used by client code,
1806 either interactively in-process (typically triggered by the readline
1837 either interactively in-process (typically triggered by the readline
1807 library), programatically (such as in test suites) or out-of-prcess
1838 library), programatically (such as in test suites) or out-of-prcess
1808 (typically over the network by remote frontends).
1839 (typically over the network by remote frontends).
1809 """
1840 """
1810 from IPython.core.completer import IPCompleter
1841 from IPython.core.completer import IPCompleter
1811 from IPython.core.completerlib import (module_completer,
1842 from IPython.core.completerlib import (module_completer,
1812 magic_run_completer, cd_completer)
1843 magic_run_completer, cd_completer)
1813
1844
1814 self.Completer = IPCompleter(shell=self,
1845 self.Completer = IPCompleter(shell=self,
1815 namespace=self.user_ns,
1846 namespace=self.user_ns,
1816 global_namespace=self.user_global_ns,
1847 global_namespace=self.user_global_ns,
1817 alias_table=self.alias_manager.alias_table,
1848 alias_table=self.alias_manager.alias_table,
1818 use_readline=self.has_readline,
1849 use_readline=self.has_readline,
1819 config=self.config,
1850 config=self.config,
1820 )
1851 )
1821 self.configurables.append(self.Completer)
1852 self.configurables.append(self.Completer)
1822
1853
1823 # Add custom completers to the basic ones built into IPCompleter
1854 # Add custom completers to the basic ones built into IPCompleter
1824 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1855 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1825 self.strdispatchers['complete_command'] = sdisp
1856 self.strdispatchers['complete_command'] = sdisp
1826 self.Completer.custom_completers = sdisp
1857 self.Completer.custom_completers = sdisp
1827
1858
1828 self.set_hook('complete_command', module_completer, str_key = 'import')
1859 self.set_hook('complete_command', module_completer, str_key = 'import')
1829 self.set_hook('complete_command', module_completer, str_key = 'from')
1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1830 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1831 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1832
1863
1833 # Only configure readline if we truly are using readline. IPython can
1864 # Only configure readline if we truly are using readline. IPython can
1834 # do tab-completion over the network, in GUIs, etc, where readline
1865 # do tab-completion over the network, in GUIs, etc, where readline
1835 # itself may be absent
1866 # itself may be absent
1836 if self.has_readline:
1867 if self.has_readline:
1837 self.set_readline_completer()
1868 self.set_readline_completer()
1838
1869
1839 def complete(self, text, line=None, cursor_pos=None):
1870 def complete(self, text, line=None, cursor_pos=None):
1840 """Return the completed text and a list of completions.
1871 """Return the completed text and a list of completions.
1841
1872
1842 Parameters
1873 Parameters
1843 ----------
1874 ----------
1844
1875
1845 text : string
1876 text : string
1846 A string of text to be completed on. It can be given as empty and
1877 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
1878 instead a line/position pair are given. In this case, the
1848 completer itself will split the line like readline does.
1879 completer itself will split the line like readline does.
1849
1880
1850 line : string, optional
1881 line : string, optional
1851 The complete line that text is part of.
1882 The complete line that text is part of.
1852
1883
1853 cursor_pos : int, optional
1884 cursor_pos : int, optional
1854 The position of the cursor on the input line.
1885 The position of the cursor on the input line.
1855
1886
1856 Returns
1887 Returns
1857 -------
1888 -------
1858 text : string
1889 text : string
1859 The actual text that was completed.
1890 The actual text that was completed.
1860
1891
1861 matches : list
1892 matches : list
1862 A sorted list with all possible completions.
1893 A sorted list with all possible completions.
1863
1894
1864 The optional arguments allow the completion to take more context into
1895 The optional arguments allow the completion to take more context into
1865 account, and are part of the low-level completion API.
1896 account, and are part of the low-level completion API.
1866
1897
1867 This is a wrapper around the completion mechanism, similar to what
1898 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
1899 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
1900 exposing it as a method, it can be used by other non-readline
1870 environments (such as GUIs) for text completion.
1901 environments (such as GUIs) for text completion.
1871
1902
1872 Simple usage example:
1903 Simple usage example:
1873
1904
1874 In [1]: x = 'hello'
1905 In [1]: x = 'hello'
1875
1906
1876 In [2]: _ip.complete('x.l')
1907 In [2]: _ip.complete('x.l')
1877 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1908 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1878 """
1909 """
1879
1910
1880 # Inject names into __builtin__ so we can complete on the added names.
1911 # Inject names into __builtin__ so we can complete on the added names.
1881 with self.builtin_trap:
1912 with self.builtin_trap:
1882 return self.Completer.complete(text, line, cursor_pos)
1913 return self.Completer.complete(text, line, cursor_pos)
1883
1914
1884 def set_custom_completer(self, completer, pos=0):
1915 def set_custom_completer(self, completer, pos=0):
1885 """Adds a new custom completer function.
1916 """Adds a new custom completer function.
1886
1917
1887 The position argument (defaults to 0) is the index in the completers
1918 The position argument (defaults to 0) is the index in the completers
1888 list where you want the completer to be inserted."""
1919 list where you want the completer to be inserted."""
1889
1920
1890 newcomp = types.MethodType(completer,self.Completer)
1921 newcomp = types.MethodType(completer,self.Completer)
1891 self.Completer.matchers.insert(pos,newcomp)
1922 self.Completer.matchers.insert(pos,newcomp)
1892
1923
1893 def set_readline_completer(self):
1924 def set_readline_completer(self):
1894 """Reset readline's completer to be our own."""
1925 """Reset readline's completer to be our own."""
1895 self.readline.set_completer(self.Completer.rlcomplete)
1926 self.readline.set_completer(self.Completer.rlcomplete)
1896
1927
1897 def set_completer_frame(self, frame=None):
1928 def set_completer_frame(self, frame=None):
1898 """Set the frame of the completer."""
1929 """Set the frame of the completer."""
1899 if frame:
1930 if frame:
1900 self.Completer.namespace = frame.f_locals
1931 self.Completer.namespace = frame.f_locals
1901 self.Completer.global_namespace = frame.f_globals
1932 self.Completer.global_namespace = frame.f_globals
1902 else:
1933 else:
1903 self.Completer.namespace = self.user_ns
1934 self.Completer.namespace = self.user_ns
1904 self.Completer.global_namespace = self.user_global_ns
1935 self.Completer.global_namespace = self.user_global_ns
1905
1936
1906 #-------------------------------------------------------------------------
1937 #-------------------------------------------------------------------------
1907 # Things related to magics
1938 # Things related to magics
1908 #-------------------------------------------------------------------------
1939 #-------------------------------------------------------------------------
1909
1940
1910 def init_magics(self):
1941 def init_magics(self):
1911 # FIXME: Move the color initialization to the DisplayHook, which
1942 # FIXME: Move the color initialization to the DisplayHook, which
1912 # should be split into a prompt manager and displayhook. We probably
1943 # should be split into a prompt manager and displayhook. We probably
1913 # even need a centralize colors management object.
1944 # even need a centralize colors management object.
1914 self.magic_colors(self.colors)
1945 self.magic_colors(self.colors)
1915 # History was moved to a separate module
1946 # History was moved to a separate module
1916 from . import history
1947 from . import history
1917 history.init_ipython(self)
1948 history.init_ipython(self)
1918
1949
1919 def magic(self, arg_s, next_input=None):
1950 def magic(self, arg_s, next_input=None):
1920 """Call a magic function by name.
1951 """Call a magic function by name.
1921
1952
1922 Input: a string containing the name of the magic function to call and
1953 Input: a string containing the name of the magic function to call and
1923 any additional arguments to be passed to the magic.
1954 any additional arguments to be passed to the magic.
1924
1955
1925 magic('name -opt foo bar') is equivalent to typing at the ipython
1956 magic('name -opt foo bar') is equivalent to typing at the ipython
1926 prompt:
1957 prompt:
1927
1958
1928 In[1]: %name -opt foo bar
1959 In[1]: %name -opt foo bar
1929
1960
1930 To call a magic without arguments, simply use magic('name').
1961 To call a magic without arguments, simply use magic('name').
1931
1962
1932 This provides a proper Python function to call IPython's magics in any
1963 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
1964 valid Python code you can type at the interpreter, including loops and
1934 compound statements.
1965 compound statements.
1935 """
1966 """
1936 # Allow setting the next input - this is used if the user does `a=abs?`.
1967 # 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.
1968 # We do this first so that magic functions can override it.
1938 if next_input:
1969 if next_input:
1939 self.set_next_input(next_input)
1970 self.set_next_input(next_input)
1940
1971
1941 args = arg_s.split(' ',1)
1972 args = arg_s.split(' ',1)
1942 magic_name = args[0]
1973 magic_name = args[0]
1943 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1974 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1944
1975
1945 try:
1976 try:
1946 magic_args = args[1]
1977 magic_args = args[1]
1947 except IndexError:
1978 except IndexError:
1948 magic_args = ''
1979 magic_args = ''
1949 fn = getattr(self,'magic_'+magic_name,None)
1980 fn = getattr(self,'magic_'+magic_name,None)
1950 if fn is None:
1981 if fn is None:
1951 error("Magic function `%s` not found." % magic_name)
1982 error("Magic function `%s` not found." % magic_name)
1952 else:
1983 else:
1953 magic_args = self.var_expand(magic_args,1)
1984 magic_args = self.var_expand(magic_args,1)
1954 # Grab local namespace if we need it:
1985 # Grab local namespace if we need it:
1955 if getattr(fn, "needs_local_scope", False):
1986 if getattr(fn, "needs_local_scope", False):
1956 self._magic_locals = sys._getframe(1).f_locals
1987 self._magic_locals = sys._getframe(1).f_locals
1957 with self.builtin_trap:
1988 with self.builtin_trap:
1958 result = fn(magic_args)
1989 result = fn(magic_args)
1959 # Ensure we're not keeping object references around:
1990 # Ensure we're not keeping object references around:
1960 self._magic_locals = {}
1991 self._magic_locals = {}
1961 return result
1992 return result
1962
1993
1963 def define_magic(self, magicname, func):
1994 def define_magic(self, magicname, func):
1964 """Expose own function as magic function for ipython
1995 """Expose own function as magic function for ipython
1965
1996
1966 Example::
1997 Example::
1967
1998
1968 def foo_impl(self,parameter_s=''):
1999 def foo_impl(self,parameter_s=''):
1969 'My very own magic!. (Use docstrings, IPython reads them).'
2000 'My very own magic!. (Use docstrings, IPython reads them).'
1970 print 'Magic function. Passed parameter is between < >:'
2001 print 'Magic function. Passed parameter is between < >:'
1971 print '<%s>' % parameter_s
2002 print '<%s>' % parameter_s
1972 print 'The self object is:', self
2003 print 'The self object is:', self
1973
2004
1974 ip.define_magic('foo',foo_impl)
2005 ip.define_magic('foo',foo_impl)
1975 """
2006 """
1976 im = types.MethodType(func,self)
2007 im = types.MethodType(func,self)
1977 old = getattr(self, "magic_" + magicname, None)
2008 old = getattr(self, "magic_" + magicname, None)
1978 setattr(self, "magic_" + magicname, im)
2009 setattr(self, "magic_" + magicname, im)
1979 return old
2010 return old
1980
2011
1981 #-------------------------------------------------------------------------
2012 #-------------------------------------------------------------------------
1982 # Things related to macros
2013 # Things related to macros
1983 #-------------------------------------------------------------------------
2014 #-------------------------------------------------------------------------
1984
2015
1985 def define_macro(self, name, themacro):
2016 def define_macro(self, name, themacro):
1986 """Define a new macro
2017 """Define a new macro
1987
2018
1988 Parameters
2019 Parameters
1989 ----------
2020 ----------
1990 name : str
2021 name : str
1991 The name of the macro.
2022 The name of the macro.
1992 themacro : str or Macro
2023 themacro : str or Macro
1993 The action to do upon invoking the macro. If a string, a new
2024 The action to do upon invoking the macro. If a string, a new
1994 Macro object is created by passing the string to it.
2025 Macro object is created by passing the string to it.
1995 """
2026 """
1996
2027
1997 from IPython.core import macro
2028 from IPython.core import macro
1998
2029
1999 if isinstance(themacro, basestring):
2030 if isinstance(themacro, basestring):
2000 themacro = macro.Macro(themacro)
2031 themacro = macro.Macro(themacro)
2001 if not isinstance(themacro, macro.Macro):
2032 if not isinstance(themacro, macro.Macro):
2002 raise ValueError('A macro must be a string or a Macro instance.')
2033 raise ValueError('A macro must be a string or a Macro instance.')
2003 self.user_ns[name] = themacro
2034 self.user_ns[name] = themacro
2004
2035
2005 #-------------------------------------------------------------------------
2036 #-------------------------------------------------------------------------
2006 # Things related to the running of system commands
2037 # Things related to the running of system commands
2007 #-------------------------------------------------------------------------
2038 #-------------------------------------------------------------------------
2008
2039
2009 def system_piped(self, cmd):
2040 def system_piped(self, cmd):
2010 """Call the given cmd in a subprocess, piping stdout/err
2041 """Call the given cmd in a subprocess, piping stdout/err
2011
2042
2012 Parameters
2043 Parameters
2013 ----------
2044 ----------
2014 cmd : str
2045 cmd : str
2015 Command to execute (can not end in '&', as background processes are
2046 Command to execute (can not end in '&', as background processes are
2016 not supported. Should not be a command that expects input
2047 not supported. Should not be a command that expects input
2017 other than simple text.
2048 other than simple text.
2018 """
2049 """
2019 if cmd.rstrip().endswith('&'):
2050 if cmd.rstrip().endswith('&'):
2020 # this is *far* from a rigorous test
2051 # this is *far* from a rigorous test
2021 # We do not support backgrounding processes because we either use
2052 # We do not support backgrounding processes because we either use
2022 # pexpect or pipes to read from. Users can always just call
2053 # pexpect or pipes to read from. Users can always just call
2023 # os.system() or use ip.system=ip.system_raw
2054 # os.system() or use ip.system=ip.system_raw
2024 # if they really want a background process.
2055 # if they really want a background process.
2025 raise OSError("Background processes not supported.")
2056 raise OSError("Background processes not supported.")
2026
2057
2027 # we explicitly do NOT return the subprocess status code, because
2058 # we explicitly do NOT return the subprocess status code, because
2028 # a non-None value would trigger :func:`sys.displayhook` calls.
2059 # a non-None value would trigger :func:`sys.displayhook` calls.
2029 # Instead, we store the exit_code in user_ns.
2060 # Instead, we store the exit_code in user_ns.
2030 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2061 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2031
2062
2032 def system_raw(self, cmd):
2063 def system_raw(self, cmd):
2033 """Call the given cmd in a subprocess using os.system
2064 """Call the given cmd in a subprocess using os.system
2034
2065
2035 Parameters
2066 Parameters
2036 ----------
2067 ----------
2037 cmd : str
2068 cmd : str
2038 Command to execute.
2069 Command to execute.
2039 """
2070 """
2040 cmd = self.var_expand(cmd, depth=2)
2071 cmd = self.var_expand(cmd, depth=2)
2041 # protect os.system from UNC paths on Windows, which it can't handle:
2072 # protect os.system from UNC paths on Windows, which it can't handle:
2042 if sys.platform == 'win32':
2073 if sys.platform == 'win32':
2043 from IPython.utils._process_win32 import AvoidUNCPath
2074 from IPython.utils._process_win32 import AvoidUNCPath
2044 with AvoidUNCPath() as path:
2075 with AvoidUNCPath() as path:
2045 if path is not None:
2076 if path is not None:
2046 cmd = '"pushd %s &&"%s' % (path, cmd)
2077 cmd = '"pushd %s &&"%s' % (path, cmd)
2047 cmd = py3compat.unicode_to_str(cmd)
2078 cmd = py3compat.unicode_to_str(cmd)
2048 ec = os.system(cmd)
2079 ec = os.system(cmd)
2049 else:
2080 else:
2050 cmd = py3compat.unicode_to_str(cmd)
2081 cmd = py3compat.unicode_to_str(cmd)
2051 ec = os.system(cmd)
2082 ec = os.system(cmd)
2052
2083
2053 # We explicitly do NOT return the subprocess status code, because
2084 # We explicitly do NOT return the subprocess status code, because
2054 # a non-None value would trigger :func:`sys.displayhook` calls.
2085 # a non-None value would trigger :func:`sys.displayhook` calls.
2055 # Instead, we store the exit_code in user_ns.
2086 # Instead, we store the exit_code in user_ns.
2056 self.user_ns['_exit_code'] = ec
2087 self.user_ns['_exit_code'] = ec
2057
2088
2058 # use piped system by default, because it is better behaved
2089 # use piped system by default, because it is better behaved
2059 system = system_piped
2090 system = system_piped
2060
2091
2061 def getoutput(self, cmd, split=True):
2092 def getoutput(self, cmd, split=True):
2062 """Get output (possibly including stderr) from a subprocess.
2093 """Get output (possibly including stderr) from a subprocess.
2063
2094
2064 Parameters
2095 Parameters
2065 ----------
2096 ----------
2066 cmd : str
2097 cmd : str
2067 Command to execute (can not end in '&', as background processes are
2098 Command to execute (can not end in '&', as background processes are
2068 not supported.
2099 not supported.
2069 split : bool, optional
2100 split : bool, optional
2070
2101
2071 If True, split the output into an IPython SList. Otherwise, an
2102 If True, split the output into an IPython SList. Otherwise, an
2072 IPython LSString is returned. These are objects similar to normal
2103 IPython LSString is returned. These are objects similar to normal
2073 lists and strings, with a few convenience attributes for easier
2104 lists and strings, with a few convenience attributes for easier
2074 manipulation of line-based output. You can use '?' on them for
2105 manipulation of line-based output. You can use '?' on them for
2075 details.
2106 details.
2076 """
2107 """
2077 if cmd.rstrip().endswith('&'):
2108 if cmd.rstrip().endswith('&'):
2078 # this is *far* from a rigorous test
2109 # this is *far* from a rigorous test
2079 raise OSError("Background processes not supported.")
2110 raise OSError("Background processes not supported.")
2080 out = getoutput(self.var_expand(cmd, depth=2))
2111 out = getoutput(self.var_expand(cmd, depth=2))
2081 if split:
2112 if split:
2082 out = SList(out.splitlines())
2113 out = SList(out.splitlines())
2083 else:
2114 else:
2084 out = LSString(out)
2115 out = LSString(out)
2085 return out
2116 return out
2086
2117
2087 #-------------------------------------------------------------------------
2118 #-------------------------------------------------------------------------
2088 # Things related to aliases
2119 # Things related to aliases
2089 #-------------------------------------------------------------------------
2120 #-------------------------------------------------------------------------
2090
2121
2091 def init_alias(self):
2122 def init_alias(self):
2092 self.alias_manager = AliasManager(shell=self, config=self.config)
2123 self.alias_manager = AliasManager(shell=self, config=self.config)
2093 self.configurables.append(self.alias_manager)
2124 self.configurables.append(self.alias_manager)
2094 self.ns_table['alias'] = self.alias_manager.alias_table,
2125 self.ns_table['alias'] = self.alias_manager.alias_table,
2095
2126
2096 #-------------------------------------------------------------------------
2127 #-------------------------------------------------------------------------
2097 # Things related to extensions and plugins
2128 # Things related to extensions and plugins
2098 #-------------------------------------------------------------------------
2129 #-------------------------------------------------------------------------
2099
2130
2100 def init_extension_manager(self):
2131 def init_extension_manager(self):
2101 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2132 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2102 self.configurables.append(self.extension_manager)
2133 self.configurables.append(self.extension_manager)
2103
2134
2104 def init_plugin_manager(self):
2135 def init_plugin_manager(self):
2105 self.plugin_manager = PluginManager(config=self.config)
2136 self.plugin_manager = PluginManager(config=self.config)
2106 self.configurables.append(self.plugin_manager)
2137 self.configurables.append(self.plugin_manager)
2107
2138
2108
2139
2109 #-------------------------------------------------------------------------
2140 #-------------------------------------------------------------------------
2110 # Things related to payloads
2141 # Things related to payloads
2111 #-------------------------------------------------------------------------
2142 #-------------------------------------------------------------------------
2112
2143
2113 def init_payload(self):
2144 def init_payload(self):
2114 self.payload_manager = PayloadManager(config=self.config)
2145 self.payload_manager = PayloadManager(config=self.config)
2115 self.configurables.append(self.payload_manager)
2146 self.configurables.append(self.payload_manager)
2116
2147
2117 #-------------------------------------------------------------------------
2148 #-------------------------------------------------------------------------
2118 # Things related to the prefilter
2149 # Things related to the prefilter
2119 #-------------------------------------------------------------------------
2150 #-------------------------------------------------------------------------
2120
2151
2121 def init_prefilter(self):
2152 def init_prefilter(self):
2122 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2153 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2123 self.configurables.append(self.prefilter_manager)
2154 self.configurables.append(self.prefilter_manager)
2124 # Ultimately this will be refactored in the new interpreter code, but
2155 # Ultimately this will be refactored in the new interpreter code, but
2125 # for now, we should expose the main prefilter method (there's legacy
2156 # for now, we should expose the main prefilter method (there's legacy
2126 # code out there that may rely on this).
2157 # code out there that may rely on this).
2127 self.prefilter = self.prefilter_manager.prefilter_lines
2158 self.prefilter = self.prefilter_manager.prefilter_lines
2128
2159
2129 def auto_rewrite_input(self, cmd):
2160 def auto_rewrite_input(self, cmd):
2130 """Print to the screen the rewritten form of the user's command.
2161 """Print to the screen the rewritten form of the user's command.
2131
2162
2132 This shows visual feedback by rewriting input lines that cause
2163 This shows visual feedback by rewriting input lines that cause
2133 automatic calling to kick in, like::
2164 automatic calling to kick in, like::
2134
2165
2135 /f x
2166 /f x
2136
2167
2137 into::
2168 into::
2138
2169
2139 ------> f(x)
2170 ------> f(x)
2140
2171
2141 after the user's input prompt. This helps the user understand that the
2172 after the user's input prompt. This helps the user understand that the
2142 input line was transformed automatically by IPython.
2173 input line was transformed automatically by IPython.
2143 """
2174 """
2175 if not self.show_rewritten_input:
2176 return
2177
2144 rw = self.prompt_manager.render('rewrite') + cmd
2178 rw = self.prompt_manager.render('rewrite') + cmd
2145
2179
2146 try:
2180 try:
2147 # plain ascii works better w/ pyreadline, on some machines, so
2181 # plain ascii works better w/ pyreadline, on some machines, so
2148 # we use it and only print uncolored rewrite if we have unicode
2182 # we use it and only print uncolored rewrite if we have unicode
2149 rw = str(rw)
2183 rw = str(rw)
2150 print >> io.stdout, rw
2184 print >> io.stdout, rw
2151 except UnicodeEncodeError:
2185 except UnicodeEncodeError:
2152 print "------> " + cmd
2186 print "------> " + cmd
2153
2187
2154 #-------------------------------------------------------------------------
2188 #-------------------------------------------------------------------------
2155 # Things related to extracting values/expressions from kernel and user_ns
2189 # Things related to extracting values/expressions from kernel and user_ns
2156 #-------------------------------------------------------------------------
2190 #-------------------------------------------------------------------------
2157
2191
2158 def _simple_error(self):
2192 def _simple_error(self):
2159 etype, value = sys.exc_info()[:2]
2193 etype, value = sys.exc_info()[:2]
2160 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2194 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2161
2195
2162 def user_variables(self, names):
2196 def user_variables(self, names):
2163 """Get a list of variable names from the user's namespace.
2197 """Get a list of variable names from the user's namespace.
2164
2198
2165 Parameters
2199 Parameters
2166 ----------
2200 ----------
2167 names : list of strings
2201 names : list of strings
2168 A list of names of variables to be read from the user namespace.
2202 A list of names of variables to be read from the user namespace.
2169
2203
2170 Returns
2204 Returns
2171 -------
2205 -------
2172 A dict, keyed by the input names and with the repr() of each value.
2206 A dict, keyed by the input names and with the repr() of each value.
2173 """
2207 """
2174 out = {}
2208 out = {}
2175 user_ns = self.user_ns
2209 user_ns = self.user_ns
2176 for varname in names:
2210 for varname in names:
2177 try:
2211 try:
2178 value = repr(user_ns[varname])
2212 value = repr(user_ns[varname])
2179 except:
2213 except:
2180 value = self._simple_error()
2214 value = self._simple_error()
2181 out[varname] = value
2215 out[varname] = value
2182 return out
2216 return out
2183
2217
2184 def user_expressions(self, expressions):
2218 def user_expressions(self, expressions):
2185 """Evaluate a dict of expressions in the user's namespace.
2219 """Evaluate a dict of expressions in the user's namespace.
2186
2220
2187 Parameters
2221 Parameters
2188 ----------
2222 ----------
2189 expressions : dict
2223 expressions : dict
2190 A dict with string keys and string values. The expression values
2224 A dict with string keys and string values. The expression values
2191 should be valid Python expressions, each of which will be evaluated
2225 should be valid Python expressions, each of which will be evaluated
2192 in the user namespace.
2226 in the user namespace.
2193
2227
2194 Returns
2228 Returns
2195 -------
2229 -------
2196 A dict, keyed like the input expressions dict, with the repr() of each
2230 A dict, keyed like the input expressions dict, with the repr() of each
2197 value.
2231 value.
2198 """
2232 """
2199 out = {}
2233 out = {}
2200 user_ns = self.user_ns
2234 user_ns = self.user_ns
2201 global_ns = self.user_global_ns
2235 global_ns = self.user_global_ns
2202 for key, expr in expressions.iteritems():
2236 for key, expr in expressions.iteritems():
2203 try:
2237 try:
2204 value = repr(eval(expr, global_ns, user_ns))
2238 value = repr(eval(expr, global_ns, user_ns))
2205 except:
2239 except:
2206 value = self._simple_error()
2240 value = self._simple_error()
2207 out[key] = value
2241 out[key] = value
2208 return out
2242 return out
2209
2243
2210 #-------------------------------------------------------------------------
2244 #-------------------------------------------------------------------------
2211 # Things related to the running of code
2245 # Things related to the running of code
2212 #-------------------------------------------------------------------------
2246 #-------------------------------------------------------------------------
2213
2247
2214 def ex(self, cmd):
2248 def ex(self, cmd):
2215 """Execute a normal python statement in user namespace."""
2249 """Execute a normal python statement in user namespace."""
2216 with self.builtin_trap:
2250 with self.builtin_trap:
2217 exec cmd in self.user_global_ns, self.user_ns
2251 exec cmd in self.user_global_ns, self.user_ns
2218
2252
2219 def ev(self, expr):
2253 def ev(self, expr):
2220 """Evaluate python expression expr in user namespace.
2254 """Evaluate python expression expr in user namespace.
2221
2255
2222 Returns the result of evaluation
2256 Returns the result of evaluation
2223 """
2257 """
2224 with self.builtin_trap:
2258 with self.builtin_trap:
2225 return eval(expr, self.user_global_ns, self.user_ns)
2259 return eval(expr, self.user_global_ns, self.user_ns)
2226
2260
2227 def safe_execfile(self, fname, *where, **kw):
2261 def safe_execfile(self, fname, *where, **kw):
2228 """A safe version of the builtin execfile().
2262 """A safe version of the builtin execfile().
2229
2263
2230 This version will never throw an exception, but instead print
2264 This version will never throw an exception, but instead print
2231 helpful error messages to the screen. This only works on pure
2265 helpful error messages to the screen. This only works on pure
2232 Python files with the .py extension.
2266 Python files with the .py extension.
2233
2267
2234 Parameters
2268 Parameters
2235 ----------
2269 ----------
2236 fname : string
2270 fname : string
2237 The name of the file to be executed.
2271 The name of the file to be executed.
2238 where : tuple
2272 where : tuple
2239 One or two namespaces, passed to execfile() as (globals,locals).
2273 One or two namespaces, passed to execfile() as (globals,locals).
2240 If only one is given, it is passed as both.
2274 If only one is given, it is passed as both.
2241 exit_ignore : bool (False)
2275 exit_ignore : bool (False)
2242 If True, then silence SystemExit for non-zero status (it is always
2276 If True, then silence SystemExit for non-zero status (it is always
2243 silenced for zero status, as it is so common).
2277 silenced for zero status, as it is so common).
2244 raise_exceptions : bool (False)
2278 raise_exceptions : bool (False)
2245 If True raise exceptions everywhere. Meant for testing.
2279 If True raise exceptions everywhere. Meant for testing.
2246
2280
2247 """
2281 """
2248 kw.setdefault('exit_ignore', False)
2282 kw.setdefault('exit_ignore', False)
2249 kw.setdefault('raise_exceptions', False)
2283 kw.setdefault('raise_exceptions', False)
2250
2284
2251 fname = os.path.abspath(os.path.expanduser(fname))
2285 fname = os.path.abspath(os.path.expanduser(fname))
2252
2286
2253 # Make sure we can open the file
2287 # Make sure we can open the file
2254 try:
2288 try:
2255 with open(fname) as thefile:
2289 with open(fname) as thefile:
2256 pass
2290 pass
2257 except:
2291 except:
2258 warn('Could not open file <%s> for safe execution.' % fname)
2292 warn('Could not open file <%s> for safe execution.' % fname)
2259 return
2293 return
2260
2294
2261 # Find things also in current directory. This is needed to mimic the
2295 # Find things also in current directory. This is needed to mimic the
2262 # behavior of running a script from the system command line, where
2296 # behavior of running a script from the system command line, where
2263 # Python inserts the script's directory into sys.path
2297 # Python inserts the script's directory into sys.path
2264 dname = os.path.dirname(fname)
2298 dname = os.path.dirname(fname)
2265
2299
2266 with prepended_to_syspath(dname):
2300 with prepended_to_syspath(dname):
2267 try:
2301 try:
2268 py3compat.execfile(fname,*where)
2302 py3compat.execfile(fname,*where)
2269 except SystemExit, status:
2303 except SystemExit, status:
2270 # If the call was made with 0 or None exit status (sys.exit(0)
2304 # 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
2305 # or sys.exit() ), don't bother showing a traceback, as both of
2272 # these are considered normal by the OS:
2306 # these are considered normal by the OS:
2273 # > python -c'import sys;sys.exit(0)'; echo $?
2307 # > python -c'import sys;sys.exit(0)'; echo $?
2274 # 0
2308 # 0
2275 # > python -c'import sys;sys.exit()'; echo $?
2309 # > python -c'import sys;sys.exit()'; echo $?
2276 # 0
2310 # 0
2277 # For other exit status, we show the exception unless
2311 # For other exit status, we show the exception unless
2278 # explicitly silenced, but only in short form.
2312 # explicitly silenced, but only in short form.
2279 if kw['raise_exceptions']:
2313 if kw['raise_exceptions']:
2280 raise
2314 raise
2281 if status.code not in (0, None) and not kw['exit_ignore']:
2315 if status.code not in (0, None) and not kw['exit_ignore']:
2282 self.showtraceback(exception_only=True)
2316 self.showtraceback(exception_only=True)
2283 except:
2317 except:
2284 if kw['raise_exceptions']:
2318 if kw['raise_exceptions']:
2285 raise
2319 raise
2286 self.showtraceback()
2320 self.showtraceback()
2287
2321
2288 def safe_execfile_ipy(self, fname):
2322 def safe_execfile_ipy(self, fname):
2289 """Like safe_execfile, but for .ipy files with IPython syntax.
2323 """Like safe_execfile, but for .ipy files with IPython syntax.
2290
2324
2291 Parameters
2325 Parameters
2292 ----------
2326 ----------
2293 fname : str
2327 fname : str
2294 The name of the file to execute. The filename must have a
2328 The name of the file to execute. The filename must have a
2295 .ipy extension.
2329 .ipy extension.
2296 """
2330 """
2297 fname = os.path.abspath(os.path.expanduser(fname))
2331 fname = os.path.abspath(os.path.expanduser(fname))
2298
2332
2299 # Make sure we can open the file
2333 # Make sure we can open the file
2300 try:
2334 try:
2301 with open(fname) as thefile:
2335 with open(fname) as thefile:
2302 pass
2336 pass
2303 except:
2337 except:
2304 warn('Could not open file <%s> for safe execution.' % fname)
2338 warn('Could not open file <%s> for safe execution.' % fname)
2305 return
2339 return
2306
2340
2307 # Find things also in current directory. This is needed to mimic the
2341 # Find things also in current directory. This is needed to mimic the
2308 # behavior of running a script from the system command line, where
2342 # behavior of running a script from the system command line, where
2309 # Python inserts the script's directory into sys.path
2343 # Python inserts the script's directory into sys.path
2310 dname = os.path.dirname(fname)
2344 dname = os.path.dirname(fname)
2311
2345
2312 with prepended_to_syspath(dname):
2346 with prepended_to_syspath(dname):
2313 try:
2347 try:
2314 with open(fname) as thefile:
2348 with open(fname) as thefile:
2315 # self.run_cell currently captures all exceptions
2349 # self.run_cell currently captures all exceptions
2316 # raised in user code. It would be nice if there were
2350 # raised in user code. It would be nice if there were
2317 # versions of runlines, execfile that did raise, so
2351 # versions of runlines, execfile that did raise, so
2318 # we could catch the errors.
2352 # we could catch the errors.
2319 self.run_cell(thefile.read(), store_history=False)
2353 self.run_cell(thefile.read(), store_history=False)
2320 except:
2354 except:
2321 self.showtraceback()
2355 self.showtraceback()
2322 warn('Unknown failure executing file: <%s>' % fname)
2356 warn('Unknown failure executing file: <%s>' % fname)
2323
2357
2324 def run_cell(self, raw_cell, store_history=False):
2358 def run_cell(self, raw_cell, store_history=False):
2325 """Run a complete IPython cell.
2359 """Run a complete IPython cell.
2326
2360
2327 Parameters
2361 Parameters
2328 ----------
2362 ----------
2329 raw_cell : str
2363 raw_cell : str
2330 The code (including IPython code such as %magic functions) to run.
2364 The code (including IPython code such as %magic functions) to run.
2331 store_history : bool
2365 store_history : bool
2332 If True, the raw and translated cell will be stored in IPython's
2366 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
2367 history. For user code calling back into IPython's machinery, this
2334 should be set to False.
2368 should be set to False.
2335 """
2369 """
2336 if (not raw_cell) or raw_cell.isspace():
2370 if (not raw_cell) or raw_cell.isspace():
2337 return
2371 return
2338
2372
2339 for line in raw_cell.splitlines():
2373 for line in raw_cell.splitlines():
2340 self.input_splitter.push(line)
2374 self.input_splitter.push(line)
2341 cell = self.input_splitter.source_reset()
2375 cell = self.input_splitter.source_reset()
2342
2376
2343 with self.builtin_trap:
2377 with self.builtin_trap:
2344 prefilter_failed = False
2378 prefilter_failed = False
2345 if len(cell.splitlines()) == 1:
2379 if len(cell.splitlines()) == 1:
2346 try:
2380 try:
2347 # use prefilter_lines to handle trailing newlines
2381 # use prefilter_lines to handle trailing newlines
2348 # restore trailing newline for ast.parse
2382 # restore trailing newline for ast.parse
2349 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2383 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2350 except AliasError as e:
2384 except AliasError as e:
2351 error(e)
2385 error(e)
2352 prefilter_failed = True
2386 prefilter_failed = True
2353 except Exception:
2387 except Exception:
2354 # don't allow prefilter errors to crash IPython
2388 # don't allow prefilter errors to crash IPython
2355 self.showtraceback()
2389 self.showtraceback()
2356 prefilter_failed = True
2390 prefilter_failed = True
2357
2391
2358 # Store raw and processed history
2392 # Store raw and processed history
2359 if store_history:
2393 if store_history:
2360 self.history_manager.store_inputs(self.execution_count,
2394 self.history_manager.store_inputs(self.execution_count,
2361 cell, raw_cell)
2395 cell, raw_cell)
2362
2396
2363 self.logger.log(cell, raw_cell)
2397 self.logger.log(cell, raw_cell)
2364
2398
2365 if not prefilter_failed:
2399 if not prefilter_failed:
2366 # don't run if prefilter failed
2400 # don't run if prefilter failed
2367 cell_name = self.compile.cache(cell, self.execution_count)
2401 cell_name = self.compile.cache(cell, self.execution_count)
2368
2402
2369 with self.display_trap:
2403 with self.display_trap:
2370 try:
2404 try:
2371 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2405 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2372 except IndentationError:
2406 except IndentationError:
2373 self.showindentationerror()
2407 self.showindentationerror()
2374 self.execution_count += 1
2408 self.execution_count += 1
2375 return None
2409 return None
2376 except (OverflowError, SyntaxError, ValueError, TypeError,
2410 except (OverflowError, SyntaxError, ValueError, TypeError,
2377 MemoryError):
2411 MemoryError):
2378 self.showsyntaxerror()
2412 self.showsyntaxerror()
2379 self.execution_count += 1
2413 self.execution_count += 1
2380 return None
2414 return None
2381
2415
2382 self.run_ast_nodes(code_ast.body, cell_name,
2416 self.run_ast_nodes(code_ast.body, cell_name,
2383 interactivity="last_expr")
2417 interactivity="last_expr")
2384
2418
2385 # Execute any registered post-execution functions.
2419 # Execute any registered post-execution functions.
2386 for func, status in self._post_execute.iteritems():
2420 for func, status in self._post_execute.iteritems():
2387 if not status:
2421 if not status:
2388 continue
2422 continue
2389 try:
2423 try:
2390 func()
2424 func()
2391 except KeyboardInterrupt:
2425 except KeyboardInterrupt:
2392 print >> io.stderr, "\nKeyboardInterrupt"
2426 print >> io.stderr, "\nKeyboardInterrupt"
2393 except Exception:
2427 except Exception:
2394 print >> io.stderr, "Disabling failed post-execution function: %s" % func
2428 print >> io.stderr, "Disabling failed post-execution function: %s" % func
2395 self.showtraceback()
2429 self.showtraceback()
2396 # Deactivate failing function
2430 # Deactivate failing function
2397 self._post_execute[func] = False
2431 self._post_execute[func] = False
2398
2432
2399 if store_history:
2433 if store_history:
2400 # Write output to the database. Does nothing unless
2434 # Write output to the database. Does nothing unless
2401 # history output logging is enabled.
2435 # history output logging is enabled.
2402 self.history_manager.store_output(self.execution_count)
2436 self.history_manager.store_output(self.execution_count)
2403 # Each cell is a *single* input, regardless of how many lines it has
2437 # Each cell is a *single* input, regardless of how many lines it has
2404 self.execution_count += 1
2438 self.execution_count += 1
2405
2439
2406 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2440 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2407 """Run a sequence of AST nodes. The execution mode depends on the
2441 """Run a sequence of AST nodes. The execution mode depends on the
2408 interactivity parameter.
2442 interactivity parameter.
2409
2443
2410 Parameters
2444 Parameters
2411 ----------
2445 ----------
2412 nodelist : list
2446 nodelist : list
2413 A sequence of AST nodes to run.
2447 A sequence of AST nodes to run.
2414 cell_name : str
2448 cell_name : str
2415 Will be passed to the compiler as the filename of the cell. Typically
2449 Will be passed to the compiler as the filename of the cell. Typically
2416 the value returned by ip.compile.cache(cell).
2450 the value returned by ip.compile.cache(cell).
2417 interactivity : str
2451 interactivity : str
2418 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2452 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2419 run interactively (displaying output from expressions). 'last_expr'
2453 run interactively (displaying output from expressions). 'last_expr'
2420 will run the last node interactively only if it is an expression (i.e.
2454 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
2455 expressions in loops or other blocks are not displayed. Other values
2422 for this parameter will raise a ValueError.
2456 for this parameter will raise a ValueError.
2423 """
2457 """
2424 if not nodelist:
2458 if not nodelist:
2425 return
2459 return
2426
2460
2427 if interactivity == 'last_expr':
2461 if interactivity == 'last_expr':
2428 if isinstance(nodelist[-1], ast.Expr):
2462 if isinstance(nodelist[-1], ast.Expr):
2429 interactivity = "last"
2463 interactivity = "last"
2430 else:
2464 else:
2431 interactivity = "none"
2465 interactivity = "none"
2432
2466
2433 if interactivity == 'none':
2467 if interactivity == 'none':
2434 to_run_exec, to_run_interactive = nodelist, []
2468 to_run_exec, to_run_interactive = nodelist, []
2435 elif interactivity == 'last':
2469 elif interactivity == 'last':
2436 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2470 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2437 elif interactivity == 'all':
2471 elif interactivity == 'all':
2438 to_run_exec, to_run_interactive = [], nodelist
2472 to_run_exec, to_run_interactive = [], nodelist
2439 else:
2473 else:
2440 raise ValueError("Interactivity was %r" % interactivity)
2474 raise ValueError("Interactivity was %r" % interactivity)
2441
2475
2442 exec_count = self.execution_count
2476 exec_count = self.execution_count
2443
2477
2444 try:
2478 try:
2445 for i, node in enumerate(to_run_exec):
2479 for i, node in enumerate(to_run_exec):
2446 mod = ast.Module([node])
2480 mod = ast.Module([node])
2447 code = self.compile(mod, cell_name, "exec")
2481 code = self.compile(mod, cell_name, "exec")
2448 if self.run_code(code):
2482 if self.run_code(code):
2449 return True
2483 return True
2450
2484
2451 for i, node in enumerate(to_run_interactive):
2485 for i, node in enumerate(to_run_interactive):
2452 mod = ast.Interactive([node])
2486 mod = ast.Interactive([node])
2453 code = self.compile(mod, cell_name, "single")
2487 code = self.compile(mod, cell_name, "single")
2454 if self.run_code(code):
2488 if self.run_code(code):
2455 return True
2489 return True
2456 except:
2490 except:
2457 # It's possible to have exceptions raised here, typically by
2491 # It's possible to have exceptions raised here, typically by
2458 # compilation of odd code (such as a naked 'return' outside a
2492 # compilation of odd code (such as a naked 'return' outside a
2459 # function) that did parse but isn't valid. Typically the exception
2493 # 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
2494 # is a SyntaxError, but it's safest just to catch anything and show
2461 # the user a traceback.
2495 # the user a traceback.
2462
2496
2463 # We do only one try/except outside the loop to minimize the impact
2497 # 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
2498 # on runtime, and also because if any node in the node list is
2465 # broken, we should stop execution completely.
2499 # broken, we should stop execution completely.
2466 self.showtraceback()
2500 self.showtraceback()
2467
2501
2468 return False
2502 return False
2469
2503
2470 def run_code(self, code_obj):
2504 def run_code(self, code_obj):
2471 """Execute a code object.
2505 """Execute a code object.
2472
2506
2473 When an exception occurs, self.showtraceback() is called to display a
2507 When an exception occurs, self.showtraceback() is called to display a
2474 traceback.
2508 traceback.
2475
2509
2476 Parameters
2510 Parameters
2477 ----------
2511 ----------
2478 code_obj : code object
2512 code_obj : code object
2479 A compiled code object, to be executed
2513 A compiled code object, to be executed
2480 post_execute : bool [default: True]
2514 post_execute : bool [default: True]
2481 whether to call post_execute hooks after this particular execution.
2515 whether to call post_execute hooks after this particular execution.
2482
2516
2483 Returns
2517 Returns
2484 -------
2518 -------
2485 False : successful execution.
2519 False : successful execution.
2486 True : an error occurred.
2520 True : an error occurred.
2487 """
2521 """
2488
2522
2489 # Set our own excepthook in case the user code tries to call it
2523 # 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
2524 # directly, so that the IPython crash handler doesn't get triggered
2491 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2525 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2492
2526
2493 # we save the original sys.excepthook in the instance, in case config
2527 # we save the original sys.excepthook in the instance, in case config
2494 # code (such as magics) needs access to it.
2528 # code (such as magics) needs access to it.
2495 self.sys_excepthook = old_excepthook
2529 self.sys_excepthook = old_excepthook
2496 outflag = 1 # happens in more places, so it's easier as default
2530 outflag = 1 # happens in more places, so it's easier as default
2497 try:
2531 try:
2498 try:
2532 try:
2499 self.hooks.pre_run_code_hook()
2533 self.hooks.pre_run_code_hook()
2500 #rprint('Running code', repr(code_obj)) # dbg
2534 #rprint('Running code', repr(code_obj)) # dbg
2501 exec code_obj in self.user_global_ns, self.user_ns
2535 exec code_obj in self.user_global_ns, self.user_ns
2502 finally:
2536 finally:
2503 # Reset our crash handler in place
2537 # Reset our crash handler in place
2504 sys.excepthook = old_excepthook
2538 sys.excepthook = old_excepthook
2505 except SystemExit:
2539 except SystemExit:
2506 self.showtraceback(exception_only=True)
2540 self.showtraceback(exception_only=True)
2507 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2541 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2508 except self.custom_exceptions:
2542 except self.custom_exceptions:
2509 etype,value,tb = sys.exc_info()
2543 etype,value,tb = sys.exc_info()
2510 self.CustomTB(etype,value,tb)
2544 self.CustomTB(etype,value,tb)
2511 except:
2545 except:
2512 self.showtraceback()
2546 self.showtraceback()
2513 else:
2547 else:
2514 outflag = 0
2548 outflag = 0
2515 if softspace(sys.stdout, 0):
2549 if softspace(sys.stdout, 0):
2516 print
2550 print
2517
2551
2518 return outflag
2552 return outflag
2519
2553
2520 # For backwards compatibility
2554 # For backwards compatibility
2521 runcode = run_code
2555 runcode = run_code
2522
2556
2523 #-------------------------------------------------------------------------
2557 #-------------------------------------------------------------------------
2524 # Things related to GUI support and pylab
2558 # Things related to GUI support and pylab
2525 #-------------------------------------------------------------------------
2559 #-------------------------------------------------------------------------
2526
2560
2527 def enable_gui(self, gui=None):
2561 def enable_gui(self, gui=None):
2528 raise NotImplementedError('Implement enable_gui in a subclass')
2562 raise NotImplementedError('Implement enable_gui in a subclass')
2529
2563
2530 def enable_pylab(self, gui=None, import_all=True):
2564 def enable_pylab(self, gui=None, import_all=True):
2531 """Activate pylab support at runtime.
2565 """Activate pylab support at runtime.
2532
2566
2533 This turns on support for matplotlib, preloads into the interactive
2567 This turns on support for matplotlib, preloads into the interactive
2534 namespace all of numpy and pylab, and configures IPython to correctly
2568 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
2569 interact with the GUI event loop. The GUI backend to be used can be
2536 optionally selected with the optional :param:`gui` argument.
2570 optionally selected with the optional :param:`gui` argument.
2537
2571
2538 Parameters
2572 Parameters
2539 ----------
2573 ----------
2540 gui : optional, string
2574 gui : optional, string
2541
2575
2542 If given, dictates the choice of matplotlib GUI backend to use
2576 If given, dictates the choice of matplotlib GUI backend to use
2543 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2577 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2544 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2578 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2545 matplotlib (as dictated by the matplotlib build-time options plus the
2579 matplotlib (as dictated by the matplotlib build-time options plus the
2546 user's matplotlibrc configuration file). Note that not all backends
2580 user's matplotlibrc configuration file). Note that not all backends
2547 make sense in all contexts, for example a terminal ipython can't
2581 make sense in all contexts, for example a terminal ipython can't
2548 display figures inline.
2582 display figures inline.
2549 """
2583 """
2550
2584
2551 # We want to prevent the loading of pylab to pollute the user's
2585 # 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
2586 # 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
2587 # code in an empty namespace, and we update *both* user_ns and
2554 # user_ns_hidden with this information.
2588 # user_ns_hidden with this information.
2555 ns = {}
2589 ns = {}
2556 try:
2590 try:
2557 gui = pylab_activate(ns, gui, import_all, self)
2591 gui = pylab_activate(ns, gui, import_all, self)
2558 except KeyError:
2592 except KeyError:
2559 error("Backend %r not supported" % gui)
2593 error("Backend %r not supported" % gui)
2560 return
2594 return
2561 self.user_ns.update(ns)
2595 self.user_ns.update(ns)
2562 self.user_ns_hidden.update(ns)
2596 self.user_ns_hidden.update(ns)
2563 # Now we must activate the gui pylab wants to use, and fix %run to take
2597 # Now we must activate the gui pylab wants to use, and fix %run to take
2564 # plot updates into account
2598 # plot updates into account
2565 self.enable_gui(gui)
2599 self.enable_gui(gui)
2566 self.magic_run = self._pylab_magic_run
2600 self.magic_run = self._pylab_magic_run
2567
2601
2568 #-------------------------------------------------------------------------
2602 #-------------------------------------------------------------------------
2569 # Utilities
2603 # Utilities
2570 #-------------------------------------------------------------------------
2604 #-------------------------------------------------------------------------
2571
2605
2572 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2606 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2573 """Expand python variables in a string.
2607 """Expand python variables in a string.
2574
2608
2575 The depth argument indicates how many frames above the caller should
2609 The depth argument indicates how many frames above the caller should
2576 be walked to look for the local namespace where to expand variables.
2610 be walked to look for the local namespace where to expand variables.
2577
2611
2578 The global namespace for expansion is always the user's interactive
2612 The global namespace for expansion is always the user's interactive
2579 namespace.
2613 namespace.
2580 """
2614 """
2581 ns = self.user_ns.copy()
2615 ns = self.user_ns.copy()
2582 ns.update(sys._getframe(depth+1).f_locals)
2616 ns.update(sys._getframe(depth+1).f_locals)
2583 ns.pop('self', None)
2617 ns.pop('self', None)
2584 return formatter.format(cmd, **ns)
2618 return formatter.format(cmd, **ns)
2585
2619
2586 def mktempfile(self, data=None, prefix='ipython_edit_'):
2620 def mktempfile(self, data=None, prefix='ipython_edit_'):
2587 """Make a new tempfile and return its filename.
2621 """Make a new tempfile and return its filename.
2588
2622
2589 This makes a call to tempfile.mktemp, but it registers the created
2623 This makes a call to tempfile.mktemp, but it registers the created
2590 filename internally so ipython cleans it up at exit time.
2624 filename internally so ipython cleans it up at exit time.
2591
2625
2592 Optional inputs:
2626 Optional inputs:
2593
2627
2594 - data(None): if data is given, it gets written out to the temp file
2628 - data(None): if data is given, it gets written out to the temp file
2595 immediately, and the file is closed again."""
2629 immediately, and the file is closed again."""
2596
2630
2597 filename = tempfile.mktemp('.py', prefix)
2631 filename = tempfile.mktemp('.py', prefix)
2598 self.tempfiles.append(filename)
2632 self.tempfiles.append(filename)
2599
2633
2600 if data:
2634 if data:
2601 tmp_file = open(filename,'w')
2635 tmp_file = open(filename,'w')
2602 tmp_file.write(data)
2636 tmp_file.write(data)
2603 tmp_file.close()
2637 tmp_file.close()
2604 return filename
2638 return filename
2605
2639
2606 # TODO: This should be removed when Term is refactored.
2640 # TODO: This should be removed when Term is refactored.
2607 def write(self,data):
2641 def write(self,data):
2608 """Write a string to the default output"""
2642 """Write a string to the default output"""
2609 io.stdout.write(data)
2643 io.stdout.write(data)
2610
2644
2611 # TODO: This should be removed when Term is refactored.
2645 # TODO: This should be removed when Term is refactored.
2612 def write_err(self,data):
2646 def write_err(self,data):
2613 """Write a string to the default error output"""
2647 """Write a string to the default error output"""
2614 io.stderr.write(data)
2648 io.stderr.write(data)
2615
2649
2616 def ask_yes_no(self, prompt, default=None):
2650 def ask_yes_no(self, prompt, default=None):
2617 if self.quiet:
2651 if self.quiet:
2618 return True
2652 return True
2619 return ask_yes_no(prompt,default)
2653 return ask_yes_no(prompt,default)
2620
2654
2621 def show_usage(self):
2655 def show_usage(self):
2622 """Show a usage message"""
2656 """Show a usage message"""
2623 page.page(IPython.core.usage.interactive_usage)
2657 page.page(IPython.core.usage.interactive_usage)
2624
2658
2625 def find_user_code(self, target, raw=True):
2659 def find_user_code(self, target, raw=True):
2626 """Get a code string from history, file, or a string or macro.
2660 """Get a code string from history, file, or a string or macro.
2627
2661
2628 This is mainly used by magic functions.
2662 This is mainly used by magic functions.
2629
2663
2630 Parameters
2664 Parameters
2631 ----------
2665 ----------
2632 target : str
2666 target : str
2633 A string specifying code to retrieve. This will be tried respectively
2667 A string specifying code to retrieve. This will be tried respectively
2634 as: ranges of input history (see %history for syntax), a filename, or
2668 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.
2669 an expression evaluating to a string or Macro in the user namespace.
2636 raw : bool
2670 raw : bool
2637 If true (default), retrieve raw history. Has no effect on the other
2671 If true (default), retrieve raw history. Has no effect on the other
2638 retrieval mechanisms.
2672 retrieval mechanisms.
2639
2673
2640 Returns
2674 Returns
2641 -------
2675 -------
2642 A string of code.
2676 A string of code.
2643
2677
2644 ValueError is raised if nothing is found, and TypeError if it evaluates
2678 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
2679 to an object of another type. In each case, .args[0] is a printable
2646 message.
2680 message.
2647 """
2681 """
2648 code = self.extract_input_lines(target, raw=raw) # Grab history
2682 code = self.extract_input_lines(target, raw=raw) # Grab history
2649 if code:
2683 if code:
2650 return code
2684 return code
2651 if os.path.isfile(target): # Read file
2685 if os.path.isfile(target): # Read file
2652 return open(target, "r").read()
2686 return open(target, "r").read()
2653
2687
2654 try: # User namespace
2688 try: # User namespace
2655 codeobj = eval(target, self.user_ns)
2689 codeobj = eval(target, self.user_ns)
2656 except Exception:
2690 except Exception:
2657 raise ValueError(("'%s' was not found in history, as a file, nor in"
2691 raise ValueError(("'%s' was not found in history, as a file, nor in"
2658 " the user namespace.") % target)
2692 " the user namespace.") % target)
2659 if isinstance(codeobj, basestring):
2693 if isinstance(codeobj, basestring):
2660 return codeobj
2694 return codeobj
2661 elif isinstance(codeobj, Macro):
2695 elif isinstance(codeobj, Macro):
2662 return codeobj.value
2696 return codeobj.value
2663
2697
2664 raise TypeError("%s is neither a string nor a macro." % target,
2698 raise TypeError("%s is neither a string nor a macro." % target,
2665 codeobj)
2699 codeobj)
2666
2700
2667 #-------------------------------------------------------------------------
2701 #-------------------------------------------------------------------------
2668 # Things related to IPython exiting
2702 # Things related to IPython exiting
2669 #-------------------------------------------------------------------------
2703 #-------------------------------------------------------------------------
2670 def atexit_operations(self):
2704 def atexit_operations(self):
2671 """This will be executed at the time of exit.
2705 """This will be executed at the time of exit.
2672
2706
2673 Cleanup operations and saving of persistent data that is done
2707 Cleanup operations and saving of persistent data that is done
2674 unconditionally by IPython should be performed here.
2708 unconditionally by IPython should be performed here.
2675
2709
2676 For things that may depend on startup flags or platform specifics (such
2710 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
2711 as having readline or not), register a separate atexit function in the
2678 code that has the appropriate information, rather than trying to
2712 code that has the appropriate information, rather than trying to
2679 clutter
2713 clutter
2680 """
2714 """
2681 # Close the history session (this stores the end time and line count)
2715 # Close the history session (this stores the end time and line count)
2682 # this must be *before* the tempfile cleanup, in case of temporary
2716 # this must be *before* the tempfile cleanup, in case of temporary
2683 # history db
2717 # history db
2684 self.history_manager.end_session()
2718 self.history_manager.end_session()
2685
2719
2686 # Cleanup all tempfiles left around
2720 # Cleanup all tempfiles left around
2687 for tfile in self.tempfiles:
2721 for tfile in self.tempfiles:
2688 try:
2722 try:
2689 os.unlink(tfile)
2723 os.unlink(tfile)
2690 except OSError:
2724 except OSError:
2691 pass
2725 pass
2692
2726
2693 # Clear all user namespaces to release all references cleanly.
2727 # Clear all user namespaces to release all references cleanly.
2694 self.reset(new_session=False)
2728 self.reset(new_session=False)
2695
2729
2696 # Run user hooks
2730 # Run user hooks
2697 self.hooks.shutdown_hook()
2731 self.hooks.shutdown_hook()
2698
2732
2699 def cleanup(self):
2733 def cleanup(self):
2700 self.restore_sys_module_state()
2734 self.restore_sys_module_state()
2701
2735
2702
2736
2703 class InteractiveShellABC(object):
2737 class InteractiveShellABC(object):
2704 """An abstract base class for InteractiveShell."""
2738 """An abstract base class for InteractiveShell."""
2705 __metaclass__ = abc.ABCMeta
2739 __metaclass__ = abc.ABCMeta
2706
2740
2707 InteractiveShellABC.register(InteractiveShell)
2741 InteractiveShellABC.register(InteractiveShell)
@@ -1,378 +1,396 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")
261
263
262 justify = Bool(True, config=True, help="""
264 justify = Bool(True, config=True, help="""
263 If True (default), each prompt will be right-aligned with the
265 If True (default), each prompt will be right-aligned with the
264 preceding one.
266 preceding one.
265 """)
267 """)
266
268
267 # We actually store the expanded templates here:
269 # We actually store the expanded templates here:
268 templates = Dict()
270 templates = Dict()
269
271
270 # The number of characters in the last prompt rendered, not including
272 # The number of characters in the last prompt rendered, not including
271 # colour characters.
273 # colour characters.
272 width = Int()
274 width = Int()
275 txtwidth = Int() # Not including right-justification
273
276
274 # The number of characters in each prompt which don't contribute to width
277 # The number of characters in each prompt which don't contribute to width
275 invisible_chars = Dict()
278 invisible_chars = Dict()
276 def _invisible_chars_default(self):
279 def _invisible_chars_default(self):
277 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite': 0}
280 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite':0}
278
281
279 def __init__(self, shell, config=None):
282 def __init__(self, shell, config=None):
280 super(PromptManager, self).__init__(shell=shell, config=config)
283 super(PromptManager, self).__init__(shell=shell, config=config)
281
284
282 # Prepare colour scheme table
285 # Prepare colour scheme table
283 self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors,
286 self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors,
284 PColLinux, PColLightBG], self.color_scheme)
287 PColLinux, PColLightBG], self.color_scheme)
285
288
286 # Prepare templates
289 # Prepare templates & numbers of invisible characters
287 self.update_prompt('in', self.in_template)
290 self.update_prompt('in', self.in_template)
288 self.update_prompt('in2', self.in2_template)
291 self.update_prompt('in2', self.in2_template)
289 self.update_prompt('out', self.out_template)
292 self.update_prompt('out', self.out_template)
290 self.update_prompt('rewrite', self.rewrite_template)
293 self.update_prompt('rewrite')
291 self.on_trait_change(self._update_prompt_trait, ['in_template',
294 self.on_trait_change(self._update_prompt_trait, ['in_template',
292 'in2_template', 'out_template', 'rewrite_template'])
295 'in2_template', 'out_template'])
293
296
294 def update_prompt(self, name, new_template=None):
297 def update_prompt(self, name, new_template=None):
295 """This is called when a prompt template is updated. It processes
298 """This is called when a prompt template is updated. It processes
296 abbreviations used in the prompt template (like \#) and calculates how
299 abbreviations used in the prompt template (like \#) and calculates how
297 many invisible characters (ANSI colour escapes) the resulting prompt
300 many invisible characters (ANSI colour escapes) the resulting prompt
298 contains.
301 contains.
299
302
300 It is also called for each prompt on changing the colour scheme. In both
303 It is also called for each prompt on changing the colour scheme. In both
301 cases, traitlets should take care of calling this automatically.
304 cases, traitlets should take care of calling this automatically.
302 """
305 """
303 if new_template is not None:
306 if new_template is not None:
304 self.templates[name] = multiple_replace(prompt_abbreviations, new_template)
307 self.templates[name] = multiple_replace(prompt_abbreviations, new_template)
305 invis_chars = len(self.render(name, color=True, just=False)) - \
308 invis_chars = len(self._render(name, color=True)) - \
306 len(self.render(name, color=False, just=False))
309 len(self._render(name, color=False))
307 self.invisible_chars[name] = invis_chars
310 self.invisible_chars[name] = invis_chars
308
311
309 def _update_prompt_trait(self, traitname, new_template):
312 def _update_prompt_trait(self, traitname, new_template):
310 name = traitname[:-9] # Cut off '_template'
313 name = traitname[:-9] # Cut off '_template'
311 self.update_prompt(name, new_template)
314 self.update_prompt(name, new_template)
312
315
313 def render(self, name, color=True, just=None, **kwargs):
316 def _render(self, name, color=True, **kwargs):
317 """Render but don't justify, or update the width or txtwidth attributes.
314 """
318 """
315 Render the selected prompt.
319 if name == 'rewrite':
320 return self._render_rewrite(color=color)
316
321
317 Parameters
318 ----------
319 name : str
320 Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
321 color : bool
322 If True (default), include ANSI escape sequences for a coloured prompt.
323 just : bool
324 If True, justify the prompt to the width of the last prompt. The
325 default is stored in self.justify.
326 **kwargs :
327 Additional arguments will be passed to the string formatting operation,
328 so they can override the values that would otherwise fill in the
329 template.
330
331 Returns
332 -------
333 A string containing the rendered prompt.
334 """
335 if color:
322 if color:
336 scheme = self.color_scheme_table.active_colors
323 scheme = self.color_scheme_table.active_colors
337 if name=='out':
324 if name=='out':
338 colors = color_lists['normal']
325 colors = color_lists['normal']
339 colors.number, colors.prompt, colors.normal = \
326 colors.number, colors.prompt, colors.normal = \
340 scheme.out_number, scheme.out_prompt, scheme.normal
327 scheme.out_number, scheme.out_prompt, scheme.normal
341 elif name=='rewrite':
342 colors = color_lists['normal']
343 # We need a non-input version of these escapes
344 colors.number = scheme.in_number.replace("\001","").replace("\002","")
345 colors.prompt = scheme.in_prompt.replace("\001","").replace("\002","")
346 colors.normal = scheme.normal
347 else:
328 else:
348 colors = color_lists['inp']
329 colors = color_lists['inp']
349 colors.number, colors.prompt, colors.normal = \
330 colors.number, colors.prompt, colors.normal = \
350 scheme.in_number, scheme.in_prompt, scheme.in_normal
331 scheme.in_number, scheme.in_prompt, scheme.in_normal
351 if name=='in2':
332 if name=='in2':
352 colors.prompt = scheme.in_prompt2
333 colors.prompt = scheme.in_prompt2
353 else:
334 else:
354 # No color
335 # No color
355 colors = color_lists['nocolor']
336 colors = color_lists['nocolor']
356 colors.number, colors.prompt, colors.normal = '', '', ''
337 colors.number, colors.prompt, colors.normal = '', '', ''
357
338
358 count = self.shell.execution_count # Shorthand
339 count = self.shell.execution_count # Shorthand
359 # Build the dictionary to be passed to string formatting
340 # Build the dictionary to be passed to string formatting
360 fmtargs = dict(color=colors, count=count,
341 fmtargs = dict(color=colors, count=count,
361 dots="."*len(str(count)) )
342 dots="."*len(str(count)),
343 width=self.width, txtwidth=self.txtwidth )
362 fmtargs.update(self.lazy_evaluate_fields)
344 fmtargs.update(self.lazy_evaluate_fields)
363 fmtargs.update(kwargs)
345 fmtargs.update(kwargs)
364
346
365 # Prepare the prompt
347 # Prepare the prompt
366 prompt = colors.prompt + self.templates[name] + colors.normal
348 prompt = colors.prompt + self.templates[name] + colors.normal
367
349
368 # Fill in required fields
350 # Fill in required fields
369 res = prompt.format(**fmtargs)
351 return prompt.format(**fmtargs)
352
353 def _render_rewrite(self, color=True):
354 """Render the ---> rewrite prompt."""
355 if color:
356 scheme = self.color_scheme_table.active_colors
357 # We need a non-input version of these escapes
358 color_prompt = scheme.in_prompt.replace("\001","").replace("\002","")
359 color_normal = scheme.normal
360 else:
361 color_prompt, color_normal = '', ''
362
363 return color_prompt + "-> ".rjust(self.txtwidth, "-") + color_normal
364
365 def render(self, name, color=True, just=None, **kwargs):
366 """
367 Render the selected prompt.
368
369 Parameters
370 ----------
371 name : str
372 Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
373 color : bool
374 If True (default), include ANSI escape sequences for a coloured prompt.
375 just : bool
376 If True, justify the prompt to the width of the last prompt. The
377 default is stored in self.justify.
378 **kwargs :
379 Additional arguments will be passed to the string formatting operation,
380 so they can override the values that would otherwise fill in the
381 template.
382
383 Returns
384 -------
385 A string containing the rendered prompt.
386 """
387 res = self._render(name, color=color, **kwargs)
370
388
371 # Handle justification of prompt
389 # Handle justification of prompt
372 invis_chars = self.invisible_chars[name] if color else 0
390 invis_chars = self.invisible_chars[name] if color else 0
391 self.txtwidth = len(res) - invis_chars
373 just = self.justify if (just is None) else just
392 just = self.justify if (just is None) else just
374 if just:
393 if just:
375 res = res.rjust(self.width + invis_chars)
394 res = res.rjust(self.width + invis_chars)
376 self.width = len(res) - invis_chars
395 self.width = len(res) - invis_chars
377 return res
396 return res
378
@@ -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,294 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 c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
159 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>'
159 c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
160 c.PromptManager.out_template = r'<\#> '
160
161
161 You can change the prompt configuration to your liking by editing
162 You can change the prompt configuration to your liking by editing
162 ipython_config.py.
163 ipython_config.py.
163
164
164 .. _string_lists:
165 .. _string_lists:
165
166
166 String lists
167 String lists
167 ============
168 ============
168
169
169 String lists (IPython.utils.text.SList) are handy way to process output
170 String lists (IPython.utils.text.SList) are handy way to process output
170 from system commands. They are produced by ``var = !cmd`` syntax.
171 from system commands. They are produced by ``var = !cmd`` syntax.
171
172
172 First, we acquire the output of 'ls -l'::
173 First, we acquire the output of 'ls -l'::
173
174
174 [Q:doc/examples]|2> lines = !ls -l
175 [Q:doc/examples]|2> lines = !ls -l
175 ==
176 ==
176 ['total 23',
177 ['total 23',
177 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
178 '-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',
179 '-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',
180 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
180 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
181 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
181 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
182 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
182 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
183 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
183 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
184 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
184
185
185 Now, let's take a look at the contents of 'lines' (the first number is
186 Now, let's take a look at the contents of 'lines' (the first number is
186 the list element number)::
187 the list element number)::
187
188
188 [Q:doc/examples]|3> lines
189 [Q:doc/examples]|3> lines
189 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
190 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
190
191
191 0: total 23
192 0: total 23
192 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
193 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
194 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
195 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
196 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
197 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
197 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
198 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
198 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
199 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
199
200
200 Now, let's filter out the 'embed' lines::
201 Now, let's filter out the 'embed' lines::
201
202
202 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
203 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
203 [Q:doc/examples]|5> l2
204 [Q:doc/examples]|5> l2
204 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
205 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
205
206
206 0: total 23
207 0: total 23
207 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
208 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
209 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
210 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
210 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
211 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
211 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
212 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
212
213
213 Now, we want strings having just file names and permissions::
214 Now, we want strings having just file names and permissions::
214
215
215 [Q:doc/examples]|6> l2.fields(8,0)
216 [Q:doc/examples]|6> l2.fields(8,0)
216 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
217 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
217
218
218 0: total
219 0: total
219 1: example-demo.py -rw-rw-rw-
220 1: example-demo.py -rw-rw-rw-
220 2: example-gnuplot.py -rwxrwxrwx
221 2: example-gnuplot.py -rwxrwxrwx
221 3: extension.py -rwxrwxrwx
222 3: extension.py -rwxrwxrwx
222 4: seteditor.py -rwxrwxrwx
223 4: seteditor.py -rwxrwxrwx
223 5: seteditor.pyc -rwxrwxrwx
224 5: seteditor.pyc -rwxrwxrwx
224
225
225 Note how the line with 'total' does not raise IndexError.
226 Note how the line with 'total' does not raise IndexError.
226
227
227 If you want to split these (yielding lists), call fields() without
228 If you want to split these (yielding lists), call fields() without
228 arguments::
229 arguments::
229
230
230 [Q:doc/examples]|7> _.fields()
231 [Q:doc/examples]|7> _.fields()
231 <7>
232 <7>
232 [['total'],
233 [['total'],
233 ['example-demo.py', '-rw-rw-rw-'],
234 ['example-demo.py', '-rw-rw-rw-'],
234 ['example-gnuplot.py', '-rwxrwxrwx'],
235 ['example-gnuplot.py', '-rwxrwxrwx'],
235 ['extension.py', '-rwxrwxrwx'],
236 ['extension.py', '-rwxrwxrwx'],
236 ['seteditor.py', '-rwxrwxrwx'],
237 ['seteditor.py', '-rwxrwxrwx'],
237 ['seteditor.pyc', '-rwxrwxrwx']]
238 ['seteditor.pyc', '-rwxrwxrwx']]
238
239
239 If you want to pass these separated with spaces to a command (typical
240 If you want to pass these separated with spaces to a command (typical
240 for lists if files), use the .s property::
241 for lists if files), use the .s property::
241
242
242
243
243 [Q:doc/examples]|13> files = l2.fields(8).s
244 [Q:doc/examples]|13> files = l2.fields(8).s
244 [Q:doc/examples]|14> files
245 [Q:doc/examples]|14> files
245 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
246 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
246 [Q:doc/examples]|15> ls $files
247 [Q:doc/examples]|15> ls $files
247 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
248 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
248
249
249 SLists are inherited from normal python lists, so every list method is
250 SLists are inherited from normal python lists, so every list method is
250 available::
251 available::
251
252
252 [Q:doc/examples]|21> lines.append('hey')
253 [Q:doc/examples]|21> lines.append('hey')
253
254
254
255
255 Real world example: remove all files outside version control
256 Real world example: remove all files outside version control
256 ------------------------------------------------------------
257 ------------------------------------------------------------
257
258
258 First, capture output of "hg status"::
259 First, capture output of "hg status"::
259
260
260 [Q:/ipython]|28> out = !hg status
261 [Q:/ipython]|28> out = !hg status
261 ==
262 ==
262 ['M IPython\\extensions\\ipy_kitcfg.py',
263 ['M IPython\\extensions\\ipy_kitcfg.py',
263 'M IPython\\extensions\\ipy_rehashdir.py',
264 'M IPython\\extensions\\ipy_rehashdir.py',
264 ...
265 ...
265 '? build\\lib\\IPython\\Debugger.py',
266 '? build\\lib\\IPython\\Debugger.py',
266 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
267 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
267 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
268 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
268 ...
269 ...
269
270
270 (lines starting with ? are not under version control).
271 (lines starting with ? are not under version control).
271
272
272 ::
273 ::
273
274
274 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
275 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
275 [Q:/ipython]|36> junk
276 [Q:/ipython]|36> junk
276 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
277 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
277 ...
278 ...
278 10: build\bdist.win32\winexe\temp\_ctypes.py
279 10: build\bdist.win32\winexe\temp\_ctypes.py
279 11: build\bdist.win32\winexe\temp\_hashlib.py
280 11: build\bdist.win32\winexe\temp\_hashlib.py
280 12: build\bdist.win32\winexe\temp\_socket.py
281 12: build\bdist.win32\winexe\temp\_socket.py
281
282
282 Now we can just remove these files by doing 'rm $junk.s'.
283 Now we can just remove these files by doing 'rm $junk.s'.
283
284
284 The .s, .n, .p properties
285 The .s, .n, .p properties
285 -------------------------
286 -------------------------
286
287
287 The ``.s`` property returns one string where lines are separated by
288 The ``.s`` property returns one string where lines are separated by
288 single space (for convenient passing to system commands). The ``.n``
289 single space (for convenient passing to system commands). The ``.n``
289 property return one string where the lines are separated by a newline
290 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
291 (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
292 list are file names, ``.p`` can be used to get a list of "path" objects
292 for convenient file manipulation.
293 for convenient file manipulation.
293
294
General Comments 0
You need to be logged in to leave comments. Login now