##// END OF EJS Templates
making %clear a native magic
Paul Ivanov -
Show More
@@ -1,318 +1,321 b''
1 """Implementations for various useful completers.
1 """Implementations for various useful completers.
2
2
3 These are all loaded by default by IPython.
3 These are all loaded by default by IPython.
4 """
4 """
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2010-2011 The IPython Development Team.
6 # Copyright (C) 2010-2011 The IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the BSD License.
8 # Distributed under the terms of the BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib imports
18 # Stdlib imports
19 import glob
19 import glob
20 import inspect
20 import inspect
21 import os
21 import os
22 import re
22 import re
23 import sys
23 import sys
24
24
25 # Third-party imports
25 # Third-party imports
26 from time import time
26 from time import time
27 from zipimport import zipimporter
27 from zipimport import zipimporter
28
28
29 # Our own imports
29 # Our own imports
30 from IPython.core.completer import expand_user, compress_user
30 from IPython.core.completer import expand_user, compress_user
31 from IPython.core.error import TryNext
31 from IPython.core.error import TryNext
32 from IPython.utils import py3compat
32 from IPython.utils import py3compat
33 from IPython.utils._process_common import arg_split
33 from IPython.utils._process_common import arg_split
34
34
35 # FIXME: this should be pulled in with the right call via the component system
35 # FIXME: this should be pulled in with the right call via the component system
36 from IPython.core.ipapi import get as get_ipython
36 from IPython.core.ipapi import get as get_ipython
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Globals and constants
39 # Globals and constants
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41
41
42 # Time in seconds after which the rootmodules will be stored permanently in the
42 # Time in seconds after which the rootmodules will be stored permanently in the
43 # ipython ip.db database (kept in the user's .ipython dir).
43 # ipython ip.db database (kept in the user's .ipython dir).
44 TIMEOUT_STORAGE = 2
44 TIMEOUT_STORAGE = 2
45
45
46 # Time in seconds after which we give up
46 # Time in seconds after which we give up
47 TIMEOUT_GIVEUP = 20
47 TIMEOUT_GIVEUP = 20
48
48
49 # Regular expression for the python import statement
49 # Regular expression for the python import statement
50 import_re = re.compile(r'.*(\.so|\.py[cod]?)$')
50 import_re = re.compile(r'.*(\.so|\.py[cod]?)$')
51
51
52 # RE for the ipython %run command (python + ipython scripts)
52 # RE for the ipython %run command (python + ipython scripts)
53 magic_run_re = re.compile(r'.*(\.ipy|\.py[w]?)$')
53 magic_run_re = re.compile(r'.*(\.ipy|\.py[w]?)$')
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Local utilities
56 # Local utilities
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 def module_list(path):
59 def module_list(path):
60 """
60 """
61 Return the list containing the names of the modules available in the given
61 Return the list containing the names of the modules available in the given
62 folder.
62 folder.
63 """
63 """
64
64
65 if os.path.isdir(path):
65 if os.path.isdir(path):
66 folder_list = os.listdir(path)
66 folder_list = os.listdir(path)
67 elif path.endswith('.egg'):
67 elif path.endswith('.egg'):
68 try:
68 try:
69 folder_list = [f for f in zipimporter(path)._files]
69 folder_list = [f for f in zipimporter(path)._files]
70 except:
70 except:
71 folder_list = []
71 folder_list = []
72 else:
72 else:
73 folder_list = []
73 folder_list = []
74
74
75 if not folder_list:
75 if not folder_list:
76 return []
76 return []
77
77
78 # A few local constants to be used in loops below
78 # A few local constants to be used in loops below
79 isfile = os.path.isfile
79 isfile = os.path.isfile
80 pjoin = os.path.join
80 pjoin = os.path.join
81 basename = os.path.basename
81 basename = os.path.basename
82
82
83 # Now find actual path matches for packages or modules
83 # Now find actual path matches for packages or modules
84 folder_list = [p for p in folder_list
84 folder_list = [p for p in folder_list
85 if isfile(pjoin(path, p,'__init__.py'))
85 if isfile(pjoin(path, p,'__init__.py'))
86 or import_re.match(p) ]
86 or import_re.match(p) ]
87
87
88 return [basename(p).split('.')[0] for p in folder_list]
88 return [basename(p).split('.')[0] for p in folder_list]
89
89
90 def get_root_modules():
90 def get_root_modules():
91 """
91 """
92 Returns a list containing the names of all the modules available in the
92 Returns a list containing the names of all the modules available in the
93 folders of the pythonpath.
93 folders of the pythonpath.
94 """
94 """
95 ip = get_ipython()
95 ip = get_ipython()
96
96
97 if 'rootmodules' in ip.db:
97 if 'rootmodules' in ip.db:
98 return ip.db['rootmodules']
98 return ip.db['rootmodules']
99
99
100 t = time()
100 t = time()
101 store = False
101 store = False
102 modules = list(sys.builtin_module_names)
102 modules = list(sys.builtin_module_names)
103 for path in sys.path:
103 for path in sys.path:
104 modules += module_list(path)
104 modules += module_list(path)
105 if time() - t >= TIMEOUT_STORAGE and not store:
105 if time() - t >= TIMEOUT_STORAGE and not store:
106 store = True
106 store = True
107 print("\nCaching the list of root modules, please wait!")
107 print("\nCaching the list of root modules, please wait!")
108 print("(This will only be done once - type '%rehashx' to "
108 print("(This will only be done once - type '%rehashx' to "
109 "reset cache!)\n")
109 "reset cache!)\n")
110 sys.stdout.flush()
110 sys.stdout.flush()
111 if time() - t > TIMEOUT_GIVEUP:
111 if time() - t > TIMEOUT_GIVEUP:
112 print("This is taking too long, we give up.\n")
112 print("This is taking too long, we give up.\n")
113 ip.db['rootmodules'] = []
113 ip.db['rootmodules'] = []
114 return []
114 return []
115
115
116 modules = set(modules)
116 modules = set(modules)
117 if '__init__' in modules:
117 if '__init__' in modules:
118 modules.remove('__init__')
118 modules.remove('__init__')
119 modules = list(modules)
119 modules = list(modules)
120 if store:
120 if store:
121 ip.db['rootmodules'] = modules
121 ip.db['rootmodules'] = modules
122 return modules
122 return modules
123
123
124
124
125 def is_importable(module, attr, only_modules):
125 def is_importable(module, attr, only_modules):
126 if only_modules:
126 if only_modules:
127 return inspect.ismodule(getattr(module, attr))
127 return inspect.ismodule(getattr(module, attr))
128 else:
128 else:
129 return not(attr[:2] == '__' and attr[-2:] == '__')
129 return not(attr[:2] == '__' and attr[-2:] == '__')
130
130
131
131
132 def try_import(mod, only_modules=False):
132 def try_import(mod, only_modules=False):
133 try:
133 try:
134 m = __import__(mod)
134 m = __import__(mod)
135 except:
135 except:
136 return []
136 return []
137 mods = mod.split('.')
137 mods = mod.split('.')
138 for module in mods[1:]:
138 for module in mods[1:]:
139 m = getattr(m, module)
139 m = getattr(m, module)
140
140
141 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
141 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
142
142
143 completions = []
143 completions = []
144 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
144 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
145 completions.extend( [attr for attr in dir(m) if
145 completions.extend( [attr for attr in dir(m) if
146 is_importable(m, attr, only_modules)])
146 is_importable(m, attr, only_modules)])
147
147
148 completions.extend(getattr(m, '__all__', []))
148 completions.extend(getattr(m, '__all__', []))
149 if m_is_init:
149 if m_is_init:
150 completions.extend(module_list(os.path.dirname(m.__file__)))
150 completions.extend(module_list(os.path.dirname(m.__file__)))
151 completions = set(completions)
151 completions = set(completions)
152 if '__init__' in completions:
152 if '__init__' in completions:
153 completions.remove('__init__')
153 completions.remove('__init__')
154 return list(completions)
154 return list(completions)
155
155
156
156
157 #-----------------------------------------------------------------------------
157 #-----------------------------------------------------------------------------
158 # Completion-related functions.
158 # Completion-related functions.
159 #-----------------------------------------------------------------------------
159 #-----------------------------------------------------------------------------
160
160
161 def quick_completer(cmd, completions):
161 def quick_completer(cmd, completions):
162 """ Easily create a trivial completer for a command.
162 """ Easily create a trivial completer for a command.
163
163
164 Takes either a list of completions, or all completions in string (that will
164 Takes either a list of completions, or all completions in string (that will
165 be split on whitespace).
165 be split on whitespace).
166
166
167 Example::
167 Example::
168
168
169 [d:\ipython]|1> import ipy_completers
169 [d:\ipython]|1> import ipy_completers
170 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
170 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
171 [d:\ipython]|3> foo b<TAB>
171 [d:\ipython]|3> foo b<TAB>
172 bar baz
172 bar baz
173 [d:\ipython]|3> foo ba
173 [d:\ipython]|3> foo ba
174 """
174 """
175
175
176 if isinstance(completions, basestring):
176 if isinstance(completions, basestring):
177 completions = completions.split()
177 completions = completions.split()
178
178
179 def do_complete(self, event):
179 def do_complete(self, event):
180 return completions
180 return completions
181
181
182 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
182 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
183
183
184
185 def module_completion(line):
184 def module_completion(line):
186 """
185 """
187 Returns a list containing the completion possibilities for an import line.
186 Returns a list containing the completion possibilities for an import line.
188
187
189 The line looks like this :
188 The line looks like this :
190 'import xml.d'
189 'import xml.d'
191 'from xml.dom import'
190 'from xml.dom import'
192 """
191 """
193
192
194 words = line.split(' ')
193 words = line.split(' ')
195 nwords = len(words)
194 nwords = len(words)
196
195
197 # from whatever <tab> -> 'import '
196 # from whatever <tab> -> 'import '
198 if nwords == 3 and words[0] == 'from':
197 if nwords == 3 and words[0] == 'from':
199 return ['import ']
198 return ['import ']
200
199
201 # 'from xy<tab>' or 'import xy<tab>'
200 # 'from xy<tab>' or 'import xy<tab>'
202 if nwords < 3 and (words[0] in ['import','from']) :
201 if nwords < 3 and (words[0] in ['import','from']) :
203 if nwords == 1:
202 if nwords == 1:
204 return get_root_modules()
203 return get_root_modules()
205 mod = words[1].split('.')
204 mod = words[1].split('.')
206 if len(mod) < 2:
205 if len(mod) < 2:
207 return get_root_modules()
206 return get_root_modules()
208 completion_list = try_import('.'.join(mod[:-1]), True)
207 completion_list = try_import('.'.join(mod[:-1]), True)
209 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
208 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
210
209
211 # 'from xyz import abc<tab>'
210 # 'from xyz import abc<tab>'
212 if nwords >= 3 and words[0] == 'from':
211 if nwords >= 3 and words[0] == 'from':
213 mod = words[1]
212 mod = words[1]
214 return try_import(mod)
213 return try_import(mod)
215
214
216 #-----------------------------------------------------------------------------
215 #-----------------------------------------------------------------------------
217 # Completers
216 # Completers
218 #-----------------------------------------------------------------------------
217 #-----------------------------------------------------------------------------
219 # These all have the func(self, event) signature to be used as custom
218 # These all have the func(self, event) signature to be used as custom
220 # completers
219 # completers
221
220
222 def module_completer(self,event):
221 def module_completer(self,event):
223 """Give completions after user has typed 'import ...' or 'from ...'"""
222 """Give completions after user has typed 'import ...' or 'from ...'"""
224
223
225 # This works in all versions of python. While 2.5 has
224 # This works in all versions of python. While 2.5 has
226 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
225 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
227 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
226 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
228 # of possibly problematic side effects.
227 # of possibly problematic side effects.
229 # This search the folders in the sys.path for available modules.
228 # This search the folders in the sys.path for available modules.
230
229
231 return module_completion(event.line)
230 return module_completion(event.line)
232
231
233 # FIXME: there's a lot of logic common to the run, cd and builtin file
232 # FIXME: there's a lot of logic common to the run, cd and builtin file
234 # completers, that is currently reimplemented in each.
233 # completers, that is currently reimplemented in each.
235
234
236 def magic_run_completer(self, event):
235 def magic_run_completer(self, event):
237 """Complete files that end in .py or .ipy for the %run command.
236 """Complete files that end in .py or .ipy for the %run command.
238 """
237 """
239 comps = arg_split(event.line, strict=False)
238 comps = arg_split(event.line, strict=False)
240 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
239 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
241
240
242 #print("\nev=", event) # dbg
241 #print("\nev=", event) # dbg
243 #print("rp=", relpath) # dbg
242 #print("rp=", relpath) # dbg
244 #print('comps=', comps) # dbg
243 #print('comps=', comps) # dbg
245
244
246 lglob = glob.glob
245 lglob = glob.glob
247 isdir = os.path.isdir
246 isdir = os.path.isdir
248 relpath, tilde_expand, tilde_val = expand_user(relpath)
247 relpath, tilde_expand, tilde_val = expand_user(relpath)
249
248
250 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
249 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
251
250
252 # Find if the user has already typed the first filename, after which we
251 # Find if the user has already typed the first filename, after which we
253 # should complete on all files, since after the first one other files may
252 # should complete on all files, since after the first one other files may
254 # be arguments to the input script.
253 # be arguments to the input script.
255
254
256 if filter(magic_run_re.match, comps):
255 if filter(magic_run_re.match, comps):
257 pys = [f.replace('\\','/') for f in lglob('*')]
256 pys = [f.replace('\\','/') for f in lglob('*')]
258 else:
257 else:
259 pys = [f.replace('\\','/')
258 pys = [f.replace('\\','/')
260 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
259 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
261 lglob(relpath + '*.pyw')]
260 lglob(relpath + '*.pyw')]
262 #print('run comp:', dirs+pys) # dbg
261 #print('run comp:', dirs+pys) # dbg
263 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
262 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
264
263
265
264
266 def cd_completer(self, event):
265 def cd_completer(self, event):
267 """Completer function for cd, which only returns directories."""
266 """Completer function for cd, which only returns directories."""
268 ip = get_ipython()
267 ip = get_ipython()
269 relpath = event.symbol
268 relpath = event.symbol
270
269
271 #print(event) # dbg
270 #print(event) # dbg
272 if event.line.endswith('-b') or ' -b ' in event.line:
271 if event.line.endswith('-b') or ' -b ' in event.line:
273 # return only bookmark completions
272 # return only bookmark completions
274 bkms = self.db.get('bookmarks', None)
273 bkms = self.db.get('bookmarks', None)
275 if bkms:
274 if bkms:
276 return bkms.keys()
275 return bkms.keys()
277 else:
276 else:
278 return []
277 return []
279
278
280 if event.symbol == '-':
279 if event.symbol == '-':
281 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
280 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
282 # jump in directory history by number
281 # jump in directory history by number
283 fmt = '-%0' + width_dh +'d [%s]'
282 fmt = '-%0' + width_dh +'d [%s]'
284 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
283 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
285 if len(ents) > 1:
284 if len(ents) > 1:
286 return ents
285 return ents
287 return []
286 return []
288
287
289 if event.symbol.startswith('--'):
288 if event.symbol.startswith('--'):
290 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
289 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
291
290
292 # Expand ~ in path and normalize directory separators.
291 # Expand ~ in path and normalize directory separators.
293 relpath, tilde_expand, tilde_val = expand_user(relpath)
292 relpath, tilde_expand, tilde_val = expand_user(relpath)
294 relpath = relpath.replace('\\','/')
293 relpath = relpath.replace('\\','/')
295
294
296 found = []
295 found = []
297 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
296 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
298 if os.path.isdir(f)]:
297 if os.path.isdir(f)]:
299 if ' ' in d:
298 if ' ' in d:
300 # we don't want to deal with any of that, complex code
299 # we don't want to deal with any of that, complex code
301 # for this is elsewhere
300 # for this is elsewhere
302 raise TryNext
301 raise TryNext
303
302
304 found.append(d)
303 found.append(d)
305
304
306 if not found:
305 if not found:
307 if os.path.isdir(relpath):
306 if os.path.isdir(relpath):
308 return [compress_user(relpath, tilde_expand, tilde_val)]
307 return [compress_user(relpath, tilde_expand, tilde_val)]
309
308
310 # if no completions so far, try bookmarks
309 # if no completions so far, try bookmarks
311 bks = self.db.get('bookmarks',{}).iterkeys()
310 bks = self.db.get('bookmarks',{}).iterkeys()
312 bkmatches = [s for s in bks if s.startswith(event.symbol)]
311 bkmatches = [s for s in bks if s.startswith(event.symbol)]
313 if bkmatches:
312 if bkmatches:
314 return bkmatches
313 return bkmatches
315
314
316 raise TryNext
315 raise TryNext
317
316
318 return [compress_user(p, tilde_expand, tilde_val) for p in found]
317 return [compress_user(p, tilde_expand, tilde_val) for p in found]
318
319 def clear_completer(self, event):
320 "A completer for %clear magic"
321 return 'in out array dhist'.split()
@@ -1,2748 +1,2749 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.utils import PyColorize
67 from IPython.utils import PyColorize
68 from IPython.utils import io
68 from IPython.utils import io
69 from IPython.utils import py3compat
69 from IPython.utils import py3compat
70 from IPython.utils.doctestreload import doctest_reload
70 from IPython.utils.doctestreload import doctest_reload
71 from IPython.utils.io import ask_yes_no, rprint
71 from IPython.utils.io import ask_yes_no, rprint
72 from IPython.utils.ipstruct import Struct
72 from IPython.utils.ipstruct import Struct
73 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
73 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
74 from IPython.utils.pickleshare import PickleShareDB
74 from IPython.utils.pickleshare import PickleShareDB
75 from IPython.utils.process import system, getoutput
75 from IPython.utils.process import system, getoutput
76 from IPython.utils.strdispatch import StrDispatch
76 from IPython.utils.strdispatch import StrDispatch
77 from IPython.utils.syspathcontext import prepended_to_syspath
77 from IPython.utils.syspathcontext import prepended_to_syspath
78 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
78 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
79 DollarFormatter)
79 DollarFormatter)
80 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
80 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
81 List, Unicode, Instance, Type)
81 List, Unicode, Instance, Type)
82 from IPython.utils.warn import warn, error, fatal
82 from IPython.utils.warn import warn, error, fatal
83 import IPython.core.hooks
83 import IPython.core.hooks
84
84
85 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
86 # Globals
86 # Globals
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88
88
89 # compiled regexps for autoindent management
89 # compiled regexps for autoindent management
90 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
90 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
91
91
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93 # Utilities
93 # Utilities
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95
95
96 def softspace(file, newvalue):
96 def softspace(file, newvalue):
97 """Copied from code.py, to remove the dependency"""
97 """Copied from code.py, to remove the dependency"""
98
98
99 oldvalue = 0
99 oldvalue = 0
100 try:
100 try:
101 oldvalue = file.softspace
101 oldvalue = file.softspace
102 except AttributeError:
102 except AttributeError:
103 pass
103 pass
104 try:
104 try:
105 file.softspace = newvalue
105 file.softspace = newvalue
106 except (AttributeError, TypeError):
106 except (AttributeError, TypeError):
107 # "attribute-less object" or "read-only attributes"
107 # "attribute-less object" or "read-only attributes"
108 pass
108 pass
109 return oldvalue
109 return oldvalue
110
110
111
111
112 def no_op(*a, **kw): pass
112 def no_op(*a, **kw): pass
113
113
114 class NoOpContext(object):
114 class NoOpContext(object):
115 def __enter__(self): pass
115 def __enter__(self): pass
116 def __exit__(self, type, value, traceback): pass
116 def __exit__(self, type, value, traceback): pass
117 no_op_context = NoOpContext()
117 no_op_context = NoOpContext()
118
118
119 class SpaceInInput(Exception): pass
119 class SpaceInInput(Exception): pass
120
120
121 class Bunch: pass
121 class Bunch: pass
122
122
123
123
124 def get_default_colors():
124 def get_default_colors():
125 if sys.platform=='darwin':
125 if sys.platform=='darwin':
126 return "LightBG"
126 return "LightBG"
127 elif os.name=='nt':
127 elif os.name=='nt':
128 return 'Linux'
128 return 'Linux'
129 else:
129 else:
130 return 'Linux'
130 return 'Linux'
131
131
132
132
133 class SeparateUnicode(Unicode):
133 class SeparateUnicode(Unicode):
134 """A Unicode subclass to validate separate_in, separate_out, etc.
134 """A Unicode subclass to validate separate_in, separate_out, etc.
135
135
136 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
136 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
137 """
137 """
138
138
139 def validate(self, obj, value):
139 def validate(self, obj, value):
140 if value == '0': value = ''
140 if value == '0': value = ''
141 value = value.replace('\\n','\n')
141 value = value.replace('\\n','\n')
142 return super(SeparateUnicode, self).validate(obj, value)
142 return super(SeparateUnicode, self).validate(obj, value)
143
143
144
144
145 class ReadlineNoRecord(object):
145 class ReadlineNoRecord(object):
146 """Context manager to execute some code, then reload readline history
146 """Context manager to execute some code, then reload readline history
147 so that interactive input to the code doesn't appear when pressing up."""
147 so that interactive input to the code doesn't appear when pressing up."""
148 def __init__(self, shell):
148 def __init__(self, shell):
149 self.shell = shell
149 self.shell = shell
150 self._nested_level = 0
150 self._nested_level = 0
151
151
152 def __enter__(self):
152 def __enter__(self):
153 if self._nested_level == 0:
153 if self._nested_level == 0:
154 try:
154 try:
155 self.orig_length = self.current_length()
155 self.orig_length = self.current_length()
156 self.readline_tail = self.get_readline_tail()
156 self.readline_tail = self.get_readline_tail()
157 except (AttributeError, IndexError): # Can fail with pyreadline
157 except (AttributeError, IndexError): # Can fail with pyreadline
158 self.orig_length, self.readline_tail = 999999, []
158 self.orig_length, self.readline_tail = 999999, []
159 self._nested_level += 1
159 self._nested_level += 1
160
160
161 def __exit__(self, type, value, traceback):
161 def __exit__(self, type, value, traceback):
162 self._nested_level -= 1
162 self._nested_level -= 1
163 if self._nested_level == 0:
163 if self._nested_level == 0:
164 # Try clipping the end if it's got longer
164 # Try clipping the end if it's got longer
165 try:
165 try:
166 e = self.current_length() - self.orig_length
166 e = self.current_length() - self.orig_length
167 if e > 0:
167 if e > 0:
168 for _ in range(e):
168 for _ in range(e):
169 self.shell.readline.remove_history_item(self.orig_length)
169 self.shell.readline.remove_history_item(self.orig_length)
170
170
171 # If it still doesn't match, just reload readline history.
171 # If it still doesn't match, just reload readline history.
172 if self.current_length() != self.orig_length \
172 if self.current_length() != self.orig_length \
173 or self.get_readline_tail() != self.readline_tail:
173 or self.get_readline_tail() != self.readline_tail:
174 self.shell.refill_readline_hist()
174 self.shell.refill_readline_hist()
175 except (AttributeError, IndexError):
175 except (AttributeError, IndexError):
176 pass
176 pass
177 # Returning False will cause exceptions to propagate
177 # Returning False will cause exceptions to propagate
178 return False
178 return False
179
179
180 def current_length(self):
180 def current_length(self):
181 return self.shell.readline.get_current_history_length()
181 return self.shell.readline.get_current_history_length()
182
182
183 def get_readline_tail(self, n=10):
183 def get_readline_tail(self, n=10):
184 """Get the last n items in readline history."""
184 """Get the last n items in readline history."""
185 end = self.shell.readline.get_current_history_length() + 1
185 end = self.shell.readline.get_current_history_length() + 1
186 start = max(end-n, 1)
186 start = max(end-n, 1)
187 ghi = self.shell.readline.get_history_item
187 ghi = self.shell.readline.get_history_item
188 return [ghi(x) for x in range(start, end)]
188 return [ghi(x) for x in range(start, end)]
189
189
190 #-----------------------------------------------------------------------------
190 #-----------------------------------------------------------------------------
191 # Main IPython class
191 # Main IPython class
192 #-----------------------------------------------------------------------------
192 #-----------------------------------------------------------------------------
193
193
194 class InteractiveShell(SingletonConfigurable, Magic):
194 class InteractiveShell(SingletonConfigurable, Magic):
195 """An enhanced, interactive shell for Python."""
195 """An enhanced, interactive shell for Python."""
196
196
197 _instance = None
197 _instance = None
198
198
199 autocall = Enum((0,1,2), default_value=0, config=True, help=
199 autocall = Enum((0,1,2), default_value=0, config=True, help=
200 """
200 """
201 Make IPython automatically call any callable object even if you didn't
201 Make IPython automatically call any callable object even if you didn't
202 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
202 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
203 automatically. The value can be '0' to disable the feature, '1' for
203 automatically. The value can be '0' to disable the feature, '1' for
204 'smart' autocall, where it is not applied if there are no more
204 'smart' autocall, where it is not applied if there are no more
205 arguments on the line, and '2' for 'full' autocall, where all callable
205 arguments on the line, and '2' for 'full' autocall, where all callable
206 objects are automatically called (even if no arguments are present).
206 objects are automatically called (even if no arguments are present).
207 """
207 """
208 )
208 )
209 # TODO: remove all autoindent logic and put into frontends.
209 # TODO: remove all autoindent logic and put into frontends.
210 # We can't do this yet because even runlines uses the autoindent.
210 # We can't do this yet because even runlines uses the autoindent.
211 autoindent = CBool(True, config=True, help=
211 autoindent = CBool(True, config=True, help=
212 """
212 """
213 Autoindent IPython code entered interactively.
213 Autoindent IPython code entered interactively.
214 """
214 """
215 )
215 )
216 automagic = CBool(True, config=True, help=
216 automagic = CBool(True, config=True, help=
217 """
217 """
218 Enable magic commands to be called without the leading %.
218 Enable magic commands to be called without the leading %.
219 """
219 """
220 )
220 )
221 cache_size = Integer(1000, config=True, help=
221 cache_size = Integer(1000, config=True, help=
222 """
222 """
223 Set the size of the output cache. The default is 1000, you can
223 Set the size of the output cache. The default is 1000, you can
224 change it permanently in your config file. Setting it to 0 completely
224 change it permanently in your config file. Setting it to 0 completely
225 disables the caching system, and the minimum value accepted is 20 (if
225 disables the caching system, and the minimum value accepted is 20 (if
226 you provide a value less than 20, it is reset to 0 and a warning is
226 you provide a value less than 20, it is reset to 0 and a warning is
227 issued). This limit is defined because otherwise you'll spend more
227 issued). This limit is defined because otherwise you'll spend more
228 time re-flushing a too small cache than working
228 time re-flushing a too small cache than working
229 """
229 """
230 )
230 )
231 color_info = CBool(True, config=True, help=
231 color_info = CBool(True, config=True, help=
232 """
232 """
233 Use colors for displaying information about objects. Because this
233 Use colors for displaying information about objects. Because this
234 information is passed through a pager (like 'less'), and some pagers
234 information is passed through a pager (like 'less'), and some pagers
235 get confused with color codes, this capability can be turned off.
235 get confused with color codes, this capability can be turned off.
236 """
236 """
237 )
237 )
238 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
238 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
239 default_value=get_default_colors(), config=True,
239 default_value=get_default_colors(), config=True,
240 help="Set the color scheme (NoColor, Linux, or LightBG)."
240 help="Set the color scheme (NoColor, Linux, or LightBG)."
241 )
241 )
242 colors_force = CBool(False, help=
242 colors_force = CBool(False, help=
243 """
243 """
244 Force use of ANSI color codes, regardless of OS and readline
244 Force use of ANSI color codes, regardless of OS and readline
245 availability.
245 availability.
246 """
246 """
247 # FIXME: This is essentially a hack to allow ZMQShell to show colors
247 # FIXME: This is essentially a hack to allow ZMQShell to show colors
248 # without readline on Win32. When the ZMQ formatting system is
248 # without readline on Win32. When the ZMQ formatting system is
249 # refactored, this should be removed.
249 # refactored, this should be removed.
250 )
250 )
251 debug = CBool(False, config=True)
251 debug = CBool(False, config=True)
252 deep_reload = CBool(False, config=True, help=
252 deep_reload = CBool(False, config=True, help=
253 """
253 """
254 Enable deep (recursive) reloading by default. IPython can use the
254 Enable deep (recursive) reloading by default. IPython can use the
255 deep_reload module which reloads changes in modules recursively (it
255 deep_reload module which reloads changes in modules recursively (it
256 replaces the reload() function, so you don't need to change anything to
256 replaces the reload() function, so you don't need to change anything to
257 use it). deep_reload() forces a full reload of modules whose code may
257 use it). deep_reload() forces a full reload of modules whose code may
258 have changed, which the default reload() function does not. When
258 have changed, which the default reload() function does not. When
259 deep_reload is off, IPython will use the normal reload(), but
259 deep_reload is off, IPython will use the normal reload(), but
260 deep_reload will still be available as dreload().
260 deep_reload will still be available as dreload().
261 """
261 """
262 )
262 )
263 disable_failing_post_execute = CBool(False, config=True,
263 disable_failing_post_execute = CBool(False, config=True,
264 help="Don't call post-execute functions that have failed in the past."""
264 help="Don't call post-execute functions that have failed in the past."""
265 )
265 )
266 display_formatter = Instance(DisplayFormatter)
266 display_formatter = Instance(DisplayFormatter)
267 displayhook_class = Type(DisplayHook)
267 displayhook_class = Type(DisplayHook)
268 display_pub_class = Type(DisplayPublisher)
268 display_pub_class = Type(DisplayPublisher)
269
269
270 exit_now = CBool(False)
270 exit_now = CBool(False)
271 exiter = Instance(ExitAutocall)
271 exiter = Instance(ExitAutocall)
272 def _exiter_default(self):
272 def _exiter_default(self):
273 return ExitAutocall(self)
273 return ExitAutocall(self)
274 # Monotonically increasing execution counter
274 # Monotonically increasing execution counter
275 execution_count = Integer(1)
275 execution_count = Integer(1)
276 filename = Unicode("<ipython console>")
276 filename = Unicode("<ipython console>")
277 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
277 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
278
278
279 # Input splitter, to split entire cells of input into either individual
279 # Input splitter, to split entire cells of input into either individual
280 # interactive statements or whole blocks.
280 # interactive statements or whole blocks.
281 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
281 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
282 (), {})
282 (), {})
283 logstart = CBool(False, config=True, help=
283 logstart = CBool(False, config=True, help=
284 """
284 """
285 Start logging to the default log file.
285 Start logging to the default log file.
286 """
286 """
287 )
287 )
288 logfile = Unicode('', config=True, help=
288 logfile = Unicode('', config=True, help=
289 """
289 """
290 The name of the logfile to use.
290 The name of the logfile to use.
291 """
291 """
292 )
292 )
293 logappend = Unicode('', config=True, help=
293 logappend = Unicode('', config=True, help=
294 """
294 """
295 Start logging to the given file in append mode.
295 Start logging to the given file in append mode.
296 """
296 """
297 )
297 )
298 object_info_string_level = Enum((0,1,2), default_value=0,
298 object_info_string_level = Enum((0,1,2), default_value=0,
299 config=True)
299 config=True)
300 pdb = CBool(False, config=True, help=
300 pdb = CBool(False, config=True, help=
301 """
301 """
302 Automatically call the pdb debugger after every exception.
302 Automatically call the pdb debugger after every exception.
303 """
303 """
304 )
304 )
305 multiline_history = CBool(sys.platform != 'win32', config=True,
305 multiline_history = CBool(sys.platform != 'win32', config=True,
306 help="Save multi-line entries as one entry in readline history"
306 help="Save multi-line entries as one entry in readline history"
307 )
307 )
308
308
309 # deprecated prompt traits:
309 # deprecated prompt traits:
310
310
311 prompt_in1 = Unicode('In [\\#]: ', config=True,
311 prompt_in1 = Unicode('In [\\#]: ', config=True,
312 help="Deprecated, use PromptManager.in_template")
312 help="Deprecated, use PromptManager.in_template")
313 prompt_in2 = Unicode(' .\\D.: ', config=True,
313 prompt_in2 = Unicode(' .\\D.: ', config=True,
314 help="Deprecated, use PromptManager.in2_template")
314 help="Deprecated, use PromptManager.in2_template")
315 prompt_out = Unicode('Out[\\#]: ', config=True,
315 prompt_out = Unicode('Out[\\#]: ', config=True,
316 help="Deprecated, use PromptManager.out_template")
316 help="Deprecated, use PromptManager.out_template")
317 prompts_pad_left = CBool(True, config=True,
317 prompts_pad_left = CBool(True, config=True,
318 help="Deprecated, use PromptManager.justify")
318 help="Deprecated, use PromptManager.justify")
319
319
320 def _prompt_trait_changed(self, name, old, new):
320 def _prompt_trait_changed(self, name, old, new):
321 table = {
321 table = {
322 'prompt_in1' : 'in_template',
322 'prompt_in1' : 'in_template',
323 'prompt_in2' : 'in2_template',
323 'prompt_in2' : 'in2_template',
324 'prompt_out' : 'out_template',
324 'prompt_out' : 'out_template',
325 'prompts_pad_left' : 'justify',
325 'prompts_pad_left' : 'justify',
326 }
326 }
327 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
327 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
328 name=name, newname=table[name])
328 name=name, newname=table[name])
329 )
329 )
330 # protect against weird cases where self.config may not exist:
330 # protect against weird cases where self.config may not exist:
331 if self.config is not None:
331 if self.config is not None:
332 # propagate to corresponding PromptManager trait
332 # propagate to corresponding PromptManager trait
333 setattr(self.config.PromptManager, table[name], new)
333 setattr(self.config.PromptManager, table[name], new)
334
334
335 _prompt_in1_changed = _prompt_trait_changed
335 _prompt_in1_changed = _prompt_trait_changed
336 _prompt_in2_changed = _prompt_trait_changed
336 _prompt_in2_changed = _prompt_trait_changed
337 _prompt_out_changed = _prompt_trait_changed
337 _prompt_out_changed = _prompt_trait_changed
338 _prompt_pad_left_changed = _prompt_trait_changed
338 _prompt_pad_left_changed = _prompt_trait_changed
339
339
340 show_rewritten_input = CBool(True, config=True,
340 show_rewritten_input = CBool(True, config=True,
341 help="Show rewritten input, e.g. for autocall."
341 help="Show rewritten input, e.g. for autocall."
342 )
342 )
343
343
344 quiet = CBool(False, config=True)
344 quiet = CBool(False, config=True)
345
345
346 history_length = Integer(10000, config=True)
346 history_length = Integer(10000, config=True)
347
347
348 # The readline stuff will eventually be moved to the terminal subclass
348 # The readline stuff will eventually be moved to the terminal subclass
349 # but for now, we can't do that as readline is welded in everywhere.
349 # but for now, we can't do that as readline is welded in everywhere.
350 readline_use = CBool(True, config=True)
350 readline_use = CBool(True, config=True)
351 readline_remove_delims = Unicode('-/~', config=True)
351 readline_remove_delims = Unicode('-/~', config=True)
352 # don't use \M- bindings by default, because they
352 # don't use \M- bindings by default, because they
353 # conflict with 8-bit encodings. See gh-58,gh-88
353 # conflict with 8-bit encodings. See gh-58,gh-88
354 readline_parse_and_bind = List([
354 readline_parse_and_bind = List([
355 'tab: complete',
355 'tab: complete',
356 '"\C-l": clear-screen',
356 '"\C-l": clear-screen',
357 'set show-all-if-ambiguous on',
357 'set show-all-if-ambiguous on',
358 '"\C-o": tab-insert',
358 '"\C-o": tab-insert',
359 '"\C-r": reverse-search-history',
359 '"\C-r": reverse-search-history',
360 '"\C-s": forward-search-history',
360 '"\C-s": forward-search-history',
361 '"\C-p": history-search-backward',
361 '"\C-p": history-search-backward',
362 '"\C-n": history-search-forward',
362 '"\C-n": history-search-forward',
363 '"\e[A": history-search-backward',
363 '"\e[A": history-search-backward',
364 '"\e[B": history-search-forward',
364 '"\e[B": history-search-forward',
365 '"\C-k": kill-line',
365 '"\C-k": kill-line',
366 '"\C-u": unix-line-discard',
366 '"\C-u": unix-line-discard',
367 ], allow_none=False, config=True)
367 ], allow_none=False, config=True)
368
368
369 # TODO: this part of prompt management should be moved to the frontends.
369 # TODO: this part of prompt management should be moved to the frontends.
370 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
370 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
371 separate_in = SeparateUnicode('\n', config=True)
371 separate_in = SeparateUnicode('\n', config=True)
372 separate_out = SeparateUnicode('', config=True)
372 separate_out = SeparateUnicode('', config=True)
373 separate_out2 = SeparateUnicode('', config=True)
373 separate_out2 = SeparateUnicode('', config=True)
374 wildcards_case_sensitive = CBool(True, config=True)
374 wildcards_case_sensitive = CBool(True, config=True)
375 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
375 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
376 default_value='Context', config=True)
376 default_value='Context', config=True)
377
377
378 # Subcomponents of InteractiveShell
378 # Subcomponents of InteractiveShell
379 alias_manager = Instance('IPython.core.alias.AliasManager')
379 alias_manager = Instance('IPython.core.alias.AliasManager')
380 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
380 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
381 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
381 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
382 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
382 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
383 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
383 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
384 plugin_manager = Instance('IPython.core.plugin.PluginManager')
384 plugin_manager = Instance('IPython.core.plugin.PluginManager')
385 payload_manager = Instance('IPython.core.payload.PayloadManager')
385 payload_manager = Instance('IPython.core.payload.PayloadManager')
386 history_manager = Instance('IPython.core.history.HistoryManager')
386 history_manager = Instance('IPython.core.history.HistoryManager')
387
387
388 profile_dir = Instance('IPython.core.application.ProfileDir')
388 profile_dir = Instance('IPython.core.application.ProfileDir')
389 @property
389 @property
390 def profile(self):
390 def profile(self):
391 if self.profile_dir is not None:
391 if self.profile_dir is not None:
392 name = os.path.basename(self.profile_dir.location)
392 name = os.path.basename(self.profile_dir.location)
393 return name.replace('profile_','')
393 return name.replace('profile_','')
394
394
395
395
396 # Private interface
396 # Private interface
397 _post_execute = Instance(dict)
397 _post_execute = Instance(dict)
398
398
399 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
399 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
400 user_module=None, user_ns=None,
400 user_module=None, user_ns=None,
401 custom_exceptions=((), None)):
401 custom_exceptions=((), None)):
402
402
403 # This is where traits with a config_key argument are updated
403 # This is where traits with a config_key argument are updated
404 # from the values on config.
404 # from the values on config.
405 super(InteractiveShell, self).__init__(config=config)
405 super(InteractiveShell, self).__init__(config=config)
406 self.configurables = [self]
406 self.configurables = [self]
407
407
408 # These are relatively independent and stateless
408 # These are relatively independent and stateless
409 self.init_ipython_dir(ipython_dir)
409 self.init_ipython_dir(ipython_dir)
410 self.init_profile_dir(profile_dir)
410 self.init_profile_dir(profile_dir)
411 self.init_instance_attrs()
411 self.init_instance_attrs()
412 self.init_environment()
412 self.init_environment()
413
413
414 # Create namespaces (user_ns, user_global_ns, etc.)
414 # Create namespaces (user_ns, user_global_ns, etc.)
415 self.init_create_namespaces(user_module, user_ns)
415 self.init_create_namespaces(user_module, user_ns)
416 # This has to be done after init_create_namespaces because it uses
416 # This has to be done after init_create_namespaces because it uses
417 # something in self.user_ns, but before init_sys_modules, which
417 # something in self.user_ns, but before init_sys_modules, which
418 # is the first thing to modify sys.
418 # is the first thing to modify sys.
419 # TODO: When we override sys.stdout and sys.stderr before this class
419 # TODO: When we override sys.stdout and sys.stderr before this class
420 # is created, we are saving the overridden ones here. Not sure if this
420 # is created, we are saving the overridden ones here. Not sure if this
421 # is what we want to do.
421 # is what we want to do.
422 self.save_sys_module_state()
422 self.save_sys_module_state()
423 self.init_sys_modules()
423 self.init_sys_modules()
424
424
425 # While we're trying to have each part of the code directly access what
425 # While we're trying to have each part of the code directly access what
426 # it needs without keeping redundant references to objects, we have too
426 # it needs without keeping redundant references to objects, we have too
427 # much legacy code that expects ip.db to exist.
427 # much legacy code that expects ip.db to exist.
428 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
428 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
429
429
430 self.init_history()
430 self.init_history()
431 self.init_encoding()
431 self.init_encoding()
432 self.init_prefilter()
432 self.init_prefilter()
433
433
434 Magic.__init__(self, self)
434 Magic.__init__(self, self)
435
435
436 self.init_syntax_highlighting()
436 self.init_syntax_highlighting()
437 self.init_hooks()
437 self.init_hooks()
438 self.init_pushd_popd_magic()
438 self.init_pushd_popd_magic()
439 # self.init_traceback_handlers use to be here, but we moved it below
439 # self.init_traceback_handlers use to be here, but we moved it below
440 # because it and init_io have to come after init_readline.
440 # because it and init_io have to come after init_readline.
441 self.init_user_ns()
441 self.init_user_ns()
442 self.init_logger()
442 self.init_logger()
443 self.init_alias()
443 self.init_alias()
444 self.init_builtins()
444 self.init_builtins()
445
445
446 # pre_config_initialization
446 # pre_config_initialization
447
447
448 # The next section should contain everything that was in ipmaker.
448 # The next section should contain everything that was in ipmaker.
449 self.init_logstart()
449 self.init_logstart()
450
450
451 # The following was in post_config_initialization
451 # The following was in post_config_initialization
452 self.init_inspector()
452 self.init_inspector()
453 # init_readline() must come before init_io(), because init_io uses
453 # init_readline() must come before init_io(), because init_io uses
454 # readline related things.
454 # readline related things.
455 self.init_readline()
455 self.init_readline()
456 # We save this here in case user code replaces raw_input, but it needs
456 # We save this here in case user code replaces raw_input, but it needs
457 # to be after init_readline(), because PyPy's readline works by replacing
457 # to be after init_readline(), because PyPy's readline works by replacing
458 # raw_input.
458 # raw_input.
459 if py3compat.PY3:
459 if py3compat.PY3:
460 self.raw_input_original = input
460 self.raw_input_original = input
461 else:
461 else:
462 self.raw_input_original = raw_input
462 self.raw_input_original = raw_input
463 # init_completer must come after init_readline, because it needs to
463 # init_completer must come after init_readline, because it needs to
464 # know whether readline is present or not system-wide to configure the
464 # know whether readline is present or not system-wide to configure the
465 # completers, since the completion machinery can now operate
465 # completers, since the completion machinery can now operate
466 # independently of readline (e.g. over the network)
466 # independently of readline (e.g. over the network)
467 self.init_completer()
467 self.init_completer()
468 # TODO: init_io() needs to happen before init_traceback handlers
468 # TODO: init_io() needs to happen before init_traceback handlers
469 # because the traceback handlers hardcode the stdout/stderr streams.
469 # because the traceback handlers hardcode the stdout/stderr streams.
470 # This logic in in debugger.Pdb and should eventually be changed.
470 # This logic in in debugger.Pdb and should eventually be changed.
471 self.init_io()
471 self.init_io()
472 self.init_traceback_handlers(custom_exceptions)
472 self.init_traceback_handlers(custom_exceptions)
473 self.init_prompts()
473 self.init_prompts()
474 self.init_display_formatter()
474 self.init_display_formatter()
475 self.init_display_pub()
475 self.init_display_pub()
476 self.init_displayhook()
476 self.init_displayhook()
477 self.init_reload_doctest()
477 self.init_reload_doctest()
478 self.init_magics()
478 self.init_magics()
479 self.init_pdb()
479 self.init_pdb()
480 self.init_extension_manager()
480 self.init_extension_manager()
481 self.init_plugin_manager()
481 self.init_plugin_manager()
482 self.init_payload()
482 self.init_payload()
483 self.hooks.late_startup_hook()
483 self.hooks.late_startup_hook()
484 atexit.register(self.atexit_operations)
484 atexit.register(self.atexit_operations)
485
485
486 def get_ipython(self):
486 def get_ipython(self):
487 """Return the currently running IPython instance."""
487 """Return the currently running IPython instance."""
488 return self
488 return self
489
489
490 #-------------------------------------------------------------------------
490 #-------------------------------------------------------------------------
491 # Trait changed handlers
491 # Trait changed handlers
492 #-------------------------------------------------------------------------
492 #-------------------------------------------------------------------------
493
493
494 def _ipython_dir_changed(self, name, new):
494 def _ipython_dir_changed(self, name, new):
495 if not os.path.isdir(new):
495 if not os.path.isdir(new):
496 os.makedirs(new, mode = 0777)
496 os.makedirs(new, mode = 0777)
497
497
498 def set_autoindent(self,value=None):
498 def set_autoindent(self,value=None):
499 """Set the autoindent flag, checking for readline support.
499 """Set the autoindent flag, checking for readline support.
500
500
501 If called with no arguments, it acts as a toggle."""
501 If called with no arguments, it acts as a toggle."""
502
502
503 if value != 0 and not self.has_readline:
503 if value != 0 and not self.has_readline:
504 if os.name == 'posix':
504 if os.name == 'posix':
505 warn("The auto-indent feature requires the readline library")
505 warn("The auto-indent feature requires the readline library")
506 self.autoindent = 0
506 self.autoindent = 0
507 return
507 return
508 if value is None:
508 if value is None:
509 self.autoindent = not self.autoindent
509 self.autoindent = not self.autoindent
510 else:
510 else:
511 self.autoindent = value
511 self.autoindent = value
512
512
513 #-------------------------------------------------------------------------
513 #-------------------------------------------------------------------------
514 # init_* methods called by __init__
514 # init_* methods called by __init__
515 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
516
516
517 def init_ipython_dir(self, ipython_dir):
517 def init_ipython_dir(self, ipython_dir):
518 if ipython_dir is not None:
518 if ipython_dir is not None:
519 self.ipython_dir = ipython_dir
519 self.ipython_dir = ipython_dir
520 return
520 return
521
521
522 self.ipython_dir = get_ipython_dir()
522 self.ipython_dir = get_ipython_dir()
523
523
524 def init_profile_dir(self, profile_dir):
524 def init_profile_dir(self, profile_dir):
525 if profile_dir is not None:
525 if profile_dir is not None:
526 self.profile_dir = profile_dir
526 self.profile_dir = profile_dir
527 return
527 return
528 self.profile_dir =\
528 self.profile_dir =\
529 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
529 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
530
530
531 def init_instance_attrs(self):
531 def init_instance_attrs(self):
532 self.more = False
532 self.more = False
533
533
534 # command compiler
534 # command compiler
535 self.compile = CachingCompiler()
535 self.compile = CachingCompiler()
536
536
537 # Make an empty namespace, which extension writers can rely on both
537 # Make an empty namespace, which extension writers can rely on both
538 # existing and NEVER being used by ipython itself. This gives them a
538 # existing and NEVER being used by ipython itself. This gives them a
539 # convenient location for storing additional information and state
539 # convenient location for storing additional information and state
540 # their extensions may require, without fear of collisions with other
540 # their extensions may require, without fear of collisions with other
541 # ipython names that may develop later.
541 # ipython names that may develop later.
542 self.meta = Struct()
542 self.meta = Struct()
543
543
544 # Temporary files used for various purposes. Deleted at exit.
544 # Temporary files used for various purposes. Deleted at exit.
545 self.tempfiles = []
545 self.tempfiles = []
546
546
547 # Keep track of readline usage (later set by init_readline)
547 # Keep track of readline usage (later set by init_readline)
548 self.has_readline = False
548 self.has_readline = False
549
549
550 # keep track of where we started running (mainly for crash post-mortem)
550 # keep track of where we started running (mainly for crash post-mortem)
551 # This is not being used anywhere currently.
551 # This is not being used anywhere currently.
552 self.starting_dir = os.getcwdu()
552 self.starting_dir = os.getcwdu()
553
553
554 # Indentation management
554 # Indentation management
555 self.indent_current_nsp = 0
555 self.indent_current_nsp = 0
556
556
557 # Dict to track post-execution functions that have been registered
557 # Dict to track post-execution functions that have been registered
558 self._post_execute = {}
558 self._post_execute = {}
559
559
560 def init_environment(self):
560 def init_environment(self):
561 """Any changes we need to make to the user's environment."""
561 """Any changes we need to make to the user's environment."""
562 pass
562 pass
563
563
564 def init_encoding(self):
564 def init_encoding(self):
565 # Get system encoding at startup time. Certain terminals (like Emacs
565 # Get system encoding at startup time. Certain terminals (like Emacs
566 # under Win32 have it set to None, and we need to have a known valid
566 # under Win32 have it set to None, and we need to have a known valid
567 # encoding to use in the raw_input() method
567 # encoding to use in the raw_input() method
568 try:
568 try:
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
570 except AttributeError:
570 except AttributeError:
571 self.stdin_encoding = 'ascii'
571 self.stdin_encoding = 'ascii'
572
572
573 def init_syntax_highlighting(self):
573 def init_syntax_highlighting(self):
574 # Python source parser/formatter for syntax highlighting
574 # Python source parser/formatter for syntax highlighting
575 pyformat = PyColorize.Parser().format
575 pyformat = PyColorize.Parser().format
576 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
576 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
577
577
578 def init_pushd_popd_magic(self):
578 def init_pushd_popd_magic(self):
579 # for pushd/popd management
579 # for pushd/popd management
580 self.home_dir = get_home_dir()
580 self.home_dir = get_home_dir()
581
581
582 self.dir_stack = []
582 self.dir_stack = []
583
583
584 def init_logger(self):
584 def init_logger(self):
585 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
585 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
586 logmode='rotate')
586 logmode='rotate')
587
587
588 def init_logstart(self):
588 def init_logstart(self):
589 """Initialize logging in case it was requested at the command line.
589 """Initialize logging in case it was requested at the command line.
590 """
590 """
591 if self.logappend:
591 if self.logappend:
592 self.magic_logstart(self.logappend + ' append')
592 self.magic_logstart(self.logappend + ' append')
593 elif self.logfile:
593 elif self.logfile:
594 self.magic_logstart(self.logfile)
594 self.magic_logstart(self.logfile)
595 elif self.logstart:
595 elif self.logstart:
596 self.magic_logstart()
596 self.magic_logstart()
597
597
598 def init_builtins(self):
598 def init_builtins(self):
599 # A single, static flag that we set to True. Its presence indicates
599 # A single, static flag that we set to True. Its presence indicates
600 # that an IPython shell has been created, and we make no attempts at
600 # that an IPython shell has been created, and we make no attempts at
601 # removing on exit or representing the existence of more than one
601 # removing on exit or representing the existence of more than one
602 # IPython at a time.
602 # IPython at a time.
603 builtin_mod.__dict__['__IPYTHON__'] = True
603 builtin_mod.__dict__['__IPYTHON__'] = True
604
604
605 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
605 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
606 # manage on enter/exit, but with all our shells it's virtually
606 # manage on enter/exit, but with all our shells it's virtually
607 # impossible to get all the cases right. We're leaving the name in for
607 # impossible to get all the cases right. We're leaving the name in for
608 # those who adapted their codes to check for this flag, but will
608 # those who adapted their codes to check for this flag, but will
609 # eventually remove it after a few more releases.
609 # eventually remove it after a few more releases.
610 builtin_mod.__dict__['__IPYTHON__active'] = \
610 builtin_mod.__dict__['__IPYTHON__active'] = \
611 'Deprecated, check for __IPYTHON__'
611 'Deprecated, check for __IPYTHON__'
612
612
613 self.builtin_trap = BuiltinTrap(shell=self)
613 self.builtin_trap = BuiltinTrap(shell=self)
614
614
615 def init_inspector(self):
615 def init_inspector(self):
616 # Object inspector
616 # Object inspector
617 self.inspector = oinspect.Inspector(oinspect.InspectColors,
617 self.inspector = oinspect.Inspector(oinspect.InspectColors,
618 PyColorize.ANSICodeColors,
618 PyColorize.ANSICodeColors,
619 'NoColor',
619 'NoColor',
620 self.object_info_string_level)
620 self.object_info_string_level)
621
621
622 def init_io(self):
622 def init_io(self):
623 # This will just use sys.stdout and sys.stderr. If you want to
623 # This will just use sys.stdout and sys.stderr. If you want to
624 # override sys.stdout and sys.stderr themselves, you need to do that
624 # override sys.stdout and sys.stderr themselves, you need to do that
625 # *before* instantiating this class, because io holds onto
625 # *before* instantiating this class, because io holds onto
626 # references to the underlying streams.
626 # references to the underlying streams.
627 if sys.platform == 'win32' and self.has_readline:
627 if sys.platform == 'win32' and self.has_readline:
628 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
628 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
629 else:
629 else:
630 io.stdout = io.IOStream(sys.stdout)
630 io.stdout = io.IOStream(sys.stdout)
631 io.stderr = io.IOStream(sys.stderr)
631 io.stderr = io.IOStream(sys.stderr)
632
632
633 def init_prompts(self):
633 def init_prompts(self):
634 self.prompt_manager = PromptManager(shell=self, config=self.config)
634 self.prompt_manager = PromptManager(shell=self, config=self.config)
635 self.configurables.append(self.prompt_manager)
635 self.configurables.append(self.prompt_manager)
636
636
637 def init_display_formatter(self):
637 def init_display_formatter(self):
638 self.display_formatter = DisplayFormatter(config=self.config)
638 self.display_formatter = DisplayFormatter(config=self.config)
639 self.configurables.append(self.display_formatter)
639 self.configurables.append(self.display_formatter)
640
640
641 def init_display_pub(self):
641 def init_display_pub(self):
642 self.display_pub = self.display_pub_class(config=self.config)
642 self.display_pub = self.display_pub_class(config=self.config)
643 self.configurables.append(self.display_pub)
643 self.configurables.append(self.display_pub)
644
644
645 def init_displayhook(self):
645 def init_displayhook(self):
646 # Initialize displayhook, set in/out prompts and printing system
646 # Initialize displayhook, set in/out prompts and printing system
647 self.displayhook = self.displayhook_class(
647 self.displayhook = self.displayhook_class(
648 config=self.config,
648 config=self.config,
649 shell=self,
649 shell=self,
650 cache_size=self.cache_size,
650 cache_size=self.cache_size,
651 )
651 )
652 self.configurables.append(self.displayhook)
652 self.configurables.append(self.displayhook)
653 # This is a context manager that installs/revmoes the displayhook at
653 # This is a context manager that installs/revmoes the displayhook at
654 # the appropriate time.
654 # the appropriate time.
655 self.display_trap = DisplayTrap(hook=self.displayhook)
655 self.display_trap = DisplayTrap(hook=self.displayhook)
656
656
657 def init_reload_doctest(self):
657 def init_reload_doctest(self):
658 # Do a proper resetting of doctest, including the necessary displayhook
658 # Do a proper resetting of doctest, including the necessary displayhook
659 # monkeypatching
659 # monkeypatching
660 try:
660 try:
661 doctest_reload()
661 doctest_reload()
662 except ImportError:
662 except ImportError:
663 warn("doctest module does not exist.")
663 warn("doctest module does not exist.")
664
664
665 #-------------------------------------------------------------------------
665 #-------------------------------------------------------------------------
666 # Things related to injections into the sys module
666 # Things related to injections into the sys module
667 #-------------------------------------------------------------------------
667 #-------------------------------------------------------------------------
668
668
669 def save_sys_module_state(self):
669 def save_sys_module_state(self):
670 """Save the state of hooks in the sys module.
670 """Save the state of hooks in the sys module.
671
671
672 This has to be called after self.user_module is created.
672 This has to be called after self.user_module is created.
673 """
673 """
674 self._orig_sys_module_state = {}
674 self._orig_sys_module_state = {}
675 self._orig_sys_module_state['stdin'] = sys.stdin
675 self._orig_sys_module_state['stdin'] = sys.stdin
676 self._orig_sys_module_state['stdout'] = sys.stdout
676 self._orig_sys_module_state['stdout'] = sys.stdout
677 self._orig_sys_module_state['stderr'] = sys.stderr
677 self._orig_sys_module_state['stderr'] = sys.stderr
678 self._orig_sys_module_state['excepthook'] = sys.excepthook
678 self._orig_sys_module_state['excepthook'] = sys.excepthook
679 self._orig_sys_modules_main_name = self.user_module.__name__
679 self._orig_sys_modules_main_name = self.user_module.__name__
680
680
681 def restore_sys_module_state(self):
681 def restore_sys_module_state(self):
682 """Restore the state of the sys module."""
682 """Restore the state of the sys module."""
683 try:
683 try:
684 for k, v in self._orig_sys_module_state.iteritems():
684 for k, v in self._orig_sys_module_state.iteritems():
685 setattr(sys, k, v)
685 setattr(sys, k, v)
686 except AttributeError:
686 except AttributeError:
687 pass
687 pass
688 # Reset what what done in self.init_sys_modules
688 # Reset what what done in self.init_sys_modules
689 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
689 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
690
690
691 #-------------------------------------------------------------------------
691 #-------------------------------------------------------------------------
692 # Things related to hooks
692 # Things related to hooks
693 #-------------------------------------------------------------------------
693 #-------------------------------------------------------------------------
694
694
695 def init_hooks(self):
695 def init_hooks(self):
696 # hooks holds pointers used for user-side customizations
696 # hooks holds pointers used for user-side customizations
697 self.hooks = Struct()
697 self.hooks = Struct()
698
698
699 self.strdispatchers = {}
699 self.strdispatchers = {}
700
700
701 # Set all default hooks, defined in the IPython.hooks module.
701 # Set all default hooks, defined in the IPython.hooks module.
702 hooks = IPython.core.hooks
702 hooks = IPython.core.hooks
703 for hook_name in hooks.__all__:
703 for hook_name in hooks.__all__:
704 # default hooks have priority 100, i.e. low; user hooks should have
704 # default hooks have priority 100, i.e. low; user hooks should have
705 # 0-100 priority
705 # 0-100 priority
706 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
706 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
707
707
708 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
708 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
709 """set_hook(name,hook) -> sets an internal IPython hook.
709 """set_hook(name,hook) -> sets an internal IPython hook.
710
710
711 IPython exposes some of its internal API as user-modifiable hooks. By
711 IPython exposes some of its internal API as user-modifiable hooks. By
712 adding your function to one of these hooks, you can modify IPython's
712 adding your function to one of these hooks, you can modify IPython's
713 behavior to call at runtime your own routines."""
713 behavior to call at runtime your own routines."""
714
714
715 # At some point in the future, this should validate the hook before it
715 # At some point in the future, this should validate the hook before it
716 # accepts it. Probably at least check that the hook takes the number
716 # accepts it. Probably at least check that the hook takes the number
717 # of args it's supposed to.
717 # of args it's supposed to.
718
718
719 f = types.MethodType(hook,self)
719 f = types.MethodType(hook,self)
720
720
721 # check if the hook is for strdispatcher first
721 # check if the hook is for strdispatcher first
722 if str_key is not None:
722 if str_key is not None:
723 sdp = self.strdispatchers.get(name, StrDispatch())
723 sdp = self.strdispatchers.get(name, StrDispatch())
724 sdp.add_s(str_key, f, priority )
724 sdp.add_s(str_key, f, priority )
725 self.strdispatchers[name] = sdp
725 self.strdispatchers[name] = sdp
726 return
726 return
727 if re_key is not None:
727 if re_key is not None:
728 sdp = self.strdispatchers.get(name, StrDispatch())
728 sdp = self.strdispatchers.get(name, StrDispatch())
729 sdp.add_re(re.compile(re_key), f, priority )
729 sdp.add_re(re.compile(re_key), f, priority )
730 self.strdispatchers[name] = sdp
730 self.strdispatchers[name] = sdp
731 return
731 return
732
732
733 dp = getattr(self.hooks, name, None)
733 dp = getattr(self.hooks, name, None)
734 if name not in IPython.core.hooks.__all__:
734 if name not in IPython.core.hooks.__all__:
735 print "Warning! Hook '%s' is not one of %s" % \
735 print "Warning! Hook '%s' is not one of %s" % \
736 (name, IPython.core.hooks.__all__ )
736 (name, IPython.core.hooks.__all__ )
737 if not dp:
737 if not dp:
738 dp = IPython.core.hooks.CommandChainDispatcher()
738 dp = IPython.core.hooks.CommandChainDispatcher()
739
739
740 try:
740 try:
741 dp.add(f,priority)
741 dp.add(f,priority)
742 except AttributeError:
742 except AttributeError:
743 # it was not commandchain, plain old func - replace
743 # it was not commandchain, plain old func - replace
744 dp = f
744 dp = f
745
745
746 setattr(self.hooks,name, dp)
746 setattr(self.hooks,name, dp)
747
747
748 def register_post_execute(self, func):
748 def register_post_execute(self, func):
749 """Register a function for calling after code execution.
749 """Register a function for calling after code execution.
750 """
750 """
751 if not callable(func):
751 if not callable(func):
752 raise ValueError('argument %s must be callable' % func)
752 raise ValueError('argument %s must be callable' % func)
753 self._post_execute[func] = True
753 self._post_execute[func] = True
754
754
755 #-------------------------------------------------------------------------
755 #-------------------------------------------------------------------------
756 # Things related to the "main" module
756 # Things related to the "main" module
757 #-------------------------------------------------------------------------
757 #-------------------------------------------------------------------------
758
758
759 def new_main_mod(self,ns=None):
759 def new_main_mod(self,ns=None):
760 """Return a new 'main' module object for user code execution.
760 """Return a new 'main' module object for user code execution.
761 """
761 """
762 main_mod = self._user_main_module
762 main_mod = self._user_main_module
763 init_fakemod_dict(main_mod,ns)
763 init_fakemod_dict(main_mod,ns)
764 return main_mod
764 return main_mod
765
765
766 def cache_main_mod(self,ns,fname):
766 def cache_main_mod(self,ns,fname):
767 """Cache a main module's namespace.
767 """Cache a main module's namespace.
768
768
769 When scripts are executed via %run, we must keep a reference to the
769 When scripts are executed via %run, we must keep a reference to the
770 namespace of their __main__ module (a FakeModule instance) around so
770 namespace of their __main__ module (a FakeModule instance) around so
771 that Python doesn't clear it, rendering objects defined therein
771 that Python doesn't clear it, rendering objects defined therein
772 useless.
772 useless.
773
773
774 This method keeps said reference in a private dict, keyed by the
774 This method keeps said reference in a private dict, keyed by the
775 absolute path of the module object (which corresponds to the script
775 absolute path of the module object (which corresponds to the script
776 path). This way, for multiple executions of the same script we only
776 path). This way, for multiple executions of the same script we only
777 keep one copy of the namespace (the last one), thus preventing memory
777 keep one copy of the namespace (the last one), thus preventing memory
778 leaks from old references while allowing the objects from the last
778 leaks from old references while allowing the objects from the last
779 execution to be accessible.
779 execution to be accessible.
780
780
781 Note: we can not allow the actual FakeModule instances to be deleted,
781 Note: we can not allow the actual FakeModule instances to be deleted,
782 because of how Python tears down modules (it hard-sets all their
782 because of how Python tears down modules (it hard-sets all their
783 references to None without regard for reference counts). This method
783 references to None without regard for reference counts). This method
784 must therefore make a *copy* of the given namespace, to allow the
784 must therefore make a *copy* of the given namespace, to allow the
785 original module's __dict__ to be cleared and reused.
785 original module's __dict__ to be cleared and reused.
786
786
787
787
788 Parameters
788 Parameters
789 ----------
789 ----------
790 ns : a namespace (a dict, typically)
790 ns : a namespace (a dict, typically)
791
791
792 fname : str
792 fname : str
793 Filename associated with the namespace.
793 Filename associated with the namespace.
794
794
795 Examples
795 Examples
796 --------
796 --------
797
797
798 In [10]: import IPython
798 In [10]: import IPython
799
799
800 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
800 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
801
801
802 In [12]: IPython.__file__ in _ip._main_ns_cache
802 In [12]: IPython.__file__ in _ip._main_ns_cache
803 Out[12]: True
803 Out[12]: True
804 """
804 """
805 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
805 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
806
806
807 def clear_main_mod_cache(self):
807 def clear_main_mod_cache(self):
808 """Clear the cache of main modules.
808 """Clear the cache of main modules.
809
809
810 Mainly for use by utilities like %reset.
810 Mainly for use by utilities like %reset.
811
811
812 Examples
812 Examples
813 --------
813 --------
814
814
815 In [15]: import IPython
815 In [15]: import IPython
816
816
817 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
817 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
818
818
819 In [17]: len(_ip._main_ns_cache) > 0
819 In [17]: len(_ip._main_ns_cache) > 0
820 Out[17]: True
820 Out[17]: True
821
821
822 In [18]: _ip.clear_main_mod_cache()
822 In [18]: _ip.clear_main_mod_cache()
823
823
824 In [19]: len(_ip._main_ns_cache) == 0
824 In [19]: len(_ip._main_ns_cache) == 0
825 Out[19]: True
825 Out[19]: True
826 """
826 """
827 self._main_ns_cache.clear()
827 self._main_ns_cache.clear()
828
828
829 #-------------------------------------------------------------------------
829 #-------------------------------------------------------------------------
830 # Things related to debugging
830 # Things related to debugging
831 #-------------------------------------------------------------------------
831 #-------------------------------------------------------------------------
832
832
833 def init_pdb(self):
833 def init_pdb(self):
834 # Set calling of pdb on exceptions
834 # Set calling of pdb on exceptions
835 # self.call_pdb is a property
835 # self.call_pdb is a property
836 self.call_pdb = self.pdb
836 self.call_pdb = self.pdb
837
837
838 def _get_call_pdb(self):
838 def _get_call_pdb(self):
839 return self._call_pdb
839 return self._call_pdb
840
840
841 def _set_call_pdb(self,val):
841 def _set_call_pdb(self,val):
842
842
843 if val not in (0,1,False,True):
843 if val not in (0,1,False,True):
844 raise ValueError,'new call_pdb value must be boolean'
844 raise ValueError,'new call_pdb value must be boolean'
845
845
846 # store value in instance
846 # store value in instance
847 self._call_pdb = val
847 self._call_pdb = val
848
848
849 # notify the actual exception handlers
849 # notify the actual exception handlers
850 self.InteractiveTB.call_pdb = val
850 self.InteractiveTB.call_pdb = val
851
851
852 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
852 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
853 'Control auto-activation of pdb at exceptions')
853 'Control auto-activation of pdb at exceptions')
854
854
855 def debugger(self,force=False):
855 def debugger(self,force=False):
856 """Call the pydb/pdb debugger.
856 """Call the pydb/pdb debugger.
857
857
858 Keywords:
858 Keywords:
859
859
860 - force(False): by default, this routine checks the instance call_pdb
860 - force(False): by default, this routine checks the instance call_pdb
861 flag and does not actually invoke the debugger if the flag is false.
861 flag and does not actually invoke the debugger if the flag is false.
862 The 'force' option forces the debugger to activate even if the flag
862 The 'force' option forces the debugger to activate even if the flag
863 is false.
863 is false.
864 """
864 """
865
865
866 if not (force or self.call_pdb):
866 if not (force or self.call_pdb):
867 return
867 return
868
868
869 if not hasattr(sys,'last_traceback'):
869 if not hasattr(sys,'last_traceback'):
870 error('No traceback has been produced, nothing to debug.')
870 error('No traceback has been produced, nothing to debug.')
871 return
871 return
872
872
873 # use pydb if available
873 # use pydb if available
874 if debugger.has_pydb:
874 if debugger.has_pydb:
875 from pydb import pm
875 from pydb import pm
876 else:
876 else:
877 # fallback to our internal debugger
877 # fallback to our internal debugger
878 pm = lambda : self.InteractiveTB.debugger(force=True)
878 pm = lambda : self.InteractiveTB.debugger(force=True)
879
879
880 with self.readline_no_record:
880 with self.readline_no_record:
881 pm()
881 pm()
882
882
883 #-------------------------------------------------------------------------
883 #-------------------------------------------------------------------------
884 # Things related to IPython's various namespaces
884 # Things related to IPython's various namespaces
885 #-------------------------------------------------------------------------
885 #-------------------------------------------------------------------------
886 default_user_namespaces = True
886 default_user_namespaces = True
887
887
888 def init_create_namespaces(self, user_module=None, user_ns=None):
888 def init_create_namespaces(self, user_module=None, user_ns=None):
889 # Create the namespace where the user will operate. user_ns is
889 # Create the namespace where the user will operate. user_ns is
890 # normally the only one used, and it is passed to the exec calls as
890 # normally the only one used, and it is passed to the exec calls as
891 # the locals argument. But we do carry a user_global_ns namespace
891 # the locals argument. But we do carry a user_global_ns namespace
892 # given as the exec 'globals' argument, This is useful in embedding
892 # given as the exec 'globals' argument, This is useful in embedding
893 # situations where the ipython shell opens in a context where the
893 # situations where the ipython shell opens in a context where the
894 # distinction between locals and globals is meaningful. For
894 # distinction between locals and globals is meaningful. For
895 # non-embedded contexts, it is just the same object as the user_ns dict.
895 # non-embedded contexts, it is just the same object as the user_ns dict.
896
896
897 # FIXME. For some strange reason, __builtins__ is showing up at user
897 # FIXME. For some strange reason, __builtins__ is showing up at user
898 # level as a dict instead of a module. This is a manual fix, but I
898 # level as a dict instead of a module. This is a manual fix, but I
899 # should really track down where the problem is coming from. Alex
899 # should really track down where the problem is coming from. Alex
900 # Schmolck reported this problem first.
900 # Schmolck reported this problem first.
901
901
902 # A useful post by Alex Martelli on this topic:
902 # A useful post by Alex Martelli on this topic:
903 # Re: inconsistent value from __builtins__
903 # Re: inconsistent value from __builtins__
904 # Von: Alex Martelli <aleaxit@yahoo.com>
904 # Von: Alex Martelli <aleaxit@yahoo.com>
905 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
905 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
906 # Gruppen: comp.lang.python
906 # Gruppen: comp.lang.python
907
907
908 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
908 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
909 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
909 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
910 # > <type 'dict'>
910 # > <type 'dict'>
911 # > >>> print type(__builtins__)
911 # > >>> print type(__builtins__)
912 # > <type 'module'>
912 # > <type 'module'>
913 # > Is this difference in return value intentional?
913 # > Is this difference in return value intentional?
914
914
915 # Well, it's documented that '__builtins__' can be either a dictionary
915 # Well, it's documented that '__builtins__' can be either a dictionary
916 # or a module, and it's been that way for a long time. Whether it's
916 # or a module, and it's been that way for a long time. Whether it's
917 # intentional (or sensible), I don't know. In any case, the idea is
917 # intentional (or sensible), I don't know. In any case, the idea is
918 # that if you need to access the built-in namespace directly, you
918 # that if you need to access the built-in namespace directly, you
919 # should start with "import __builtin__" (note, no 's') which will
919 # should start with "import __builtin__" (note, no 's') which will
920 # definitely give you a module. Yeah, it's somewhat confusing:-(.
920 # definitely give you a module. Yeah, it's somewhat confusing:-(.
921
921
922 # These routines return a properly built module and dict as needed by
922 # These routines return a properly built module and dict as needed by
923 # the rest of the code, and can also be used by extension writers to
923 # the rest of the code, and can also be used by extension writers to
924 # generate properly initialized namespaces.
924 # generate properly initialized namespaces.
925 if (user_ns is not None) or (user_module is not None):
925 if (user_ns is not None) or (user_module is not None):
926 self.default_user_namespaces = False
926 self.default_user_namespaces = False
927 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
927 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
928
928
929 # A record of hidden variables we have added to the user namespace, so
929 # A record of hidden variables we have added to the user namespace, so
930 # we can list later only variables defined in actual interactive use.
930 # we can list later only variables defined in actual interactive use.
931 self.user_ns_hidden = set()
931 self.user_ns_hidden = set()
932
932
933 # Now that FakeModule produces a real module, we've run into a nasty
933 # Now that FakeModule produces a real module, we've run into a nasty
934 # problem: after script execution (via %run), the module where the user
934 # problem: after script execution (via %run), the module where the user
935 # code ran is deleted. Now that this object is a true module (needed
935 # code ran is deleted. Now that this object is a true module (needed
936 # so docetst and other tools work correctly), the Python module
936 # so docetst and other tools work correctly), the Python module
937 # teardown mechanism runs over it, and sets to None every variable
937 # teardown mechanism runs over it, and sets to None every variable
938 # present in that module. Top-level references to objects from the
938 # present in that module. Top-level references to objects from the
939 # script survive, because the user_ns is updated with them. However,
939 # script survive, because the user_ns is updated with them. However,
940 # calling functions defined in the script that use other things from
940 # calling functions defined in the script that use other things from
941 # the script will fail, because the function's closure had references
941 # the script will fail, because the function's closure had references
942 # to the original objects, which are now all None. So we must protect
942 # to the original objects, which are now all None. So we must protect
943 # these modules from deletion by keeping a cache.
943 # these modules from deletion by keeping a cache.
944 #
944 #
945 # To avoid keeping stale modules around (we only need the one from the
945 # To avoid keeping stale modules around (we only need the one from the
946 # last run), we use a dict keyed with the full path to the script, so
946 # last run), we use a dict keyed with the full path to the script, so
947 # only the last version of the module is held in the cache. Note,
947 # only the last version of the module is held in the cache. Note,
948 # however, that we must cache the module *namespace contents* (their
948 # however, that we must cache the module *namespace contents* (their
949 # __dict__). Because if we try to cache the actual modules, old ones
949 # __dict__). Because if we try to cache the actual modules, old ones
950 # (uncached) could be destroyed while still holding references (such as
950 # (uncached) could be destroyed while still holding references (such as
951 # those held by GUI objects that tend to be long-lived)>
951 # those held by GUI objects that tend to be long-lived)>
952 #
952 #
953 # The %reset command will flush this cache. See the cache_main_mod()
953 # The %reset command will flush this cache. See the cache_main_mod()
954 # and clear_main_mod_cache() methods for details on use.
954 # and clear_main_mod_cache() methods for details on use.
955
955
956 # This is the cache used for 'main' namespaces
956 # This is the cache used for 'main' namespaces
957 self._main_ns_cache = {}
957 self._main_ns_cache = {}
958 # And this is the single instance of FakeModule whose __dict__ we keep
958 # And this is the single instance of FakeModule whose __dict__ we keep
959 # copying and clearing for reuse on each %run
959 # copying and clearing for reuse on each %run
960 self._user_main_module = FakeModule()
960 self._user_main_module = FakeModule()
961
961
962 # A table holding all the namespaces IPython deals with, so that
962 # A table holding all the namespaces IPython deals with, so that
963 # introspection facilities can search easily.
963 # introspection facilities can search easily.
964 self.ns_table = {'user_global':self.user_module.__dict__,
964 self.ns_table = {'user_global':self.user_module.__dict__,
965 'user_local':self.user_ns,
965 'user_local':self.user_ns,
966 'builtin':builtin_mod.__dict__
966 'builtin':builtin_mod.__dict__
967 }
967 }
968
968
969 @property
969 @property
970 def user_global_ns(self):
970 def user_global_ns(self):
971 return self.user_module.__dict__
971 return self.user_module.__dict__
972
972
973 def prepare_user_module(self, user_module=None, user_ns=None):
973 def prepare_user_module(self, user_module=None, user_ns=None):
974 """Prepare the module and namespace in which user code will be run.
974 """Prepare the module and namespace in which user code will be run.
975
975
976 When IPython is started normally, both parameters are None: a new module
976 When IPython is started normally, both parameters are None: a new module
977 is created automatically, and its __dict__ used as the namespace.
977 is created automatically, and its __dict__ used as the namespace.
978
978
979 If only user_module is provided, its __dict__ is used as the namespace.
979 If only user_module is provided, its __dict__ is used as the namespace.
980 If only user_ns is provided, a dummy module is created, and user_ns
980 If only user_ns is provided, a dummy module is created, and user_ns
981 becomes the global namespace. If both are provided (as they may be
981 becomes the global namespace. If both are provided (as they may be
982 when embedding), user_ns is the local namespace, and user_module
982 when embedding), user_ns is the local namespace, and user_module
983 provides the global namespace.
983 provides the global namespace.
984
984
985 Parameters
985 Parameters
986 ----------
986 ----------
987 user_module : module, optional
987 user_module : module, optional
988 The current user module in which IPython is being run. If None,
988 The current user module in which IPython is being run. If None,
989 a clean module will be created.
989 a clean module will be created.
990 user_ns : dict, optional
990 user_ns : dict, optional
991 A namespace in which to run interactive commands.
991 A namespace in which to run interactive commands.
992
992
993 Returns
993 Returns
994 -------
994 -------
995 A tuple of user_module and user_ns, each properly initialised.
995 A tuple of user_module and user_ns, each properly initialised.
996 """
996 """
997 if user_module is None and user_ns is not None:
997 if user_module is None and user_ns is not None:
998 user_ns.setdefault("__name__", "__main__")
998 user_ns.setdefault("__name__", "__main__")
999 class DummyMod(object):
999 class DummyMod(object):
1000 "A dummy module used for IPython's interactive namespace."
1000 "A dummy module used for IPython's interactive namespace."
1001 pass
1001 pass
1002 user_module = DummyMod()
1002 user_module = DummyMod()
1003 user_module.__dict__ = user_ns
1003 user_module.__dict__ = user_ns
1004
1004
1005 if user_module is None:
1005 if user_module is None:
1006 user_module = types.ModuleType("__main__",
1006 user_module = types.ModuleType("__main__",
1007 doc="Automatically created module for IPython interactive environment")
1007 doc="Automatically created module for IPython interactive environment")
1008
1008
1009 # We must ensure that __builtin__ (without the final 's') is always
1009 # We must ensure that __builtin__ (without the final 's') is always
1010 # available and pointing to the __builtin__ *module*. For more details:
1010 # available and pointing to the __builtin__ *module*. For more details:
1011 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1011 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1012 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1012 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1013 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1013 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1014
1014
1015 if user_ns is None:
1015 if user_ns is None:
1016 user_ns = user_module.__dict__
1016 user_ns = user_module.__dict__
1017
1017
1018 return user_module, user_ns
1018 return user_module, user_ns
1019
1019
1020 def init_sys_modules(self):
1020 def init_sys_modules(self):
1021 # We need to insert into sys.modules something that looks like a
1021 # We need to insert into sys.modules something that looks like a
1022 # module but which accesses the IPython namespace, for shelve and
1022 # module but which accesses the IPython namespace, for shelve and
1023 # pickle to work interactively. Normally they rely on getting
1023 # pickle to work interactively. Normally they rely on getting
1024 # everything out of __main__, but for embedding purposes each IPython
1024 # everything out of __main__, but for embedding purposes each IPython
1025 # instance has its own private namespace, so we can't go shoving
1025 # instance has its own private namespace, so we can't go shoving
1026 # everything into __main__.
1026 # everything into __main__.
1027
1027
1028 # note, however, that we should only do this for non-embedded
1028 # note, however, that we should only do this for non-embedded
1029 # ipythons, which really mimic the __main__.__dict__ with their own
1029 # ipythons, which really mimic the __main__.__dict__ with their own
1030 # namespace. Embedded instances, on the other hand, should not do
1030 # namespace. Embedded instances, on the other hand, should not do
1031 # this because they need to manage the user local/global namespaces
1031 # this because they need to manage the user local/global namespaces
1032 # only, but they live within a 'normal' __main__ (meaning, they
1032 # only, but they live within a 'normal' __main__ (meaning, they
1033 # shouldn't overtake the execution environment of the script they're
1033 # shouldn't overtake the execution environment of the script they're
1034 # embedded in).
1034 # embedded in).
1035
1035
1036 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1036 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1037 main_name = self.user_module.__name__
1037 main_name = self.user_module.__name__
1038 sys.modules[main_name] = self.user_module
1038 sys.modules[main_name] = self.user_module
1039
1039
1040 def init_user_ns(self):
1040 def init_user_ns(self):
1041 """Initialize all user-visible namespaces to their minimum defaults.
1041 """Initialize all user-visible namespaces to their minimum defaults.
1042
1042
1043 Certain history lists are also initialized here, as they effectively
1043 Certain history lists are also initialized here, as they effectively
1044 act as user namespaces.
1044 act as user namespaces.
1045
1045
1046 Notes
1046 Notes
1047 -----
1047 -----
1048 All data structures here are only filled in, they are NOT reset by this
1048 All data structures here are only filled in, they are NOT reset by this
1049 method. If they were not empty before, data will simply be added to
1049 method. If they were not empty before, data will simply be added to
1050 therm.
1050 therm.
1051 """
1051 """
1052 # This function works in two parts: first we put a few things in
1052 # This function works in two parts: first we put a few things in
1053 # user_ns, and we sync that contents into user_ns_hidden so that these
1053 # user_ns, and we sync that contents into user_ns_hidden so that these
1054 # initial variables aren't shown by %who. After the sync, we add the
1054 # initial variables aren't shown by %who. After the sync, we add the
1055 # rest of what we *do* want the user to see with %who even on a new
1055 # rest of what we *do* want the user to see with %who even on a new
1056 # session (probably nothing, so theye really only see their own stuff)
1056 # session (probably nothing, so theye really only see their own stuff)
1057
1057
1058 # The user dict must *always* have a __builtin__ reference to the
1058 # The user dict must *always* have a __builtin__ reference to the
1059 # Python standard __builtin__ namespace, which must be imported.
1059 # Python standard __builtin__ namespace, which must be imported.
1060 # This is so that certain operations in prompt evaluation can be
1060 # This is so that certain operations in prompt evaluation can be
1061 # reliably executed with builtins. Note that we can NOT use
1061 # reliably executed with builtins. Note that we can NOT use
1062 # __builtins__ (note the 's'), because that can either be a dict or a
1062 # __builtins__ (note the 's'), because that can either be a dict or a
1063 # module, and can even mutate at runtime, depending on the context
1063 # module, and can even mutate at runtime, depending on the context
1064 # (Python makes no guarantees on it). In contrast, __builtin__ is
1064 # (Python makes no guarantees on it). In contrast, __builtin__ is
1065 # always a module object, though it must be explicitly imported.
1065 # always a module object, though it must be explicitly imported.
1066
1066
1067 # For more details:
1067 # For more details:
1068 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1068 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1069 ns = dict()
1069 ns = dict()
1070
1070
1071 # Put 'help' in the user namespace
1071 # Put 'help' in the user namespace
1072 try:
1072 try:
1073 from site import _Helper
1073 from site import _Helper
1074 ns['help'] = _Helper()
1074 ns['help'] = _Helper()
1075 except ImportError:
1075 except ImportError:
1076 warn('help() not available - check site.py')
1076 warn('help() not available - check site.py')
1077
1077
1078 # make global variables for user access to the histories
1078 # make global variables for user access to the histories
1079 ns['_ih'] = self.history_manager.input_hist_parsed
1079 ns['_ih'] = self.history_manager.input_hist_parsed
1080 ns['_oh'] = self.history_manager.output_hist
1080 ns['_oh'] = self.history_manager.output_hist
1081 ns['_dh'] = self.history_manager.dir_hist
1081 ns['_dh'] = self.history_manager.dir_hist
1082
1082
1083 ns['_sh'] = shadowns
1083 ns['_sh'] = shadowns
1084
1084
1085 # user aliases to input and output histories. These shouldn't show up
1085 # user aliases to input and output histories. These shouldn't show up
1086 # in %who, as they can have very large reprs.
1086 # in %who, as they can have very large reprs.
1087 ns['In'] = self.history_manager.input_hist_parsed
1087 ns['In'] = self.history_manager.input_hist_parsed
1088 ns['Out'] = self.history_manager.output_hist
1088 ns['Out'] = self.history_manager.output_hist
1089
1089
1090 # Store myself as the public api!!!
1090 # Store myself as the public api!!!
1091 ns['get_ipython'] = self.get_ipython
1091 ns['get_ipython'] = self.get_ipython
1092
1092
1093 ns['exit'] = self.exiter
1093 ns['exit'] = self.exiter
1094 ns['quit'] = self.exiter
1094 ns['quit'] = self.exiter
1095
1095
1096 # Sync what we've added so far to user_ns_hidden so these aren't seen
1096 # Sync what we've added so far to user_ns_hidden so these aren't seen
1097 # by %who
1097 # by %who
1098 self.user_ns_hidden.update(ns)
1098 self.user_ns_hidden.update(ns)
1099
1099
1100 # Anything put into ns now would show up in %who. Think twice before
1100 # Anything put into ns now would show up in %who. Think twice before
1101 # putting anything here, as we really want %who to show the user their
1101 # putting anything here, as we really want %who to show the user their
1102 # stuff, not our variables.
1102 # stuff, not our variables.
1103
1103
1104 # Finally, update the real user's namespace
1104 # Finally, update the real user's namespace
1105 self.user_ns.update(ns)
1105 self.user_ns.update(ns)
1106
1106
1107 @property
1107 @property
1108 def all_ns_refs(self):
1108 def all_ns_refs(self):
1109 """Get a list of references to all the namespace dictionaries in which
1109 """Get a list of references to all the namespace dictionaries in which
1110 IPython might store a user-created object.
1110 IPython might store a user-created object.
1111
1111
1112 Note that this does not include the displayhook, which also caches
1112 Note that this does not include the displayhook, which also caches
1113 objects from the output."""
1113 objects from the output."""
1114 return [self.user_ns, self.user_global_ns,
1114 return [self.user_ns, self.user_global_ns,
1115 self._user_main_module.__dict__] + self._main_ns_cache.values()
1115 self._user_main_module.__dict__] + self._main_ns_cache.values()
1116
1116
1117 def reset(self, new_session=True):
1117 def reset(self, new_session=True):
1118 """Clear all internal namespaces, and attempt to release references to
1118 """Clear all internal namespaces, and attempt to release references to
1119 user objects.
1119 user objects.
1120
1120
1121 If new_session is True, a new history session will be opened.
1121 If new_session is True, a new history session will be opened.
1122 """
1122 """
1123 # Clear histories
1123 # Clear histories
1124 self.history_manager.reset(new_session)
1124 self.history_manager.reset(new_session)
1125 # Reset counter used to index all histories
1125 # Reset counter used to index all histories
1126 if new_session:
1126 if new_session:
1127 self.execution_count = 1
1127 self.execution_count = 1
1128
1128
1129 # Flush cached output items
1129 # Flush cached output items
1130 if self.displayhook.do_full_cache:
1130 if self.displayhook.do_full_cache:
1131 self.displayhook.flush()
1131 self.displayhook.flush()
1132
1132
1133 # The main execution namespaces must be cleared very carefully,
1133 # The main execution namespaces must be cleared very carefully,
1134 # skipping the deletion of the builtin-related keys, because doing so
1134 # skipping the deletion of the builtin-related keys, because doing so
1135 # would cause errors in many object's __del__ methods.
1135 # would cause errors in many object's __del__ methods.
1136 if self.user_ns is not self.user_global_ns:
1136 if self.user_ns is not self.user_global_ns:
1137 self.user_ns.clear()
1137 self.user_ns.clear()
1138 ns = self.user_global_ns
1138 ns = self.user_global_ns
1139 drop_keys = set(ns.keys())
1139 drop_keys = set(ns.keys())
1140 drop_keys.discard('__builtin__')
1140 drop_keys.discard('__builtin__')
1141 drop_keys.discard('__builtins__')
1141 drop_keys.discard('__builtins__')
1142 drop_keys.discard('__name__')
1142 drop_keys.discard('__name__')
1143 for k in drop_keys:
1143 for k in drop_keys:
1144 del ns[k]
1144 del ns[k]
1145
1145
1146 self.user_ns_hidden.clear()
1146 self.user_ns_hidden.clear()
1147
1147
1148 # Restore the user namespaces to minimal usability
1148 # Restore the user namespaces to minimal usability
1149 self.init_user_ns()
1149 self.init_user_ns()
1150
1150
1151 # Restore the default and user aliases
1151 # Restore the default and user aliases
1152 self.alias_manager.clear_aliases()
1152 self.alias_manager.clear_aliases()
1153 self.alias_manager.init_aliases()
1153 self.alias_manager.init_aliases()
1154
1154
1155 # Flush the private list of module references kept for script
1155 # Flush the private list of module references kept for script
1156 # execution protection
1156 # execution protection
1157 self.clear_main_mod_cache()
1157 self.clear_main_mod_cache()
1158
1158
1159 # Clear out the namespace from the last %run
1159 # Clear out the namespace from the last %run
1160 self.new_main_mod()
1160 self.new_main_mod()
1161
1161
1162 def del_var(self, varname, by_name=False):
1162 def del_var(self, varname, by_name=False):
1163 """Delete a variable from the various namespaces, so that, as
1163 """Delete a variable from the various namespaces, so that, as
1164 far as possible, we're not keeping any hidden references to it.
1164 far as possible, we're not keeping any hidden references to it.
1165
1165
1166 Parameters
1166 Parameters
1167 ----------
1167 ----------
1168 varname : str
1168 varname : str
1169 The name of the variable to delete.
1169 The name of the variable to delete.
1170 by_name : bool
1170 by_name : bool
1171 If True, delete variables with the given name in each
1171 If True, delete variables with the given name in each
1172 namespace. If False (default), find the variable in the user
1172 namespace. If False (default), find the variable in the user
1173 namespace, and delete references to it.
1173 namespace, and delete references to it.
1174 """
1174 """
1175 if varname in ('__builtin__', '__builtins__'):
1175 if varname in ('__builtin__', '__builtins__'):
1176 raise ValueError("Refusing to delete %s" % varname)
1176 raise ValueError("Refusing to delete %s" % varname)
1177
1177
1178 ns_refs = self.all_ns_refs
1178 ns_refs = self.all_ns_refs
1179
1179
1180 if by_name: # Delete by name
1180 if by_name: # Delete by name
1181 for ns in ns_refs:
1181 for ns in ns_refs:
1182 try:
1182 try:
1183 del ns[varname]
1183 del ns[varname]
1184 except KeyError:
1184 except KeyError:
1185 pass
1185 pass
1186 else: # Delete by object
1186 else: # Delete by object
1187 try:
1187 try:
1188 obj = self.user_ns[varname]
1188 obj = self.user_ns[varname]
1189 except KeyError:
1189 except KeyError:
1190 raise NameError("name '%s' is not defined" % varname)
1190 raise NameError("name '%s' is not defined" % varname)
1191 # Also check in output history
1191 # Also check in output history
1192 ns_refs.append(self.history_manager.output_hist)
1192 ns_refs.append(self.history_manager.output_hist)
1193 for ns in ns_refs:
1193 for ns in ns_refs:
1194 to_delete = [n for n, o in ns.iteritems() if o is obj]
1194 to_delete = [n for n, o in ns.iteritems() if o is obj]
1195 for name in to_delete:
1195 for name in to_delete:
1196 del ns[name]
1196 del ns[name]
1197
1197
1198 # displayhook keeps extra references, but not in a dictionary
1198 # displayhook keeps extra references, but not in a dictionary
1199 for name in ('_', '__', '___'):
1199 for name in ('_', '__', '___'):
1200 if getattr(self.displayhook, name) is obj:
1200 if getattr(self.displayhook, name) is obj:
1201 setattr(self.displayhook, name, None)
1201 setattr(self.displayhook, name, None)
1202
1202
1203 def reset_selective(self, regex=None):
1203 def reset_selective(self, regex=None):
1204 """Clear selective variables from internal namespaces based on a
1204 """Clear selective variables from internal namespaces based on a
1205 specified regular expression.
1205 specified regular expression.
1206
1206
1207 Parameters
1207 Parameters
1208 ----------
1208 ----------
1209 regex : string or compiled pattern, optional
1209 regex : string or compiled pattern, optional
1210 A regular expression pattern that will be used in searching
1210 A regular expression pattern that will be used in searching
1211 variable names in the users namespaces.
1211 variable names in the users namespaces.
1212 """
1212 """
1213 if regex is not None:
1213 if regex is not None:
1214 try:
1214 try:
1215 m = re.compile(regex)
1215 m = re.compile(regex)
1216 except TypeError:
1216 except TypeError:
1217 raise TypeError('regex must be a string or compiled pattern')
1217 raise TypeError('regex must be a string or compiled pattern')
1218 # Search for keys in each namespace that match the given regex
1218 # Search for keys in each namespace that match the given regex
1219 # If a match is found, delete the key/value pair.
1219 # If a match is found, delete the key/value pair.
1220 for ns in self.all_ns_refs:
1220 for ns in self.all_ns_refs:
1221 for var in ns:
1221 for var in ns:
1222 if m.search(var):
1222 if m.search(var):
1223 del ns[var]
1223 del ns[var]
1224
1224
1225 def push(self, variables, interactive=True):
1225 def push(self, variables, interactive=True):
1226 """Inject a group of variables into the IPython user namespace.
1226 """Inject a group of variables into the IPython user namespace.
1227
1227
1228 Parameters
1228 Parameters
1229 ----------
1229 ----------
1230 variables : dict, str or list/tuple of str
1230 variables : dict, str or list/tuple of str
1231 The variables to inject into the user's namespace. If a dict, a
1231 The variables to inject into the user's namespace. If a dict, a
1232 simple update is done. If a str, the string is assumed to have
1232 simple update is done. If a str, the string is assumed to have
1233 variable names separated by spaces. A list/tuple of str can also
1233 variable names separated by spaces. A list/tuple of str can also
1234 be used to give the variable names. If just the variable names are
1234 be used to give the variable names. If just the variable names are
1235 give (list/tuple/str) then the variable values looked up in the
1235 give (list/tuple/str) then the variable values looked up in the
1236 callers frame.
1236 callers frame.
1237 interactive : bool
1237 interactive : bool
1238 If True (default), the variables will be listed with the ``who``
1238 If True (default), the variables will be listed with the ``who``
1239 magic.
1239 magic.
1240 """
1240 """
1241 vdict = None
1241 vdict = None
1242
1242
1243 # We need a dict of name/value pairs to do namespace updates.
1243 # We need a dict of name/value pairs to do namespace updates.
1244 if isinstance(variables, dict):
1244 if isinstance(variables, dict):
1245 vdict = variables
1245 vdict = variables
1246 elif isinstance(variables, (basestring, list, tuple)):
1246 elif isinstance(variables, (basestring, list, tuple)):
1247 if isinstance(variables, basestring):
1247 if isinstance(variables, basestring):
1248 vlist = variables.split()
1248 vlist = variables.split()
1249 else:
1249 else:
1250 vlist = variables
1250 vlist = variables
1251 vdict = {}
1251 vdict = {}
1252 cf = sys._getframe(1)
1252 cf = sys._getframe(1)
1253 for name in vlist:
1253 for name in vlist:
1254 try:
1254 try:
1255 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1255 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1256 except:
1256 except:
1257 print ('Could not get variable %s from %s' %
1257 print ('Could not get variable %s from %s' %
1258 (name,cf.f_code.co_name))
1258 (name,cf.f_code.co_name))
1259 else:
1259 else:
1260 raise ValueError('variables must be a dict/str/list/tuple')
1260 raise ValueError('variables must be a dict/str/list/tuple')
1261
1261
1262 # Propagate variables to user namespace
1262 # Propagate variables to user namespace
1263 self.user_ns.update(vdict)
1263 self.user_ns.update(vdict)
1264
1264
1265 # And configure interactive visibility
1265 # And configure interactive visibility
1266 user_ns_hidden = self.user_ns_hidden
1266 user_ns_hidden = self.user_ns_hidden
1267 if interactive:
1267 if interactive:
1268 user_ns_hidden.difference_update(vdict)
1268 user_ns_hidden.difference_update(vdict)
1269 else:
1269 else:
1270 user_ns_hidden.update(vdict)
1270 user_ns_hidden.update(vdict)
1271
1271
1272 def drop_by_id(self, variables):
1272 def drop_by_id(self, variables):
1273 """Remove a dict of variables from the user namespace, if they are the
1273 """Remove a dict of variables from the user namespace, if they are the
1274 same as the values in the dictionary.
1274 same as the values in the dictionary.
1275
1275
1276 This is intended for use by extensions: variables that they've added can
1276 This is intended for use by extensions: variables that they've added can
1277 be taken back out if they are unloaded, without removing any that the
1277 be taken back out if they are unloaded, without removing any that the
1278 user has overwritten.
1278 user has overwritten.
1279
1279
1280 Parameters
1280 Parameters
1281 ----------
1281 ----------
1282 variables : dict
1282 variables : dict
1283 A dictionary mapping object names (as strings) to the objects.
1283 A dictionary mapping object names (as strings) to the objects.
1284 """
1284 """
1285 for name, obj in variables.iteritems():
1285 for name, obj in variables.iteritems():
1286 if name in self.user_ns and self.user_ns[name] is obj:
1286 if name in self.user_ns and self.user_ns[name] is obj:
1287 del self.user_ns[name]
1287 del self.user_ns[name]
1288 self.user_ns_hidden.discard(name)
1288 self.user_ns_hidden.discard(name)
1289
1289
1290 #-------------------------------------------------------------------------
1290 #-------------------------------------------------------------------------
1291 # Things related to object introspection
1291 # Things related to object introspection
1292 #-------------------------------------------------------------------------
1292 #-------------------------------------------------------------------------
1293
1293
1294 def _ofind(self, oname, namespaces=None):
1294 def _ofind(self, oname, namespaces=None):
1295 """Find an object in the available namespaces.
1295 """Find an object in the available namespaces.
1296
1296
1297 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1297 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1298
1298
1299 Has special code to detect magic functions.
1299 Has special code to detect magic functions.
1300 """
1300 """
1301 oname = oname.strip()
1301 oname = oname.strip()
1302 #print '1- oname: <%r>' % oname # dbg
1302 #print '1- oname: <%r>' % oname # dbg
1303 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1303 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1304 return dict(found=False)
1304 return dict(found=False)
1305
1305
1306 alias_ns = None
1306 alias_ns = None
1307 if namespaces is None:
1307 if namespaces is None:
1308 # Namespaces to search in:
1308 # Namespaces to search in:
1309 # Put them in a list. The order is important so that we
1309 # Put them in a list. The order is important so that we
1310 # find things in the same order that Python finds them.
1310 # find things in the same order that Python finds them.
1311 namespaces = [ ('Interactive', self.user_ns),
1311 namespaces = [ ('Interactive', self.user_ns),
1312 ('Interactive (global)', self.user_global_ns),
1312 ('Interactive (global)', self.user_global_ns),
1313 ('Python builtin', builtin_mod.__dict__),
1313 ('Python builtin', builtin_mod.__dict__),
1314 ('Alias', self.alias_manager.alias_table),
1314 ('Alias', self.alias_manager.alias_table),
1315 ]
1315 ]
1316 alias_ns = self.alias_manager.alias_table
1316 alias_ns = self.alias_manager.alias_table
1317
1317
1318 # initialize results to 'null'
1318 # initialize results to 'null'
1319 found = False; obj = None; ospace = None; ds = None;
1319 found = False; obj = None; ospace = None; ds = None;
1320 ismagic = False; isalias = False; parent = None
1320 ismagic = False; isalias = False; parent = None
1321
1321
1322 # We need to special-case 'print', which as of python2.6 registers as a
1322 # We need to special-case 'print', which as of python2.6 registers as a
1323 # function but should only be treated as one if print_function was
1323 # function but should only be treated as one if print_function was
1324 # loaded with a future import. In this case, just bail.
1324 # loaded with a future import. In this case, just bail.
1325 if (oname == 'print' and not py3compat.PY3 and not \
1325 if (oname == 'print' and not py3compat.PY3 and not \
1326 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1326 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1327 return {'found':found, 'obj':obj, 'namespace':ospace,
1327 return {'found':found, 'obj':obj, 'namespace':ospace,
1328 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1328 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1329
1329
1330 # Look for the given name by splitting it in parts. If the head is
1330 # Look for the given name by splitting it in parts. If the head is
1331 # found, then we look for all the remaining parts as members, and only
1331 # found, then we look for all the remaining parts as members, and only
1332 # declare success if we can find them all.
1332 # declare success if we can find them all.
1333 oname_parts = oname.split('.')
1333 oname_parts = oname.split('.')
1334 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1334 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1335 for nsname,ns in namespaces:
1335 for nsname,ns in namespaces:
1336 try:
1336 try:
1337 obj = ns[oname_head]
1337 obj = ns[oname_head]
1338 except KeyError:
1338 except KeyError:
1339 continue
1339 continue
1340 else:
1340 else:
1341 #print 'oname_rest:', oname_rest # dbg
1341 #print 'oname_rest:', oname_rest # dbg
1342 for part in oname_rest:
1342 for part in oname_rest:
1343 try:
1343 try:
1344 parent = obj
1344 parent = obj
1345 obj = getattr(obj,part)
1345 obj = getattr(obj,part)
1346 except:
1346 except:
1347 # Blanket except b/c some badly implemented objects
1347 # Blanket except b/c some badly implemented objects
1348 # allow __getattr__ to raise exceptions other than
1348 # allow __getattr__ to raise exceptions other than
1349 # AttributeError, which then crashes IPython.
1349 # AttributeError, which then crashes IPython.
1350 break
1350 break
1351 else:
1351 else:
1352 # If we finish the for loop (no break), we got all members
1352 # If we finish the for loop (no break), we got all members
1353 found = True
1353 found = True
1354 ospace = nsname
1354 ospace = nsname
1355 if ns == alias_ns:
1355 if ns == alias_ns:
1356 isalias = True
1356 isalias = True
1357 break # namespace loop
1357 break # namespace loop
1358
1358
1359 # Try to see if it's magic
1359 # Try to see if it's magic
1360 if not found:
1360 if not found:
1361 if oname.startswith(ESC_MAGIC):
1361 if oname.startswith(ESC_MAGIC):
1362 oname = oname[1:]
1362 oname = oname[1:]
1363 obj = getattr(self,'magic_'+oname,None)
1363 obj = getattr(self,'magic_'+oname,None)
1364 if obj is not None:
1364 if obj is not None:
1365 found = True
1365 found = True
1366 ospace = 'IPython internal'
1366 ospace = 'IPython internal'
1367 ismagic = True
1367 ismagic = True
1368
1368
1369 # Last try: special-case some literals like '', [], {}, etc:
1369 # Last try: special-case some literals like '', [], {}, etc:
1370 if not found and oname_head in ["''",'""','[]','{}','()']:
1370 if not found and oname_head in ["''",'""','[]','{}','()']:
1371 obj = eval(oname_head)
1371 obj = eval(oname_head)
1372 found = True
1372 found = True
1373 ospace = 'Interactive'
1373 ospace = 'Interactive'
1374
1374
1375 return {'found':found, 'obj':obj, 'namespace':ospace,
1375 return {'found':found, 'obj':obj, 'namespace':ospace,
1376 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1376 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1377
1377
1378 def _ofind_property(self, oname, info):
1378 def _ofind_property(self, oname, info):
1379 """Second part of object finding, to look for property details."""
1379 """Second part of object finding, to look for property details."""
1380 if info.found:
1380 if info.found:
1381 # Get the docstring of the class property if it exists.
1381 # Get the docstring of the class property if it exists.
1382 path = oname.split('.')
1382 path = oname.split('.')
1383 root = '.'.join(path[:-1])
1383 root = '.'.join(path[:-1])
1384 if info.parent is not None:
1384 if info.parent is not None:
1385 try:
1385 try:
1386 target = getattr(info.parent, '__class__')
1386 target = getattr(info.parent, '__class__')
1387 # The object belongs to a class instance.
1387 # The object belongs to a class instance.
1388 try:
1388 try:
1389 target = getattr(target, path[-1])
1389 target = getattr(target, path[-1])
1390 # The class defines the object.
1390 # The class defines the object.
1391 if isinstance(target, property):
1391 if isinstance(target, property):
1392 oname = root + '.__class__.' + path[-1]
1392 oname = root + '.__class__.' + path[-1]
1393 info = Struct(self._ofind(oname))
1393 info = Struct(self._ofind(oname))
1394 except AttributeError: pass
1394 except AttributeError: pass
1395 except AttributeError: pass
1395 except AttributeError: pass
1396
1396
1397 # We return either the new info or the unmodified input if the object
1397 # We return either the new info or the unmodified input if the object
1398 # hadn't been found
1398 # hadn't been found
1399 return info
1399 return info
1400
1400
1401 def _object_find(self, oname, namespaces=None):
1401 def _object_find(self, oname, namespaces=None):
1402 """Find an object and return a struct with info about it."""
1402 """Find an object and return a struct with info about it."""
1403 inf = Struct(self._ofind(oname, namespaces))
1403 inf = Struct(self._ofind(oname, namespaces))
1404 return Struct(self._ofind_property(oname, inf))
1404 return Struct(self._ofind_property(oname, inf))
1405
1405
1406 def _inspect(self, meth, oname, namespaces=None, **kw):
1406 def _inspect(self, meth, oname, namespaces=None, **kw):
1407 """Generic interface to the inspector system.
1407 """Generic interface to the inspector system.
1408
1408
1409 This function is meant to be called by pdef, pdoc & friends."""
1409 This function is meant to be called by pdef, pdoc & friends."""
1410 info = self._object_find(oname)
1410 info = self._object_find(oname)
1411 if info.found:
1411 if info.found:
1412 pmethod = getattr(self.inspector, meth)
1412 pmethod = getattr(self.inspector, meth)
1413 formatter = format_screen if info.ismagic else None
1413 formatter = format_screen if info.ismagic else None
1414 if meth == 'pdoc':
1414 if meth == 'pdoc':
1415 pmethod(info.obj, oname, formatter)
1415 pmethod(info.obj, oname, formatter)
1416 elif meth == 'pinfo':
1416 elif meth == 'pinfo':
1417 pmethod(info.obj, oname, formatter, info, **kw)
1417 pmethod(info.obj, oname, formatter, info, **kw)
1418 else:
1418 else:
1419 pmethod(info.obj, oname)
1419 pmethod(info.obj, oname)
1420 else:
1420 else:
1421 print 'Object `%s` not found.' % oname
1421 print 'Object `%s` not found.' % oname
1422 return 'not found' # so callers can take other action
1422 return 'not found' # so callers can take other action
1423
1423
1424 def object_inspect(self, oname):
1424 def object_inspect(self, oname):
1425 with self.builtin_trap:
1425 with self.builtin_trap:
1426 info = self._object_find(oname)
1426 info = self._object_find(oname)
1427 if info.found:
1427 if info.found:
1428 return self.inspector.info(info.obj, oname, info=info)
1428 return self.inspector.info(info.obj, oname, info=info)
1429 else:
1429 else:
1430 return oinspect.object_info(name=oname, found=False)
1430 return oinspect.object_info(name=oname, found=False)
1431
1431
1432 #-------------------------------------------------------------------------
1432 #-------------------------------------------------------------------------
1433 # Things related to history management
1433 # Things related to history management
1434 #-------------------------------------------------------------------------
1434 #-------------------------------------------------------------------------
1435
1435
1436 def init_history(self):
1436 def init_history(self):
1437 """Sets up the command history, and starts regular autosaves."""
1437 """Sets up the command history, and starts regular autosaves."""
1438 self.history_manager = HistoryManager(shell=self, config=self.config)
1438 self.history_manager = HistoryManager(shell=self, config=self.config)
1439 self.configurables.append(self.history_manager)
1439 self.configurables.append(self.history_manager)
1440
1440
1441 #-------------------------------------------------------------------------
1441 #-------------------------------------------------------------------------
1442 # Things related to exception handling and tracebacks (not debugging)
1442 # Things related to exception handling and tracebacks (not debugging)
1443 #-------------------------------------------------------------------------
1443 #-------------------------------------------------------------------------
1444
1444
1445 def init_traceback_handlers(self, custom_exceptions):
1445 def init_traceback_handlers(self, custom_exceptions):
1446 # Syntax error handler.
1446 # Syntax error handler.
1447 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1447 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1448
1448
1449 # The interactive one is initialized with an offset, meaning we always
1449 # The interactive one is initialized with an offset, meaning we always
1450 # want to remove the topmost item in the traceback, which is our own
1450 # want to remove the topmost item in the traceback, which is our own
1451 # internal code. Valid modes: ['Plain','Context','Verbose']
1451 # internal code. Valid modes: ['Plain','Context','Verbose']
1452 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1452 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1453 color_scheme='NoColor',
1453 color_scheme='NoColor',
1454 tb_offset = 1,
1454 tb_offset = 1,
1455 check_cache=self.compile.check_cache)
1455 check_cache=self.compile.check_cache)
1456
1456
1457 # The instance will store a pointer to the system-wide exception hook,
1457 # The instance will store a pointer to the system-wide exception hook,
1458 # so that runtime code (such as magics) can access it. This is because
1458 # so that runtime code (such as magics) can access it. This is because
1459 # during the read-eval loop, it may get temporarily overwritten.
1459 # during the read-eval loop, it may get temporarily overwritten.
1460 self.sys_excepthook = sys.excepthook
1460 self.sys_excepthook = sys.excepthook
1461
1461
1462 # and add any custom exception handlers the user may have specified
1462 # and add any custom exception handlers the user may have specified
1463 self.set_custom_exc(*custom_exceptions)
1463 self.set_custom_exc(*custom_exceptions)
1464
1464
1465 # Set the exception mode
1465 # Set the exception mode
1466 self.InteractiveTB.set_mode(mode=self.xmode)
1466 self.InteractiveTB.set_mode(mode=self.xmode)
1467
1467
1468 def set_custom_exc(self, exc_tuple, handler):
1468 def set_custom_exc(self, exc_tuple, handler):
1469 """set_custom_exc(exc_tuple,handler)
1469 """set_custom_exc(exc_tuple,handler)
1470
1470
1471 Set a custom exception handler, which will be called if any of the
1471 Set a custom exception handler, which will be called if any of the
1472 exceptions in exc_tuple occur in the mainloop (specifically, in the
1472 exceptions in exc_tuple occur in the mainloop (specifically, in the
1473 run_code() method).
1473 run_code() method).
1474
1474
1475 Parameters
1475 Parameters
1476 ----------
1476 ----------
1477
1477
1478 exc_tuple : tuple of exception classes
1478 exc_tuple : tuple of exception classes
1479 A *tuple* of exception classes, for which to call the defined
1479 A *tuple* of exception classes, for which to call the defined
1480 handler. It is very important that you use a tuple, and NOT A
1480 handler. It is very important that you use a tuple, and NOT A
1481 LIST here, because of the way Python's except statement works. If
1481 LIST here, because of the way Python's except statement works. If
1482 you only want to trap a single exception, use a singleton tuple::
1482 you only want to trap a single exception, use a singleton tuple::
1483
1483
1484 exc_tuple == (MyCustomException,)
1484 exc_tuple == (MyCustomException,)
1485
1485
1486 handler : callable
1486 handler : callable
1487 handler must have the following signature::
1487 handler must have the following signature::
1488
1488
1489 def my_handler(self, etype, value, tb, tb_offset=None):
1489 def my_handler(self, etype, value, tb, tb_offset=None):
1490 ...
1490 ...
1491 return structured_traceback
1491 return structured_traceback
1492
1492
1493 Your handler must return a structured traceback (a list of strings),
1493 Your handler must return a structured traceback (a list of strings),
1494 or None.
1494 or None.
1495
1495
1496 This will be made into an instance method (via types.MethodType)
1496 This will be made into an instance method (via types.MethodType)
1497 of IPython itself, and it will be called if any of the exceptions
1497 of IPython itself, and it will be called if any of the exceptions
1498 listed in the exc_tuple are caught. If the handler is None, an
1498 listed in the exc_tuple are caught. If the handler is None, an
1499 internal basic one is used, which just prints basic info.
1499 internal basic one is used, which just prints basic info.
1500
1500
1501 To protect IPython from crashes, if your handler ever raises an
1501 To protect IPython from crashes, if your handler ever raises an
1502 exception or returns an invalid result, it will be immediately
1502 exception or returns an invalid result, it will be immediately
1503 disabled.
1503 disabled.
1504
1504
1505 WARNING: by putting in your own exception handler into IPython's main
1505 WARNING: by putting in your own exception handler into IPython's main
1506 execution loop, you run a very good chance of nasty crashes. This
1506 execution loop, you run a very good chance of nasty crashes. This
1507 facility should only be used if you really know what you are doing."""
1507 facility should only be used if you really know what you are doing."""
1508
1508
1509 assert type(exc_tuple)==type(()) , \
1509 assert type(exc_tuple)==type(()) , \
1510 "The custom exceptions must be given AS A TUPLE."
1510 "The custom exceptions must be given AS A TUPLE."
1511
1511
1512 def dummy_handler(self,etype,value,tb,tb_offset=None):
1512 def dummy_handler(self,etype,value,tb,tb_offset=None):
1513 print '*** Simple custom exception handler ***'
1513 print '*** Simple custom exception handler ***'
1514 print 'Exception type :',etype
1514 print 'Exception type :',etype
1515 print 'Exception value:',value
1515 print 'Exception value:',value
1516 print 'Traceback :',tb
1516 print 'Traceback :',tb
1517 #print 'Source code :','\n'.join(self.buffer)
1517 #print 'Source code :','\n'.join(self.buffer)
1518
1518
1519 def validate_stb(stb):
1519 def validate_stb(stb):
1520 """validate structured traceback return type
1520 """validate structured traceback return type
1521
1521
1522 return type of CustomTB *should* be a list of strings, but allow
1522 return type of CustomTB *should* be a list of strings, but allow
1523 single strings or None, which are harmless.
1523 single strings or None, which are harmless.
1524
1524
1525 This function will *always* return a list of strings,
1525 This function will *always* return a list of strings,
1526 and will raise a TypeError if stb is inappropriate.
1526 and will raise a TypeError if stb is inappropriate.
1527 """
1527 """
1528 msg = "CustomTB must return list of strings, not %r" % stb
1528 msg = "CustomTB must return list of strings, not %r" % stb
1529 if stb is None:
1529 if stb is None:
1530 return []
1530 return []
1531 elif isinstance(stb, basestring):
1531 elif isinstance(stb, basestring):
1532 return [stb]
1532 return [stb]
1533 elif not isinstance(stb, list):
1533 elif not isinstance(stb, list):
1534 raise TypeError(msg)
1534 raise TypeError(msg)
1535 # it's a list
1535 # it's a list
1536 for line in stb:
1536 for line in stb:
1537 # check every element
1537 # check every element
1538 if not isinstance(line, basestring):
1538 if not isinstance(line, basestring):
1539 raise TypeError(msg)
1539 raise TypeError(msg)
1540 return stb
1540 return stb
1541
1541
1542 if handler is None:
1542 if handler is None:
1543 wrapped = dummy_handler
1543 wrapped = dummy_handler
1544 else:
1544 else:
1545 def wrapped(self,etype,value,tb,tb_offset=None):
1545 def wrapped(self,etype,value,tb,tb_offset=None):
1546 """wrap CustomTB handler, to protect IPython from user code
1546 """wrap CustomTB handler, to protect IPython from user code
1547
1547
1548 This makes it harder (but not impossible) for custom exception
1548 This makes it harder (but not impossible) for custom exception
1549 handlers to crash IPython.
1549 handlers to crash IPython.
1550 """
1550 """
1551 try:
1551 try:
1552 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1552 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1553 return validate_stb(stb)
1553 return validate_stb(stb)
1554 except:
1554 except:
1555 # clear custom handler immediately
1555 # clear custom handler immediately
1556 self.set_custom_exc((), None)
1556 self.set_custom_exc((), None)
1557 print >> io.stderr, "Custom TB Handler failed, unregistering"
1557 print >> io.stderr, "Custom TB Handler failed, unregistering"
1558 # show the exception in handler first
1558 # show the exception in handler first
1559 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1559 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1560 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1560 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1561 print >> io.stdout, "The original exception:"
1561 print >> io.stdout, "The original exception:"
1562 stb = self.InteractiveTB.structured_traceback(
1562 stb = self.InteractiveTB.structured_traceback(
1563 (etype,value,tb), tb_offset=tb_offset
1563 (etype,value,tb), tb_offset=tb_offset
1564 )
1564 )
1565 return stb
1565 return stb
1566
1566
1567 self.CustomTB = types.MethodType(wrapped,self)
1567 self.CustomTB = types.MethodType(wrapped,self)
1568 self.custom_exceptions = exc_tuple
1568 self.custom_exceptions = exc_tuple
1569
1569
1570 def excepthook(self, etype, value, tb):
1570 def excepthook(self, etype, value, tb):
1571 """One more defense for GUI apps that call sys.excepthook.
1571 """One more defense for GUI apps that call sys.excepthook.
1572
1572
1573 GUI frameworks like wxPython trap exceptions and call
1573 GUI frameworks like wxPython trap exceptions and call
1574 sys.excepthook themselves. I guess this is a feature that
1574 sys.excepthook themselves. I guess this is a feature that
1575 enables them to keep running after exceptions that would
1575 enables them to keep running after exceptions that would
1576 otherwise kill their mainloop. This is a bother for IPython
1576 otherwise kill their mainloop. This is a bother for IPython
1577 which excepts to catch all of the program exceptions with a try:
1577 which excepts to catch all of the program exceptions with a try:
1578 except: statement.
1578 except: statement.
1579
1579
1580 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1580 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1581 any app directly invokes sys.excepthook, it will look to the user like
1581 any app directly invokes sys.excepthook, it will look to the user like
1582 IPython crashed. In order to work around this, we can disable the
1582 IPython crashed. In order to work around this, we can disable the
1583 CrashHandler and replace it with this excepthook instead, which prints a
1583 CrashHandler and replace it with this excepthook instead, which prints a
1584 regular traceback using our InteractiveTB. In this fashion, apps which
1584 regular traceback using our InteractiveTB. In this fashion, apps which
1585 call sys.excepthook will generate a regular-looking exception from
1585 call sys.excepthook will generate a regular-looking exception from
1586 IPython, and the CrashHandler will only be triggered by real IPython
1586 IPython, and the CrashHandler will only be triggered by real IPython
1587 crashes.
1587 crashes.
1588
1588
1589 This hook should be used sparingly, only in places which are not likely
1589 This hook should be used sparingly, only in places which are not likely
1590 to be true IPython errors.
1590 to be true IPython errors.
1591 """
1591 """
1592 self.showtraceback((etype,value,tb),tb_offset=0)
1592 self.showtraceback((etype,value,tb),tb_offset=0)
1593
1593
1594 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1594 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1595 exception_only=False):
1595 exception_only=False):
1596 """Display the exception that just occurred.
1596 """Display the exception that just occurred.
1597
1597
1598 If nothing is known about the exception, this is the method which
1598 If nothing is known about the exception, this is the method which
1599 should be used throughout the code for presenting user tracebacks,
1599 should be used throughout the code for presenting user tracebacks,
1600 rather than directly invoking the InteractiveTB object.
1600 rather than directly invoking the InteractiveTB object.
1601
1601
1602 A specific showsyntaxerror() also exists, but this method can take
1602 A specific showsyntaxerror() also exists, but this method can take
1603 care of calling it if needed, so unless you are explicitly catching a
1603 care of calling it if needed, so unless you are explicitly catching a
1604 SyntaxError exception, don't try to analyze the stack manually and
1604 SyntaxError exception, don't try to analyze the stack manually and
1605 simply call this method."""
1605 simply call this method."""
1606
1606
1607 try:
1607 try:
1608 if exc_tuple is None:
1608 if exc_tuple is None:
1609 etype, value, tb = sys.exc_info()
1609 etype, value, tb = sys.exc_info()
1610 else:
1610 else:
1611 etype, value, tb = exc_tuple
1611 etype, value, tb = exc_tuple
1612
1612
1613 if etype is None:
1613 if etype is None:
1614 if hasattr(sys, 'last_type'):
1614 if hasattr(sys, 'last_type'):
1615 etype, value, tb = sys.last_type, sys.last_value, \
1615 etype, value, tb = sys.last_type, sys.last_value, \
1616 sys.last_traceback
1616 sys.last_traceback
1617 else:
1617 else:
1618 self.write_err('No traceback available to show.\n')
1618 self.write_err('No traceback available to show.\n')
1619 return
1619 return
1620
1620
1621 if etype is SyntaxError:
1621 if etype is SyntaxError:
1622 # Though this won't be called by syntax errors in the input
1622 # Though this won't be called by syntax errors in the input
1623 # line, there may be SyntaxError cases with imported code.
1623 # line, there may be SyntaxError cases with imported code.
1624 self.showsyntaxerror(filename)
1624 self.showsyntaxerror(filename)
1625 elif etype is UsageError:
1625 elif etype is UsageError:
1626 self.write_err("UsageError: %s" % value)
1626 self.write_err("UsageError: %s" % value)
1627 else:
1627 else:
1628 # WARNING: these variables are somewhat deprecated and not
1628 # WARNING: these variables are somewhat deprecated and not
1629 # necessarily safe to use in a threaded environment, but tools
1629 # necessarily safe to use in a threaded environment, but tools
1630 # like pdb depend on their existence, so let's set them. If we
1630 # like pdb depend on their existence, so let's set them. If we
1631 # find problems in the field, we'll need to revisit their use.
1631 # find problems in the field, we'll need to revisit their use.
1632 sys.last_type = etype
1632 sys.last_type = etype
1633 sys.last_value = value
1633 sys.last_value = value
1634 sys.last_traceback = tb
1634 sys.last_traceback = tb
1635 if etype in self.custom_exceptions:
1635 if etype in self.custom_exceptions:
1636 stb = self.CustomTB(etype, value, tb, tb_offset)
1636 stb = self.CustomTB(etype, value, tb, tb_offset)
1637 else:
1637 else:
1638 if exception_only:
1638 if exception_only:
1639 stb = ['An exception has occurred, use %tb to see '
1639 stb = ['An exception has occurred, use %tb to see '
1640 'the full traceback.\n']
1640 'the full traceback.\n']
1641 stb.extend(self.InteractiveTB.get_exception_only(etype,
1641 stb.extend(self.InteractiveTB.get_exception_only(etype,
1642 value))
1642 value))
1643 else:
1643 else:
1644 stb = self.InteractiveTB.structured_traceback(etype,
1644 stb = self.InteractiveTB.structured_traceback(etype,
1645 value, tb, tb_offset=tb_offset)
1645 value, tb, tb_offset=tb_offset)
1646
1646
1647 self._showtraceback(etype, value, stb)
1647 self._showtraceback(etype, value, stb)
1648 if self.call_pdb:
1648 if self.call_pdb:
1649 # drop into debugger
1649 # drop into debugger
1650 self.debugger(force=True)
1650 self.debugger(force=True)
1651 return
1651 return
1652
1652
1653 # Actually show the traceback
1653 # Actually show the traceback
1654 self._showtraceback(etype, value, stb)
1654 self._showtraceback(etype, value, stb)
1655
1655
1656 except KeyboardInterrupt:
1656 except KeyboardInterrupt:
1657 self.write_err("\nKeyboardInterrupt\n")
1657 self.write_err("\nKeyboardInterrupt\n")
1658
1658
1659 def _showtraceback(self, etype, evalue, stb):
1659 def _showtraceback(self, etype, evalue, stb):
1660 """Actually show a traceback.
1660 """Actually show a traceback.
1661
1661
1662 Subclasses may override this method to put the traceback on a different
1662 Subclasses may override this method to put the traceback on a different
1663 place, like a side channel.
1663 place, like a side channel.
1664 """
1664 """
1665 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1665 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1666
1666
1667 def showsyntaxerror(self, filename=None):
1667 def showsyntaxerror(self, filename=None):
1668 """Display the syntax error that just occurred.
1668 """Display the syntax error that just occurred.
1669
1669
1670 This doesn't display a stack trace because there isn't one.
1670 This doesn't display a stack trace because there isn't one.
1671
1671
1672 If a filename is given, it is stuffed in the exception instead
1672 If a filename is given, it is stuffed in the exception instead
1673 of what was there before (because Python's parser always uses
1673 of what was there before (because Python's parser always uses
1674 "<string>" when reading from a string).
1674 "<string>" when reading from a string).
1675 """
1675 """
1676 etype, value, last_traceback = sys.exc_info()
1676 etype, value, last_traceback = sys.exc_info()
1677
1677
1678 # See note about these variables in showtraceback() above
1678 # See note about these variables in showtraceback() above
1679 sys.last_type = etype
1679 sys.last_type = etype
1680 sys.last_value = value
1680 sys.last_value = value
1681 sys.last_traceback = last_traceback
1681 sys.last_traceback = last_traceback
1682
1682
1683 if filename and etype is SyntaxError:
1683 if filename and etype is SyntaxError:
1684 try:
1684 try:
1685 value.filename = filename
1685 value.filename = filename
1686 except:
1686 except:
1687 # Not the format we expect; leave it alone
1687 # Not the format we expect; leave it alone
1688 pass
1688 pass
1689
1689
1690 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1690 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1691 self._showtraceback(etype, value, stb)
1691 self._showtraceback(etype, value, stb)
1692
1692
1693 # This is overridden in TerminalInteractiveShell to show a message about
1693 # This is overridden in TerminalInteractiveShell to show a message about
1694 # the %paste magic.
1694 # the %paste magic.
1695 def showindentationerror(self):
1695 def showindentationerror(self):
1696 """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
1697 at the prompt.
1697 at the prompt.
1698
1698
1699 This is overridden in TerminalInteractiveShell to show a message about
1699 This is overridden in TerminalInteractiveShell to show a message about
1700 the %paste magic."""
1700 the %paste magic."""
1701 self.showsyntaxerror()
1701 self.showsyntaxerror()
1702
1702
1703 #-------------------------------------------------------------------------
1703 #-------------------------------------------------------------------------
1704 # Things related to readline
1704 # Things related to readline
1705 #-------------------------------------------------------------------------
1705 #-------------------------------------------------------------------------
1706
1706
1707 def init_readline(self):
1707 def init_readline(self):
1708 """Command history completion/saving/reloading."""
1708 """Command history completion/saving/reloading."""
1709
1709
1710 if self.readline_use:
1710 if self.readline_use:
1711 import IPython.utils.rlineimpl as readline
1711 import IPython.utils.rlineimpl as readline
1712
1712
1713 self.rl_next_input = None
1713 self.rl_next_input = None
1714 self.rl_do_indent = False
1714 self.rl_do_indent = False
1715
1715
1716 if not self.readline_use or not readline.have_readline:
1716 if not self.readline_use or not readline.have_readline:
1717 self.has_readline = False
1717 self.has_readline = False
1718 self.readline = None
1718 self.readline = None
1719 # 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
1720 self.readline_no_record = no_op_context
1720 self.readline_no_record = no_op_context
1721 self.set_readline_completer = no_op
1721 self.set_readline_completer = no_op
1722 self.set_custom_completer = no_op
1722 self.set_custom_completer = no_op
1723 self.set_completer_frame = no_op
1723 self.set_completer_frame = no_op
1724 if self.readline_use:
1724 if self.readline_use:
1725 warn('Readline services not available or not loaded.')
1725 warn('Readline services not available or not loaded.')
1726 else:
1726 else:
1727 self.has_readline = True
1727 self.has_readline = True
1728 self.readline = readline
1728 self.readline = readline
1729 sys.modules['readline'] = readline
1729 sys.modules['readline'] = readline
1730
1730
1731 # Platform-specific configuration
1731 # Platform-specific configuration
1732 if os.name == 'nt':
1732 if os.name == 'nt':
1733 # FIXME - check with Frederick to see if we can harmonize
1733 # FIXME - check with Frederick to see if we can harmonize
1734 # naming conventions with pyreadline to avoid this
1734 # naming conventions with pyreadline to avoid this
1735 # platform-dependent check
1735 # platform-dependent check
1736 self.readline_startup_hook = readline.set_pre_input_hook
1736 self.readline_startup_hook = readline.set_pre_input_hook
1737 else:
1737 else:
1738 self.readline_startup_hook = readline.set_startup_hook
1738 self.readline_startup_hook = readline.set_startup_hook
1739
1739
1740 # Load user's initrc file (readline config)
1740 # Load user's initrc file (readline config)
1741 # Or if libedit is used, load editrc.
1741 # Or if libedit is used, load editrc.
1742 inputrc_name = os.environ.get('INPUTRC')
1742 inputrc_name = os.environ.get('INPUTRC')
1743 if inputrc_name is None:
1743 if inputrc_name is None:
1744 inputrc_name = '.inputrc'
1744 inputrc_name = '.inputrc'
1745 if readline.uses_libedit:
1745 if readline.uses_libedit:
1746 inputrc_name = '.editrc'
1746 inputrc_name = '.editrc'
1747 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1747 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1748 if os.path.isfile(inputrc_name):
1748 if os.path.isfile(inputrc_name):
1749 try:
1749 try:
1750 readline.read_init_file(inputrc_name)
1750 readline.read_init_file(inputrc_name)
1751 except:
1751 except:
1752 warn('Problems reading readline initialization file <%s>'
1752 warn('Problems reading readline initialization file <%s>'
1753 % inputrc_name)
1753 % inputrc_name)
1754
1754
1755 # Configure readline according to user's prefs
1755 # Configure readline according to user's prefs
1756 # 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
1757 # is being used (as on Leopard) the readline config is
1757 # is being used (as on Leopard) the readline config is
1758 # not run as the syntax for libedit is different.
1758 # not run as the syntax for libedit is different.
1759 if not readline.uses_libedit:
1759 if not readline.uses_libedit:
1760 for rlcommand in self.readline_parse_and_bind:
1760 for rlcommand in self.readline_parse_and_bind:
1761 #print "loading rl:",rlcommand # dbg
1761 #print "loading rl:",rlcommand # dbg
1762 readline.parse_and_bind(rlcommand)
1762 readline.parse_and_bind(rlcommand)
1763
1763
1764 # Remove some chars from the delimiters list. If we encounter
1764 # Remove some chars from the delimiters list. If we encounter
1765 # unicode chars, discard them.
1765 # unicode chars, discard them.
1766 delims = readline.get_completer_delims()
1766 delims = readline.get_completer_delims()
1767 if not py3compat.PY3:
1767 if not py3compat.PY3:
1768 delims = delims.encode("ascii", "ignore")
1768 delims = delims.encode("ascii", "ignore")
1769 for d in self.readline_remove_delims:
1769 for d in self.readline_remove_delims:
1770 delims = delims.replace(d, "")
1770 delims = delims.replace(d, "")
1771 delims = delims.replace(ESC_MAGIC, '')
1771 delims = delims.replace(ESC_MAGIC, '')
1772 readline.set_completer_delims(delims)
1772 readline.set_completer_delims(delims)
1773 # otherwise we end up with a monster history after a while:
1773 # otherwise we end up with a monster history after a while:
1774 readline.set_history_length(self.history_length)
1774 readline.set_history_length(self.history_length)
1775
1775
1776 self.refill_readline_hist()
1776 self.refill_readline_hist()
1777 self.readline_no_record = ReadlineNoRecord(self)
1777 self.readline_no_record = ReadlineNoRecord(self)
1778
1778
1779 # Configure auto-indent for all platforms
1779 # Configure auto-indent for all platforms
1780 self.set_autoindent(self.autoindent)
1780 self.set_autoindent(self.autoindent)
1781
1781
1782 def refill_readline_hist(self):
1782 def refill_readline_hist(self):
1783 # Load the last 1000 lines from history
1783 # Load the last 1000 lines from history
1784 self.readline.clear_history()
1784 self.readline.clear_history()
1785 stdin_encoding = sys.stdin.encoding or "utf-8"
1785 stdin_encoding = sys.stdin.encoding or "utf-8"
1786 last_cell = u""
1786 last_cell = u""
1787 for _, _, cell in self.history_manager.get_tail(1000,
1787 for _, _, cell in self.history_manager.get_tail(1000,
1788 include_latest=True):
1788 include_latest=True):
1789 # Ignore blank lines and consecutive duplicates
1789 # Ignore blank lines and consecutive duplicates
1790 cell = cell.rstrip()
1790 cell = cell.rstrip()
1791 if cell and (cell != last_cell):
1791 if cell and (cell != last_cell):
1792 if self.multiline_history:
1792 if self.multiline_history:
1793 self.readline.add_history(py3compat.unicode_to_str(cell,
1793 self.readline.add_history(py3compat.unicode_to_str(cell,
1794 stdin_encoding))
1794 stdin_encoding))
1795 else:
1795 else:
1796 for line in cell.splitlines():
1796 for line in cell.splitlines():
1797 self.readline.add_history(py3compat.unicode_to_str(line,
1797 self.readline.add_history(py3compat.unicode_to_str(line,
1798 stdin_encoding))
1798 stdin_encoding))
1799 last_cell = cell
1799 last_cell = cell
1800
1800
1801 def set_next_input(self, s):
1801 def set_next_input(self, s):
1802 """ Sets the 'default' input string for the next command line.
1802 """ Sets the 'default' input string for the next command line.
1803
1803
1804 Requires readline.
1804 Requires readline.
1805
1805
1806 Example:
1806 Example:
1807
1807
1808 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1808 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1809 [D:\ipython]|2> Hello Word_ # cursor is here
1809 [D:\ipython]|2> Hello Word_ # cursor is here
1810 """
1810 """
1811 self.rl_next_input = py3compat.cast_bytes_py2(s)
1811 self.rl_next_input = py3compat.cast_bytes_py2(s)
1812
1812
1813 # Maybe move this to the terminal subclass?
1813 # Maybe move this to the terminal subclass?
1814 def pre_readline(self):
1814 def pre_readline(self):
1815 """readline hook to be used at the start of each line.
1815 """readline hook to be used at the start of each line.
1816
1816
1817 Currently it handles auto-indent only."""
1817 Currently it handles auto-indent only."""
1818
1818
1819 if self.rl_do_indent:
1819 if self.rl_do_indent:
1820 self.readline.insert_text(self._indent_current_str())
1820 self.readline.insert_text(self._indent_current_str())
1821 if self.rl_next_input is not None:
1821 if self.rl_next_input is not None:
1822 self.readline.insert_text(self.rl_next_input)
1822 self.readline.insert_text(self.rl_next_input)
1823 self.rl_next_input = None
1823 self.rl_next_input = None
1824
1824
1825 def _indent_current_str(self):
1825 def _indent_current_str(self):
1826 """return the current level of indentation as a string"""
1826 """return the current level of indentation as a string"""
1827 return self.input_splitter.indent_spaces * ' '
1827 return self.input_splitter.indent_spaces * ' '
1828
1828
1829 #-------------------------------------------------------------------------
1829 #-------------------------------------------------------------------------
1830 # Things related to text completion
1830 # Things related to text completion
1831 #-------------------------------------------------------------------------
1831 #-------------------------------------------------------------------------
1832
1832
1833 def init_completer(self):
1833 def init_completer(self):
1834 """Initialize the completion machinery.
1834 """Initialize the completion machinery.
1835
1835
1836 This creates completion machinery that can be used by client code,
1836 This creates completion machinery that can be used by client code,
1837 either interactively in-process (typically triggered by the readline
1837 either interactively in-process (typically triggered by the readline
1838 library), programatically (such as in test suites) or out-of-prcess
1838 library), programatically (such as in test suites) or out-of-prcess
1839 (typically over the network by remote frontends).
1839 (typically over the network by remote frontends).
1840 """
1840 """
1841 from IPython.core.completer import IPCompleter
1841 from IPython.core.completer import IPCompleter
1842 from IPython.core.completerlib import (module_completer,
1842 from IPython.core.completerlib import (module_completer,
1843 magic_run_completer, cd_completer)
1843 magic_run_completer, cd_completer, clear_completer)
1844
1844
1845 self.Completer = IPCompleter(shell=self,
1845 self.Completer = IPCompleter(shell=self,
1846 namespace=self.user_ns,
1846 namespace=self.user_ns,
1847 global_namespace=self.user_global_ns,
1847 global_namespace=self.user_global_ns,
1848 alias_table=self.alias_manager.alias_table,
1848 alias_table=self.alias_manager.alias_table,
1849 use_readline=self.has_readline,
1849 use_readline=self.has_readline,
1850 config=self.config,
1850 config=self.config,
1851 )
1851 )
1852 self.configurables.append(self.Completer)
1852 self.configurables.append(self.Completer)
1853
1853
1854 # Add custom completers to the basic ones built into IPCompleter
1854 # Add custom completers to the basic ones built into IPCompleter
1855 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1855 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1856 self.strdispatchers['complete_command'] = sdisp
1856 self.strdispatchers['complete_command'] = sdisp
1857 self.Completer.custom_completers = sdisp
1857 self.Completer.custom_completers = sdisp
1858
1858
1859 self.set_hook('complete_command', module_completer, str_key = 'import')
1859 self.set_hook('complete_command', module_completer, str_key = 'import')
1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1863 self.set_hook('complete_command', clear_completer, str_key = '%clear')
1863
1864
1864 # Only configure readline if we truly are using readline. IPython can
1865 # Only configure readline if we truly are using readline. IPython can
1865 # do tab-completion over the network, in GUIs, etc, where readline
1866 # do tab-completion over the network, in GUIs, etc, where readline
1866 # itself may be absent
1867 # itself may be absent
1867 if self.has_readline:
1868 if self.has_readline:
1868 self.set_readline_completer()
1869 self.set_readline_completer()
1869
1870
1870 def complete(self, text, line=None, cursor_pos=None):
1871 def complete(self, text, line=None, cursor_pos=None):
1871 """Return the completed text and a list of completions.
1872 """Return the completed text and a list of completions.
1872
1873
1873 Parameters
1874 Parameters
1874 ----------
1875 ----------
1875
1876
1876 text : string
1877 text : string
1877 A string of text to be completed on. It can be given as empty and
1878 A string of text to be completed on. It can be given as empty and
1878 instead a line/position pair are given. In this case, the
1879 instead a line/position pair are given. In this case, the
1879 completer itself will split the line like readline does.
1880 completer itself will split the line like readline does.
1880
1881
1881 line : string, optional
1882 line : string, optional
1882 The complete line that text is part of.
1883 The complete line that text is part of.
1883
1884
1884 cursor_pos : int, optional
1885 cursor_pos : int, optional
1885 The position of the cursor on the input line.
1886 The position of the cursor on the input line.
1886
1887
1887 Returns
1888 Returns
1888 -------
1889 -------
1889 text : string
1890 text : string
1890 The actual text that was completed.
1891 The actual text that was completed.
1891
1892
1892 matches : list
1893 matches : list
1893 A sorted list with all possible completions.
1894 A sorted list with all possible completions.
1894
1895
1895 The optional arguments allow the completion to take more context into
1896 The optional arguments allow the completion to take more context into
1896 account, and are part of the low-level completion API.
1897 account, and are part of the low-level completion API.
1897
1898
1898 This is a wrapper around the completion mechanism, similar to what
1899 This is a wrapper around the completion mechanism, similar to what
1899 readline does at the command line when the TAB key is hit. By
1900 readline does at the command line when the TAB key is hit. By
1900 exposing it as a method, it can be used by other non-readline
1901 exposing it as a method, it can be used by other non-readline
1901 environments (such as GUIs) for text completion.
1902 environments (such as GUIs) for text completion.
1902
1903
1903 Simple usage example:
1904 Simple usage example:
1904
1905
1905 In [1]: x = 'hello'
1906 In [1]: x = 'hello'
1906
1907
1907 In [2]: _ip.complete('x.l')
1908 In [2]: _ip.complete('x.l')
1908 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1909 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1909 """
1910 """
1910
1911
1911 # Inject names into __builtin__ so we can complete on the added names.
1912 # Inject names into __builtin__ so we can complete on the added names.
1912 with self.builtin_trap:
1913 with self.builtin_trap:
1913 return self.Completer.complete(text, line, cursor_pos)
1914 return self.Completer.complete(text, line, cursor_pos)
1914
1915
1915 def set_custom_completer(self, completer, pos=0):
1916 def set_custom_completer(self, completer, pos=0):
1916 """Adds a new custom completer function.
1917 """Adds a new custom completer function.
1917
1918
1918 The position argument (defaults to 0) is the index in the completers
1919 The position argument (defaults to 0) is the index in the completers
1919 list where you want the completer to be inserted."""
1920 list where you want the completer to be inserted."""
1920
1921
1921 newcomp = types.MethodType(completer,self.Completer)
1922 newcomp = types.MethodType(completer,self.Completer)
1922 self.Completer.matchers.insert(pos,newcomp)
1923 self.Completer.matchers.insert(pos,newcomp)
1923
1924
1924 def set_readline_completer(self):
1925 def set_readline_completer(self):
1925 """Reset readline's completer to be our own."""
1926 """Reset readline's completer to be our own."""
1926 self.readline.set_completer(self.Completer.rlcomplete)
1927 self.readline.set_completer(self.Completer.rlcomplete)
1927
1928
1928 def set_completer_frame(self, frame=None):
1929 def set_completer_frame(self, frame=None):
1929 """Set the frame of the completer."""
1930 """Set the frame of the completer."""
1930 if frame:
1931 if frame:
1931 self.Completer.namespace = frame.f_locals
1932 self.Completer.namespace = frame.f_locals
1932 self.Completer.global_namespace = frame.f_globals
1933 self.Completer.global_namespace = frame.f_globals
1933 else:
1934 else:
1934 self.Completer.namespace = self.user_ns
1935 self.Completer.namespace = self.user_ns
1935 self.Completer.global_namespace = self.user_global_ns
1936 self.Completer.global_namespace = self.user_global_ns
1936
1937
1937 #-------------------------------------------------------------------------
1938 #-------------------------------------------------------------------------
1938 # Things related to magics
1939 # Things related to magics
1939 #-------------------------------------------------------------------------
1940 #-------------------------------------------------------------------------
1940
1941
1941 def init_magics(self):
1942 def init_magics(self):
1942 # FIXME: Move the color initialization to the DisplayHook, which
1943 # FIXME: Move the color initialization to the DisplayHook, which
1943 # should be split into a prompt manager and displayhook. We probably
1944 # should be split into a prompt manager and displayhook. We probably
1944 # even need a centralize colors management object.
1945 # even need a centralize colors management object.
1945 self.magic_colors(self.colors)
1946 self.magic_colors(self.colors)
1946 # History was moved to a separate module
1947 # History was moved to a separate module
1947 from IPython.core import history
1948 from IPython.core import history
1948 history.init_ipython(self)
1949 history.init_ipython(self)
1949
1950
1950 def magic(self, arg_s, next_input=None):
1951 def magic(self, arg_s, next_input=None):
1951 """Call a magic function by name.
1952 """Call a magic function by name.
1952
1953
1953 Input: a string containing the name of the magic function to call and
1954 Input: a string containing the name of the magic function to call and
1954 any additional arguments to be passed to the magic.
1955 any additional arguments to be passed to the magic.
1955
1956
1956 magic('name -opt foo bar') is equivalent to typing at the ipython
1957 magic('name -opt foo bar') is equivalent to typing at the ipython
1957 prompt:
1958 prompt:
1958
1959
1959 In[1]: %name -opt foo bar
1960 In[1]: %name -opt foo bar
1960
1961
1961 To call a magic without arguments, simply use magic('name').
1962 To call a magic without arguments, simply use magic('name').
1962
1963
1963 This provides a proper Python function to call IPython's magics in any
1964 This provides a proper Python function to call IPython's magics in any
1964 valid Python code you can type at the interpreter, including loops and
1965 valid Python code you can type at the interpreter, including loops and
1965 compound statements.
1966 compound statements.
1966 """
1967 """
1967 # Allow setting the next input - this is used if the user does `a=abs?`.
1968 # Allow setting the next input - this is used if the user does `a=abs?`.
1968 # We do this first so that magic functions can override it.
1969 # We do this first so that magic functions can override it.
1969 if next_input:
1970 if next_input:
1970 self.set_next_input(next_input)
1971 self.set_next_input(next_input)
1971
1972
1972 args = arg_s.split(' ',1)
1973 args = arg_s.split(' ',1)
1973 magic_name = args[0]
1974 magic_name = args[0]
1974 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1975 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1975
1976
1976 try:
1977 try:
1977 magic_args = args[1]
1978 magic_args = args[1]
1978 except IndexError:
1979 except IndexError:
1979 magic_args = ''
1980 magic_args = ''
1980 fn = getattr(self,'magic_'+magic_name,None)
1981 fn = getattr(self,'magic_'+magic_name,None)
1981 if fn is None:
1982 if fn is None:
1982 error("Magic function `%s` not found." % magic_name)
1983 error("Magic function `%s` not found." % magic_name)
1983 else:
1984 else:
1984 magic_args = self.var_expand(magic_args,1)
1985 magic_args = self.var_expand(magic_args,1)
1985 # Grab local namespace if we need it:
1986 # Grab local namespace if we need it:
1986 if getattr(fn, "needs_local_scope", False):
1987 if getattr(fn, "needs_local_scope", False):
1987 self._magic_locals = sys._getframe(1).f_locals
1988 self._magic_locals = sys._getframe(1).f_locals
1988 with self.builtin_trap:
1989 with self.builtin_trap:
1989 result = fn(magic_args)
1990 result = fn(magic_args)
1990 # Ensure we're not keeping object references around:
1991 # Ensure we're not keeping object references around:
1991 self._magic_locals = {}
1992 self._magic_locals = {}
1992 return result
1993 return result
1993
1994
1994 def define_magic(self, magicname, func):
1995 def define_magic(self, magicname, func):
1995 """Expose own function as magic function for ipython
1996 """Expose own function as magic function for ipython
1996
1997
1997 Example::
1998 Example::
1998
1999
1999 def foo_impl(self,parameter_s=''):
2000 def foo_impl(self,parameter_s=''):
2000 'My very own magic!. (Use docstrings, IPython reads them).'
2001 'My very own magic!. (Use docstrings, IPython reads them).'
2001 print 'Magic function. Passed parameter is between < >:'
2002 print 'Magic function. Passed parameter is between < >:'
2002 print '<%s>' % parameter_s
2003 print '<%s>' % parameter_s
2003 print 'The self object is:', self
2004 print 'The self object is:', self
2004
2005
2005 ip.define_magic('foo',foo_impl)
2006 ip.define_magic('foo',foo_impl)
2006 """
2007 """
2007 im = types.MethodType(func,self)
2008 im = types.MethodType(func,self)
2008 old = getattr(self, "magic_" + magicname, None)
2009 old = getattr(self, "magic_" + magicname, None)
2009 setattr(self, "magic_" + magicname, im)
2010 setattr(self, "magic_" + magicname, im)
2010 return old
2011 return old
2011
2012
2012 #-------------------------------------------------------------------------
2013 #-------------------------------------------------------------------------
2013 # Things related to macros
2014 # Things related to macros
2014 #-------------------------------------------------------------------------
2015 #-------------------------------------------------------------------------
2015
2016
2016 def define_macro(self, name, themacro):
2017 def define_macro(self, name, themacro):
2017 """Define a new macro
2018 """Define a new macro
2018
2019
2019 Parameters
2020 Parameters
2020 ----------
2021 ----------
2021 name : str
2022 name : str
2022 The name of the macro.
2023 The name of the macro.
2023 themacro : str or Macro
2024 themacro : str or Macro
2024 The action to do upon invoking the macro. If a string, a new
2025 The action to do upon invoking the macro. If a string, a new
2025 Macro object is created by passing the string to it.
2026 Macro object is created by passing the string to it.
2026 """
2027 """
2027
2028
2028 from IPython.core import macro
2029 from IPython.core import macro
2029
2030
2030 if isinstance(themacro, basestring):
2031 if isinstance(themacro, basestring):
2031 themacro = macro.Macro(themacro)
2032 themacro = macro.Macro(themacro)
2032 if not isinstance(themacro, macro.Macro):
2033 if not isinstance(themacro, macro.Macro):
2033 raise ValueError('A macro must be a string or a Macro instance.')
2034 raise ValueError('A macro must be a string or a Macro instance.')
2034 self.user_ns[name] = themacro
2035 self.user_ns[name] = themacro
2035
2036
2036 #-------------------------------------------------------------------------
2037 #-------------------------------------------------------------------------
2037 # Things related to the running of system commands
2038 # Things related to the running of system commands
2038 #-------------------------------------------------------------------------
2039 #-------------------------------------------------------------------------
2039
2040
2040 def system_piped(self, cmd):
2041 def system_piped(self, cmd):
2041 """Call the given cmd in a subprocess, piping stdout/err
2042 """Call the given cmd in a subprocess, piping stdout/err
2042
2043
2043 Parameters
2044 Parameters
2044 ----------
2045 ----------
2045 cmd : str
2046 cmd : str
2046 Command to execute (can not end in '&', as background processes are
2047 Command to execute (can not end in '&', as background processes are
2047 not supported. Should not be a command that expects input
2048 not supported. Should not be a command that expects input
2048 other than simple text.
2049 other than simple text.
2049 """
2050 """
2050 if cmd.rstrip().endswith('&'):
2051 if cmd.rstrip().endswith('&'):
2051 # this is *far* from a rigorous test
2052 # this is *far* from a rigorous test
2052 # We do not support backgrounding processes because we either use
2053 # We do not support backgrounding processes because we either use
2053 # pexpect or pipes to read from. Users can always just call
2054 # pexpect or pipes to read from. Users can always just call
2054 # os.system() or use ip.system=ip.system_raw
2055 # os.system() or use ip.system=ip.system_raw
2055 # if they really want a background process.
2056 # if they really want a background process.
2056 raise OSError("Background processes not supported.")
2057 raise OSError("Background processes not supported.")
2057
2058
2058 # we explicitly do NOT return the subprocess status code, because
2059 # we explicitly do NOT return the subprocess status code, because
2059 # a non-None value would trigger :func:`sys.displayhook` calls.
2060 # a non-None value would trigger :func:`sys.displayhook` calls.
2060 # Instead, we store the exit_code in user_ns.
2061 # Instead, we store the exit_code in user_ns.
2061 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2062 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2062
2063
2063 def system_raw(self, cmd):
2064 def system_raw(self, cmd):
2064 """Call the given cmd in a subprocess using os.system
2065 """Call the given cmd in a subprocess using os.system
2065
2066
2066 Parameters
2067 Parameters
2067 ----------
2068 ----------
2068 cmd : str
2069 cmd : str
2069 Command to execute.
2070 Command to execute.
2070 """
2071 """
2071 cmd = self.var_expand(cmd, depth=2)
2072 cmd = self.var_expand(cmd, depth=2)
2072 # protect os.system from UNC paths on Windows, which it can't handle:
2073 # protect os.system from UNC paths on Windows, which it can't handle:
2073 if sys.platform == 'win32':
2074 if sys.platform == 'win32':
2074 from IPython.utils._process_win32 import AvoidUNCPath
2075 from IPython.utils._process_win32 import AvoidUNCPath
2075 with AvoidUNCPath() as path:
2076 with AvoidUNCPath() as path:
2076 if path is not None:
2077 if path is not None:
2077 cmd = '"pushd %s &&"%s' % (path, cmd)
2078 cmd = '"pushd %s &&"%s' % (path, cmd)
2078 cmd = py3compat.unicode_to_str(cmd)
2079 cmd = py3compat.unicode_to_str(cmd)
2079 ec = os.system(cmd)
2080 ec = os.system(cmd)
2080 else:
2081 else:
2081 cmd = py3compat.unicode_to_str(cmd)
2082 cmd = py3compat.unicode_to_str(cmd)
2082 ec = os.system(cmd)
2083 ec = os.system(cmd)
2083
2084
2084 # We explicitly do NOT return the subprocess status code, because
2085 # We explicitly do NOT return the subprocess status code, because
2085 # a non-None value would trigger :func:`sys.displayhook` calls.
2086 # a non-None value would trigger :func:`sys.displayhook` calls.
2086 # Instead, we store the exit_code in user_ns.
2087 # Instead, we store the exit_code in user_ns.
2087 self.user_ns['_exit_code'] = ec
2088 self.user_ns['_exit_code'] = ec
2088
2089
2089 # use piped system by default, because it is better behaved
2090 # use piped system by default, because it is better behaved
2090 system = system_piped
2091 system = system_piped
2091
2092
2092 def getoutput(self, cmd, split=True):
2093 def getoutput(self, cmd, split=True):
2093 """Get output (possibly including stderr) from a subprocess.
2094 """Get output (possibly including stderr) from a subprocess.
2094
2095
2095 Parameters
2096 Parameters
2096 ----------
2097 ----------
2097 cmd : str
2098 cmd : str
2098 Command to execute (can not end in '&', as background processes are
2099 Command to execute (can not end in '&', as background processes are
2099 not supported.
2100 not supported.
2100 split : bool, optional
2101 split : bool, optional
2101
2102
2102 If True, split the output into an IPython SList. Otherwise, an
2103 If True, split the output into an IPython SList. Otherwise, an
2103 IPython LSString is returned. These are objects similar to normal
2104 IPython LSString is returned. These are objects similar to normal
2104 lists and strings, with a few convenience attributes for easier
2105 lists and strings, with a few convenience attributes for easier
2105 manipulation of line-based output. You can use '?' on them for
2106 manipulation of line-based output. You can use '?' on them for
2106 details.
2107 details.
2107 """
2108 """
2108 if cmd.rstrip().endswith('&'):
2109 if cmd.rstrip().endswith('&'):
2109 # this is *far* from a rigorous test
2110 # this is *far* from a rigorous test
2110 raise OSError("Background processes not supported.")
2111 raise OSError("Background processes not supported.")
2111 out = getoutput(self.var_expand(cmd, depth=2))
2112 out = getoutput(self.var_expand(cmd, depth=2))
2112 if split:
2113 if split:
2113 out = SList(out.splitlines())
2114 out = SList(out.splitlines())
2114 else:
2115 else:
2115 out = LSString(out)
2116 out = LSString(out)
2116 return out
2117 return out
2117
2118
2118 #-------------------------------------------------------------------------
2119 #-------------------------------------------------------------------------
2119 # Things related to aliases
2120 # Things related to aliases
2120 #-------------------------------------------------------------------------
2121 #-------------------------------------------------------------------------
2121
2122
2122 def init_alias(self):
2123 def init_alias(self):
2123 self.alias_manager = AliasManager(shell=self, config=self.config)
2124 self.alias_manager = AliasManager(shell=self, config=self.config)
2124 self.configurables.append(self.alias_manager)
2125 self.configurables.append(self.alias_manager)
2125 self.ns_table['alias'] = self.alias_manager.alias_table,
2126 self.ns_table['alias'] = self.alias_manager.alias_table,
2126
2127
2127 #-------------------------------------------------------------------------
2128 #-------------------------------------------------------------------------
2128 # Things related to extensions and plugins
2129 # Things related to extensions and plugins
2129 #-------------------------------------------------------------------------
2130 #-------------------------------------------------------------------------
2130
2131
2131 def init_extension_manager(self):
2132 def init_extension_manager(self):
2132 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2133 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2133 self.configurables.append(self.extension_manager)
2134 self.configurables.append(self.extension_manager)
2134
2135
2135 def init_plugin_manager(self):
2136 def init_plugin_manager(self):
2136 self.plugin_manager = PluginManager(config=self.config)
2137 self.plugin_manager = PluginManager(config=self.config)
2137 self.configurables.append(self.plugin_manager)
2138 self.configurables.append(self.plugin_manager)
2138
2139
2139
2140
2140 #-------------------------------------------------------------------------
2141 #-------------------------------------------------------------------------
2141 # Things related to payloads
2142 # Things related to payloads
2142 #-------------------------------------------------------------------------
2143 #-------------------------------------------------------------------------
2143
2144
2144 def init_payload(self):
2145 def init_payload(self):
2145 self.payload_manager = PayloadManager(config=self.config)
2146 self.payload_manager = PayloadManager(config=self.config)
2146 self.configurables.append(self.payload_manager)
2147 self.configurables.append(self.payload_manager)
2147
2148
2148 #-------------------------------------------------------------------------
2149 #-------------------------------------------------------------------------
2149 # Things related to the prefilter
2150 # Things related to the prefilter
2150 #-------------------------------------------------------------------------
2151 #-------------------------------------------------------------------------
2151
2152
2152 def init_prefilter(self):
2153 def init_prefilter(self):
2153 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2154 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2154 self.configurables.append(self.prefilter_manager)
2155 self.configurables.append(self.prefilter_manager)
2155 # Ultimately this will be refactored in the new interpreter code, but
2156 # Ultimately this will be refactored in the new interpreter code, but
2156 # for now, we should expose the main prefilter method (there's legacy
2157 # for now, we should expose the main prefilter method (there's legacy
2157 # code out there that may rely on this).
2158 # code out there that may rely on this).
2158 self.prefilter = self.prefilter_manager.prefilter_lines
2159 self.prefilter = self.prefilter_manager.prefilter_lines
2159
2160
2160 def auto_rewrite_input(self, cmd):
2161 def auto_rewrite_input(self, cmd):
2161 """Print to the screen the rewritten form of the user's command.
2162 """Print to the screen the rewritten form of the user's command.
2162
2163
2163 This shows visual feedback by rewriting input lines that cause
2164 This shows visual feedback by rewriting input lines that cause
2164 automatic calling to kick in, like::
2165 automatic calling to kick in, like::
2165
2166
2166 /f x
2167 /f x
2167
2168
2168 into::
2169 into::
2169
2170
2170 ------> f(x)
2171 ------> f(x)
2171
2172
2172 after the user's input prompt. This helps the user understand that the
2173 after the user's input prompt. This helps the user understand that the
2173 input line was transformed automatically by IPython.
2174 input line was transformed automatically by IPython.
2174 """
2175 """
2175 if not self.show_rewritten_input:
2176 if not self.show_rewritten_input:
2176 return
2177 return
2177
2178
2178 rw = self.prompt_manager.render('rewrite') + cmd
2179 rw = self.prompt_manager.render('rewrite') + cmd
2179
2180
2180 try:
2181 try:
2181 # plain ascii works better w/ pyreadline, on some machines, so
2182 # plain ascii works better w/ pyreadline, on some machines, so
2182 # we use it and only print uncolored rewrite if we have unicode
2183 # we use it and only print uncolored rewrite if we have unicode
2183 rw = str(rw)
2184 rw = str(rw)
2184 print >> io.stdout, rw
2185 print >> io.stdout, rw
2185 except UnicodeEncodeError:
2186 except UnicodeEncodeError:
2186 print "------> " + cmd
2187 print "------> " + cmd
2187
2188
2188 #-------------------------------------------------------------------------
2189 #-------------------------------------------------------------------------
2189 # Things related to extracting values/expressions from kernel and user_ns
2190 # Things related to extracting values/expressions from kernel and user_ns
2190 #-------------------------------------------------------------------------
2191 #-------------------------------------------------------------------------
2191
2192
2192 def _simple_error(self):
2193 def _simple_error(self):
2193 etype, value = sys.exc_info()[:2]
2194 etype, value = sys.exc_info()[:2]
2194 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2195 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2195
2196
2196 def user_variables(self, names):
2197 def user_variables(self, names):
2197 """Get a list of variable names from the user's namespace.
2198 """Get a list of variable names from the user's namespace.
2198
2199
2199 Parameters
2200 Parameters
2200 ----------
2201 ----------
2201 names : list of strings
2202 names : list of strings
2202 A list of names of variables to be read from the user namespace.
2203 A list of names of variables to be read from the user namespace.
2203
2204
2204 Returns
2205 Returns
2205 -------
2206 -------
2206 A dict, keyed by the input names and with the repr() of each value.
2207 A dict, keyed by the input names and with the repr() of each value.
2207 """
2208 """
2208 out = {}
2209 out = {}
2209 user_ns = self.user_ns
2210 user_ns = self.user_ns
2210 for varname in names:
2211 for varname in names:
2211 try:
2212 try:
2212 value = repr(user_ns[varname])
2213 value = repr(user_ns[varname])
2213 except:
2214 except:
2214 value = self._simple_error()
2215 value = self._simple_error()
2215 out[varname] = value
2216 out[varname] = value
2216 return out
2217 return out
2217
2218
2218 def user_expressions(self, expressions):
2219 def user_expressions(self, expressions):
2219 """Evaluate a dict of expressions in the user's namespace.
2220 """Evaluate a dict of expressions in the user's namespace.
2220
2221
2221 Parameters
2222 Parameters
2222 ----------
2223 ----------
2223 expressions : dict
2224 expressions : dict
2224 A dict with string keys and string values. The expression values
2225 A dict with string keys and string values. The expression values
2225 should be valid Python expressions, each of which will be evaluated
2226 should be valid Python expressions, each of which will be evaluated
2226 in the user namespace.
2227 in the user namespace.
2227
2228
2228 Returns
2229 Returns
2229 -------
2230 -------
2230 A dict, keyed like the input expressions dict, with the repr() of each
2231 A dict, keyed like the input expressions dict, with the repr() of each
2231 value.
2232 value.
2232 """
2233 """
2233 out = {}
2234 out = {}
2234 user_ns = self.user_ns
2235 user_ns = self.user_ns
2235 global_ns = self.user_global_ns
2236 global_ns = self.user_global_ns
2236 for key, expr in expressions.iteritems():
2237 for key, expr in expressions.iteritems():
2237 try:
2238 try:
2238 value = repr(eval(expr, global_ns, user_ns))
2239 value = repr(eval(expr, global_ns, user_ns))
2239 except:
2240 except:
2240 value = self._simple_error()
2241 value = self._simple_error()
2241 out[key] = value
2242 out[key] = value
2242 return out
2243 return out
2243
2244
2244 #-------------------------------------------------------------------------
2245 #-------------------------------------------------------------------------
2245 # Things related to the running of code
2246 # Things related to the running of code
2246 #-------------------------------------------------------------------------
2247 #-------------------------------------------------------------------------
2247
2248
2248 def ex(self, cmd):
2249 def ex(self, cmd):
2249 """Execute a normal python statement in user namespace."""
2250 """Execute a normal python statement in user namespace."""
2250 with self.builtin_trap:
2251 with self.builtin_trap:
2251 exec cmd in self.user_global_ns, self.user_ns
2252 exec cmd in self.user_global_ns, self.user_ns
2252
2253
2253 def ev(self, expr):
2254 def ev(self, expr):
2254 """Evaluate python expression expr in user namespace.
2255 """Evaluate python expression expr in user namespace.
2255
2256
2256 Returns the result of evaluation
2257 Returns the result of evaluation
2257 """
2258 """
2258 with self.builtin_trap:
2259 with self.builtin_trap:
2259 return eval(expr, self.user_global_ns, self.user_ns)
2260 return eval(expr, self.user_global_ns, self.user_ns)
2260
2261
2261 def safe_execfile(self, fname, *where, **kw):
2262 def safe_execfile(self, fname, *where, **kw):
2262 """A safe version of the builtin execfile().
2263 """A safe version of the builtin execfile().
2263
2264
2264 This version will never throw an exception, but instead print
2265 This version will never throw an exception, but instead print
2265 helpful error messages to the screen. This only works on pure
2266 helpful error messages to the screen. This only works on pure
2266 Python files with the .py extension.
2267 Python files with the .py extension.
2267
2268
2268 Parameters
2269 Parameters
2269 ----------
2270 ----------
2270 fname : string
2271 fname : string
2271 The name of the file to be executed.
2272 The name of the file to be executed.
2272 where : tuple
2273 where : tuple
2273 One or two namespaces, passed to execfile() as (globals,locals).
2274 One or two namespaces, passed to execfile() as (globals,locals).
2274 If only one is given, it is passed as both.
2275 If only one is given, it is passed as both.
2275 exit_ignore : bool (False)
2276 exit_ignore : bool (False)
2276 If True, then silence SystemExit for non-zero status (it is always
2277 If True, then silence SystemExit for non-zero status (it is always
2277 silenced for zero status, as it is so common).
2278 silenced for zero status, as it is so common).
2278 raise_exceptions : bool (False)
2279 raise_exceptions : bool (False)
2279 If True raise exceptions everywhere. Meant for testing.
2280 If True raise exceptions everywhere. Meant for testing.
2280
2281
2281 """
2282 """
2282 kw.setdefault('exit_ignore', False)
2283 kw.setdefault('exit_ignore', False)
2283 kw.setdefault('raise_exceptions', False)
2284 kw.setdefault('raise_exceptions', False)
2284
2285
2285 fname = os.path.abspath(os.path.expanduser(fname))
2286 fname = os.path.abspath(os.path.expanduser(fname))
2286
2287
2287 # Make sure we can open the file
2288 # Make sure we can open the file
2288 try:
2289 try:
2289 with open(fname) as thefile:
2290 with open(fname) as thefile:
2290 pass
2291 pass
2291 except:
2292 except:
2292 warn('Could not open file <%s> for safe execution.' % fname)
2293 warn('Could not open file <%s> for safe execution.' % fname)
2293 return
2294 return
2294
2295
2295 # Find things also in current directory. This is needed to mimic the
2296 # Find things also in current directory. This is needed to mimic the
2296 # behavior of running a script from the system command line, where
2297 # behavior of running a script from the system command line, where
2297 # Python inserts the script's directory into sys.path
2298 # Python inserts the script's directory into sys.path
2298 dname = os.path.dirname(fname)
2299 dname = os.path.dirname(fname)
2299
2300
2300 with prepended_to_syspath(dname):
2301 with prepended_to_syspath(dname):
2301 try:
2302 try:
2302 py3compat.execfile(fname,*where)
2303 py3compat.execfile(fname,*where)
2303 except SystemExit, status:
2304 except SystemExit, status:
2304 # If the call was made with 0 or None exit status (sys.exit(0)
2305 # If the call was made with 0 or None exit status (sys.exit(0)
2305 # or sys.exit() ), don't bother showing a traceback, as both of
2306 # or sys.exit() ), don't bother showing a traceback, as both of
2306 # these are considered normal by the OS:
2307 # these are considered normal by the OS:
2307 # > python -c'import sys;sys.exit(0)'; echo $?
2308 # > python -c'import sys;sys.exit(0)'; echo $?
2308 # 0
2309 # 0
2309 # > python -c'import sys;sys.exit()'; echo $?
2310 # > python -c'import sys;sys.exit()'; echo $?
2310 # 0
2311 # 0
2311 # For other exit status, we show the exception unless
2312 # For other exit status, we show the exception unless
2312 # explicitly silenced, but only in short form.
2313 # explicitly silenced, but only in short form.
2313 if kw['raise_exceptions']:
2314 if kw['raise_exceptions']:
2314 raise
2315 raise
2315 if status.code not in (0, None) and not kw['exit_ignore']:
2316 if status.code not in (0, None) and not kw['exit_ignore']:
2316 self.showtraceback(exception_only=True)
2317 self.showtraceback(exception_only=True)
2317 except:
2318 except:
2318 if kw['raise_exceptions']:
2319 if kw['raise_exceptions']:
2319 raise
2320 raise
2320 self.showtraceback()
2321 self.showtraceback()
2321
2322
2322 def safe_execfile_ipy(self, fname):
2323 def safe_execfile_ipy(self, fname):
2323 """Like safe_execfile, but for .ipy files with IPython syntax.
2324 """Like safe_execfile, but for .ipy files with IPython syntax.
2324
2325
2325 Parameters
2326 Parameters
2326 ----------
2327 ----------
2327 fname : str
2328 fname : str
2328 The name of the file to execute. The filename must have a
2329 The name of the file to execute. The filename must have a
2329 .ipy extension.
2330 .ipy extension.
2330 """
2331 """
2331 fname = os.path.abspath(os.path.expanduser(fname))
2332 fname = os.path.abspath(os.path.expanduser(fname))
2332
2333
2333 # Make sure we can open the file
2334 # Make sure we can open the file
2334 try:
2335 try:
2335 with open(fname) as thefile:
2336 with open(fname) as thefile:
2336 pass
2337 pass
2337 except:
2338 except:
2338 warn('Could not open file <%s> for safe execution.' % fname)
2339 warn('Could not open file <%s> for safe execution.' % fname)
2339 return
2340 return
2340
2341
2341 # Find things also in current directory. This is needed to mimic the
2342 # Find things also in current directory. This is needed to mimic the
2342 # behavior of running a script from the system command line, where
2343 # behavior of running a script from the system command line, where
2343 # Python inserts the script's directory into sys.path
2344 # Python inserts the script's directory into sys.path
2344 dname = os.path.dirname(fname)
2345 dname = os.path.dirname(fname)
2345
2346
2346 with prepended_to_syspath(dname):
2347 with prepended_to_syspath(dname):
2347 try:
2348 try:
2348 with open(fname) as thefile:
2349 with open(fname) as thefile:
2349 # self.run_cell currently captures all exceptions
2350 # self.run_cell currently captures all exceptions
2350 # raised in user code. It would be nice if there were
2351 # raised in user code. It would be nice if there were
2351 # versions of runlines, execfile that did raise, so
2352 # versions of runlines, execfile that did raise, so
2352 # we could catch the errors.
2353 # we could catch the errors.
2353 self.run_cell(thefile.read(), store_history=False)
2354 self.run_cell(thefile.read(), store_history=False)
2354 except:
2355 except:
2355 self.showtraceback()
2356 self.showtraceback()
2356 warn('Unknown failure executing file: <%s>' % fname)
2357 warn('Unknown failure executing file: <%s>' % fname)
2357
2358
2358 def run_cell(self, raw_cell, store_history=False):
2359 def run_cell(self, raw_cell, store_history=False):
2359 """Run a complete IPython cell.
2360 """Run a complete IPython cell.
2360
2361
2361 Parameters
2362 Parameters
2362 ----------
2363 ----------
2363 raw_cell : str
2364 raw_cell : str
2364 The code (including IPython code such as %magic functions) to run.
2365 The code (including IPython code such as %magic functions) to run.
2365 store_history : bool
2366 store_history : bool
2366 If True, the raw and translated cell will be stored in IPython's
2367 If True, the raw and translated cell will be stored in IPython's
2367 history. For user code calling back into IPython's machinery, this
2368 history. For user code calling back into IPython's machinery, this
2368 should be set to False.
2369 should be set to False.
2369 """
2370 """
2370 if (not raw_cell) or raw_cell.isspace():
2371 if (not raw_cell) or raw_cell.isspace():
2371 return
2372 return
2372
2373
2373 for line in raw_cell.splitlines():
2374 for line in raw_cell.splitlines():
2374 self.input_splitter.push(line)
2375 self.input_splitter.push(line)
2375 cell = self.input_splitter.source_reset()
2376 cell = self.input_splitter.source_reset()
2376
2377
2377 with self.builtin_trap:
2378 with self.builtin_trap:
2378 prefilter_failed = False
2379 prefilter_failed = False
2379 if len(cell.splitlines()) == 1:
2380 if len(cell.splitlines()) == 1:
2380 try:
2381 try:
2381 # use prefilter_lines to handle trailing newlines
2382 # use prefilter_lines to handle trailing newlines
2382 # restore trailing newline for ast.parse
2383 # restore trailing newline for ast.parse
2383 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2384 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2384 except AliasError as e:
2385 except AliasError as e:
2385 error(e)
2386 error(e)
2386 prefilter_failed = True
2387 prefilter_failed = True
2387 except Exception:
2388 except Exception:
2388 # don't allow prefilter errors to crash IPython
2389 # don't allow prefilter errors to crash IPython
2389 self.showtraceback()
2390 self.showtraceback()
2390 prefilter_failed = True
2391 prefilter_failed = True
2391
2392
2392 # Store raw and processed history
2393 # Store raw and processed history
2393 if store_history:
2394 if store_history:
2394 self.history_manager.store_inputs(self.execution_count,
2395 self.history_manager.store_inputs(self.execution_count,
2395 cell, raw_cell)
2396 cell, raw_cell)
2396
2397
2397 self.logger.log(cell, raw_cell)
2398 self.logger.log(cell, raw_cell)
2398
2399
2399 if not prefilter_failed:
2400 if not prefilter_failed:
2400 # don't run if prefilter failed
2401 # don't run if prefilter failed
2401 cell_name = self.compile.cache(cell, self.execution_count)
2402 cell_name = self.compile.cache(cell, self.execution_count)
2402
2403
2403 with self.display_trap:
2404 with self.display_trap:
2404 try:
2405 try:
2405 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2406 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2406 except IndentationError:
2407 except IndentationError:
2407 self.showindentationerror()
2408 self.showindentationerror()
2408 if store_history:
2409 if store_history:
2409 self.execution_count += 1
2410 self.execution_count += 1
2410 return None
2411 return None
2411 except (OverflowError, SyntaxError, ValueError, TypeError,
2412 except (OverflowError, SyntaxError, ValueError, TypeError,
2412 MemoryError):
2413 MemoryError):
2413 self.showsyntaxerror()
2414 self.showsyntaxerror()
2414 if store_history:
2415 if store_history:
2415 self.execution_count += 1
2416 self.execution_count += 1
2416 return None
2417 return None
2417
2418
2418 self.run_ast_nodes(code_ast.body, cell_name,
2419 self.run_ast_nodes(code_ast.body, cell_name,
2419 interactivity="last_expr")
2420 interactivity="last_expr")
2420
2421
2421 # Execute any registered post-execution functions.
2422 # Execute any registered post-execution functions.
2422 for func, status in self._post_execute.iteritems():
2423 for func, status in self._post_execute.iteritems():
2423 if self.disable_failing_post_execute and not status:
2424 if self.disable_failing_post_execute and not status:
2424 continue
2425 continue
2425 try:
2426 try:
2426 func()
2427 func()
2427 except KeyboardInterrupt:
2428 except KeyboardInterrupt:
2428 print >> io.stderr, "\nKeyboardInterrupt"
2429 print >> io.stderr, "\nKeyboardInterrupt"
2429 except Exception:
2430 except Exception:
2430 # register as failing:
2431 # register as failing:
2431 self._post_execute[func] = False
2432 self._post_execute[func] = False
2432 self.showtraceback()
2433 self.showtraceback()
2433 print >> io.stderr, '\n'.join([
2434 print >> io.stderr, '\n'.join([
2434 "post-execution function %r produced an error." % func,
2435 "post-execution function %r produced an error." % func,
2435 "If this problem persists, you can disable failing post-exec functions with:",
2436 "If this problem persists, you can disable failing post-exec functions with:",
2436 "",
2437 "",
2437 " get_ipython().disable_failing_post_execute = True"
2438 " get_ipython().disable_failing_post_execute = True"
2438 ])
2439 ])
2439
2440
2440 if store_history:
2441 if store_history:
2441 # Write output to the database. Does nothing unless
2442 # Write output to the database. Does nothing unless
2442 # history output logging is enabled.
2443 # history output logging is enabled.
2443 self.history_manager.store_output(self.execution_count)
2444 self.history_manager.store_output(self.execution_count)
2444 # Each cell is a *single* input, regardless of how many lines it has
2445 # Each cell is a *single* input, regardless of how many lines it has
2445 self.execution_count += 1
2446 self.execution_count += 1
2446
2447
2447 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2448 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2448 """Run a sequence of AST nodes. The execution mode depends on the
2449 """Run a sequence of AST nodes. The execution mode depends on the
2449 interactivity parameter.
2450 interactivity parameter.
2450
2451
2451 Parameters
2452 Parameters
2452 ----------
2453 ----------
2453 nodelist : list
2454 nodelist : list
2454 A sequence of AST nodes to run.
2455 A sequence of AST nodes to run.
2455 cell_name : str
2456 cell_name : str
2456 Will be passed to the compiler as the filename of the cell. Typically
2457 Will be passed to the compiler as the filename of the cell. Typically
2457 the value returned by ip.compile.cache(cell).
2458 the value returned by ip.compile.cache(cell).
2458 interactivity : str
2459 interactivity : str
2459 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2460 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2460 run interactively (displaying output from expressions). 'last_expr'
2461 run interactively (displaying output from expressions). 'last_expr'
2461 will run the last node interactively only if it is an expression (i.e.
2462 will run the last node interactively only if it is an expression (i.e.
2462 expressions in loops or other blocks are not displayed. Other values
2463 expressions in loops or other blocks are not displayed. Other values
2463 for this parameter will raise a ValueError.
2464 for this parameter will raise a ValueError.
2464 """
2465 """
2465 if not nodelist:
2466 if not nodelist:
2466 return
2467 return
2467
2468
2468 if interactivity == 'last_expr':
2469 if interactivity == 'last_expr':
2469 if isinstance(nodelist[-1], ast.Expr):
2470 if isinstance(nodelist[-1], ast.Expr):
2470 interactivity = "last"
2471 interactivity = "last"
2471 else:
2472 else:
2472 interactivity = "none"
2473 interactivity = "none"
2473
2474
2474 if interactivity == 'none':
2475 if interactivity == 'none':
2475 to_run_exec, to_run_interactive = nodelist, []
2476 to_run_exec, to_run_interactive = nodelist, []
2476 elif interactivity == 'last':
2477 elif interactivity == 'last':
2477 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2478 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2478 elif interactivity == 'all':
2479 elif interactivity == 'all':
2479 to_run_exec, to_run_interactive = [], nodelist
2480 to_run_exec, to_run_interactive = [], nodelist
2480 else:
2481 else:
2481 raise ValueError("Interactivity was %r" % interactivity)
2482 raise ValueError("Interactivity was %r" % interactivity)
2482
2483
2483 exec_count = self.execution_count
2484 exec_count = self.execution_count
2484
2485
2485 try:
2486 try:
2486 for i, node in enumerate(to_run_exec):
2487 for i, node in enumerate(to_run_exec):
2487 mod = ast.Module([node])
2488 mod = ast.Module([node])
2488 code = self.compile(mod, cell_name, "exec")
2489 code = self.compile(mod, cell_name, "exec")
2489 if self.run_code(code):
2490 if self.run_code(code):
2490 return True
2491 return True
2491
2492
2492 for i, node in enumerate(to_run_interactive):
2493 for i, node in enumerate(to_run_interactive):
2493 mod = ast.Interactive([node])
2494 mod = ast.Interactive([node])
2494 code = self.compile(mod, cell_name, "single")
2495 code = self.compile(mod, cell_name, "single")
2495 if self.run_code(code):
2496 if self.run_code(code):
2496 return True
2497 return True
2497 except:
2498 except:
2498 # It's possible to have exceptions raised here, typically by
2499 # It's possible to have exceptions raised here, typically by
2499 # compilation of odd code (such as a naked 'return' outside a
2500 # compilation of odd code (such as a naked 'return' outside a
2500 # function) that did parse but isn't valid. Typically the exception
2501 # function) that did parse but isn't valid. Typically the exception
2501 # is a SyntaxError, but it's safest just to catch anything and show
2502 # is a SyntaxError, but it's safest just to catch anything and show
2502 # the user a traceback.
2503 # the user a traceback.
2503
2504
2504 # We do only one try/except outside the loop to minimize the impact
2505 # We do only one try/except outside the loop to minimize the impact
2505 # on runtime, and also because if any node in the node list is
2506 # on runtime, and also because if any node in the node list is
2506 # broken, we should stop execution completely.
2507 # broken, we should stop execution completely.
2507 self.showtraceback()
2508 self.showtraceback()
2508
2509
2509 return False
2510 return False
2510
2511
2511 def run_code(self, code_obj):
2512 def run_code(self, code_obj):
2512 """Execute a code object.
2513 """Execute a code object.
2513
2514
2514 When an exception occurs, self.showtraceback() is called to display a
2515 When an exception occurs, self.showtraceback() is called to display a
2515 traceback.
2516 traceback.
2516
2517
2517 Parameters
2518 Parameters
2518 ----------
2519 ----------
2519 code_obj : code object
2520 code_obj : code object
2520 A compiled code object, to be executed
2521 A compiled code object, to be executed
2521 post_execute : bool [default: True]
2522 post_execute : bool [default: True]
2522 whether to call post_execute hooks after this particular execution.
2523 whether to call post_execute hooks after this particular execution.
2523
2524
2524 Returns
2525 Returns
2525 -------
2526 -------
2526 False : successful execution.
2527 False : successful execution.
2527 True : an error occurred.
2528 True : an error occurred.
2528 """
2529 """
2529
2530
2530 # Set our own excepthook in case the user code tries to call it
2531 # Set our own excepthook in case the user code tries to call it
2531 # directly, so that the IPython crash handler doesn't get triggered
2532 # directly, so that the IPython crash handler doesn't get triggered
2532 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2533 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2533
2534
2534 # we save the original sys.excepthook in the instance, in case config
2535 # we save the original sys.excepthook in the instance, in case config
2535 # code (such as magics) needs access to it.
2536 # code (such as magics) needs access to it.
2536 self.sys_excepthook = old_excepthook
2537 self.sys_excepthook = old_excepthook
2537 outflag = 1 # happens in more places, so it's easier as default
2538 outflag = 1 # happens in more places, so it's easier as default
2538 try:
2539 try:
2539 try:
2540 try:
2540 self.hooks.pre_run_code_hook()
2541 self.hooks.pre_run_code_hook()
2541 #rprint('Running code', repr(code_obj)) # dbg
2542 #rprint('Running code', repr(code_obj)) # dbg
2542 exec code_obj in self.user_global_ns, self.user_ns
2543 exec code_obj in self.user_global_ns, self.user_ns
2543 finally:
2544 finally:
2544 # Reset our crash handler in place
2545 # Reset our crash handler in place
2545 sys.excepthook = old_excepthook
2546 sys.excepthook = old_excepthook
2546 except SystemExit:
2547 except SystemExit:
2547 self.showtraceback(exception_only=True)
2548 self.showtraceback(exception_only=True)
2548 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2549 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2549 except self.custom_exceptions:
2550 except self.custom_exceptions:
2550 etype,value,tb = sys.exc_info()
2551 etype,value,tb = sys.exc_info()
2551 self.CustomTB(etype,value,tb)
2552 self.CustomTB(etype,value,tb)
2552 except:
2553 except:
2553 self.showtraceback()
2554 self.showtraceback()
2554 else:
2555 else:
2555 outflag = 0
2556 outflag = 0
2556 if softspace(sys.stdout, 0):
2557 if softspace(sys.stdout, 0):
2557 print
2558 print
2558
2559
2559 return outflag
2560 return outflag
2560
2561
2561 # For backwards compatibility
2562 # For backwards compatibility
2562 runcode = run_code
2563 runcode = run_code
2563
2564
2564 #-------------------------------------------------------------------------
2565 #-------------------------------------------------------------------------
2565 # Things related to GUI support and pylab
2566 # Things related to GUI support and pylab
2566 #-------------------------------------------------------------------------
2567 #-------------------------------------------------------------------------
2567
2568
2568 def enable_gui(self, gui=None):
2569 def enable_gui(self, gui=None):
2569 raise NotImplementedError('Implement enable_gui in a subclass')
2570 raise NotImplementedError('Implement enable_gui in a subclass')
2570
2571
2571 def enable_pylab(self, gui=None, import_all=True):
2572 def enable_pylab(self, gui=None, import_all=True):
2572 """Activate pylab support at runtime.
2573 """Activate pylab support at runtime.
2573
2574
2574 This turns on support for matplotlib, preloads into the interactive
2575 This turns on support for matplotlib, preloads into the interactive
2575 namespace all of numpy and pylab, and configures IPython to correctly
2576 namespace all of numpy and pylab, and configures IPython to correctly
2576 interact with the GUI event loop. The GUI backend to be used can be
2577 interact with the GUI event loop. The GUI backend to be used can be
2577 optionally selected with the optional :param:`gui` argument.
2578 optionally selected with the optional :param:`gui` argument.
2578
2579
2579 Parameters
2580 Parameters
2580 ----------
2581 ----------
2581 gui : optional, string
2582 gui : optional, string
2582
2583
2583 If given, dictates the choice of matplotlib GUI backend to use
2584 If given, dictates the choice of matplotlib GUI backend to use
2584 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2585 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2585 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2586 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2586 matplotlib (as dictated by the matplotlib build-time options plus the
2587 matplotlib (as dictated by the matplotlib build-time options plus the
2587 user's matplotlibrc configuration file). Note that not all backends
2588 user's matplotlibrc configuration file). Note that not all backends
2588 make sense in all contexts, for example a terminal ipython can't
2589 make sense in all contexts, for example a terminal ipython can't
2589 display figures inline.
2590 display figures inline.
2590 """
2591 """
2591
2592
2592 # We want to prevent the loading of pylab to pollute the user's
2593 # We want to prevent the loading of pylab to pollute the user's
2593 # namespace as shown by the %who* magics, so we execute the activation
2594 # namespace as shown by the %who* magics, so we execute the activation
2594 # code in an empty namespace, and we update *both* user_ns and
2595 # code in an empty namespace, and we update *both* user_ns and
2595 # user_ns_hidden with this information.
2596 # user_ns_hidden with this information.
2596 ns = {}
2597 ns = {}
2597 try:
2598 try:
2598 gui = pylab_activate(ns, gui, import_all, self)
2599 gui = pylab_activate(ns, gui, import_all, self)
2599 except KeyError:
2600 except KeyError:
2600 error("Backend %r not supported" % gui)
2601 error("Backend %r not supported" % gui)
2601 return
2602 return
2602 self.user_ns.update(ns)
2603 self.user_ns.update(ns)
2603 self.user_ns_hidden.update(ns)
2604 self.user_ns_hidden.update(ns)
2604 # Now we must activate the gui pylab wants to use, and fix %run to take
2605 # Now we must activate the gui pylab wants to use, and fix %run to take
2605 # plot updates into account
2606 # plot updates into account
2606 self.enable_gui(gui)
2607 self.enable_gui(gui)
2607 self.magic_run = self._pylab_magic_run
2608 self.magic_run = self._pylab_magic_run
2608
2609
2609 #-------------------------------------------------------------------------
2610 #-------------------------------------------------------------------------
2610 # Utilities
2611 # Utilities
2611 #-------------------------------------------------------------------------
2612 #-------------------------------------------------------------------------
2612
2613
2613 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2614 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2614 """Expand python variables in a string.
2615 """Expand python variables in a string.
2615
2616
2616 The depth argument indicates how many frames above the caller should
2617 The depth argument indicates how many frames above the caller should
2617 be walked to look for the local namespace where to expand variables.
2618 be walked to look for the local namespace where to expand variables.
2618
2619
2619 The global namespace for expansion is always the user's interactive
2620 The global namespace for expansion is always the user's interactive
2620 namespace.
2621 namespace.
2621 """
2622 """
2622 ns = self.user_ns.copy()
2623 ns = self.user_ns.copy()
2623 ns.update(sys._getframe(depth+1).f_locals)
2624 ns.update(sys._getframe(depth+1).f_locals)
2624 ns.pop('self', None)
2625 ns.pop('self', None)
2625 return formatter.format(cmd, **ns)
2626 return formatter.format(cmd, **ns)
2626
2627
2627 def mktempfile(self, data=None, prefix='ipython_edit_'):
2628 def mktempfile(self, data=None, prefix='ipython_edit_'):
2628 """Make a new tempfile and return its filename.
2629 """Make a new tempfile and return its filename.
2629
2630
2630 This makes a call to tempfile.mktemp, but it registers the created
2631 This makes a call to tempfile.mktemp, but it registers the created
2631 filename internally so ipython cleans it up at exit time.
2632 filename internally so ipython cleans it up at exit time.
2632
2633
2633 Optional inputs:
2634 Optional inputs:
2634
2635
2635 - data(None): if data is given, it gets written out to the temp file
2636 - data(None): if data is given, it gets written out to the temp file
2636 immediately, and the file is closed again."""
2637 immediately, and the file is closed again."""
2637
2638
2638 filename = tempfile.mktemp('.py', prefix)
2639 filename = tempfile.mktemp('.py', prefix)
2639 self.tempfiles.append(filename)
2640 self.tempfiles.append(filename)
2640
2641
2641 if data:
2642 if data:
2642 tmp_file = open(filename,'w')
2643 tmp_file = open(filename,'w')
2643 tmp_file.write(data)
2644 tmp_file.write(data)
2644 tmp_file.close()
2645 tmp_file.close()
2645 return filename
2646 return filename
2646
2647
2647 # TODO: This should be removed when Term is refactored.
2648 # TODO: This should be removed when Term is refactored.
2648 def write(self,data):
2649 def write(self,data):
2649 """Write a string to the default output"""
2650 """Write a string to the default output"""
2650 io.stdout.write(data)
2651 io.stdout.write(data)
2651
2652
2652 # TODO: This should be removed when Term is refactored.
2653 # TODO: This should be removed when Term is refactored.
2653 def write_err(self,data):
2654 def write_err(self,data):
2654 """Write a string to the default error output"""
2655 """Write a string to the default error output"""
2655 io.stderr.write(data)
2656 io.stderr.write(data)
2656
2657
2657 def ask_yes_no(self, prompt, default=None):
2658 def ask_yes_no(self, prompt, default=None):
2658 if self.quiet:
2659 if self.quiet:
2659 return True
2660 return True
2660 return ask_yes_no(prompt,default)
2661 return ask_yes_no(prompt,default)
2661
2662
2662 def show_usage(self):
2663 def show_usage(self):
2663 """Show a usage message"""
2664 """Show a usage message"""
2664 page.page(IPython.core.usage.interactive_usage)
2665 page.page(IPython.core.usage.interactive_usage)
2665
2666
2666 def find_user_code(self, target, raw=True):
2667 def find_user_code(self, target, raw=True):
2667 """Get a code string from history, file, or a string or macro.
2668 """Get a code string from history, file, or a string or macro.
2668
2669
2669 This is mainly used by magic functions.
2670 This is mainly used by magic functions.
2670
2671
2671 Parameters
2672 Parameters
2672 ----------
2673 ----------
2673 target : str
2674 target : str
2674 A string specifying code to retrieve. This will be tried respectively
2675 A string specifying code to retrieve. This will be tried respectively
2675 as: ranges of input history (see %history for syntax), a filename, or
2676 as: ranges of input history (see %history for syntax), a filename, or
2676 an expression evaluating to a string or Macro in the user namespace.
2677 an expression evaluating to a string or Macro in the user namespace.
2677 raw : bool
2678 raw : bool
2678 If true (default), retrieve raw history. Has no effect on the other
2679 If true (default), retrieve raw history. Has no effect on the other
2679 retrieval mechanisms.
2680 retrieval mechanisms.
2680
2681
2681 Returns
2682 Returns
2682 -------
2683 -------
2683 A string of code.
2684 A string of code.
2684
2685
2685 ValueError is raised if nothing is found, and TypeError if it evaluates
2686 ValueError is raised if nothing is found, and TypeError if it evaluates
2686 to an object of another type. In each case, .args[0] is a printable
2687 to an object of another type. In each case, .args[0] is a printable
2687 message.
2688 message.
2688 """
2689 """
2689 code = self.extract_input_lines(target, raw=raw) # Grab history
2690 code = self.extract_input_lines(target, raw=raw) # Grab history
2690 if code:
2691 if code:
2691 return code
2692 return code
2692 if os.path.isfile(target): # Read file
2693 if os.path.isfile(target): # Read file
2693 return open(target, "r").read()
2694 return open(target, "r").read()
2694
2695
2695 try: # User namespace
2696 try: # User namespace
2696 codeobj = eval(target, self.user_ns)
2697 codeobj = eval(target, self.user_ns)
2697 except Exception:
2698 except Exception:
2698 raise ValueError(("'%s' was not found in history, as a file, nor in"
2699 raise ValueError(("'%s' was not found in history, as a file, nor in"
2699 " the user namespace.") % target)
2700 " the user namespace.") % target)
2700 if isinstance(codeobj, basestring):
2701 if isinstance(codeobj, basestring):
2701 return codeobj
2702 return codeobj
2702 elif isinstance(codeobj, Macro):
2703 elif isinstance(codeobj, Macro):
2703 return codeobj.value
2704 return codeobj.value
2704
2705
2705 raise TypeError("%s is neither a string nor a macro." % target,
2706 raise TypeError("%s is neither a string nor a macro." % target,
2706 codeobj)
2707 codeobj)
2707
2708
2708 #-------------------------------------------------------------------------
2709 #-------------------------------------------------------------------------
2709 # Things related to IPython exiting
2710 # Things related to IPython exiting
2710 #-------------------------------------------------------------------------
2711 #-------------------------------------------------------------------------
2711 def atexit_operations(self):
2712 def atexit_operations(self):
2712 """This will be executed at the time of exit.
2713 """This will be executed at the time of exit.
2713
2714
2714 Cleanup operations and saving of persistent data that is done
2715 Cleanup operations and saving of persistent data that is done
2715 unconditionally by IPython should be performed here.
2716 unconditionally by IPython should be performed here.
2716
2717
2717 For things that may depend on startup flags or platform specifics (such
2718 For things that may depend on startup flags or platform specifics (such
2718 as having readline or not), register a separate atexit function in the
2719 as having readline or not), register a separate atexit function in the
2719 code that has the appropriate information, rather than trying to
2720 code that has the appropriate information, rather than trying to
2720 clutter
2721 clutter
2721 """
2722 """
2722 # Close the history session (this stores the end time and line count)
2723 # Close the history session (this stores the end time and line count)
2723 # this must be *before* the tempfile cleanup, in case of temporary
2724 # this must be *before* the tempfile cleanup, in case of temporary
2724 # history db
2725 # history db
2725 self.history_manager.end_session()
2726 self.history_manager.end_session()
2726
2727
2727 # Cleanup all tempfiles left around
2728 # Cleanup all tempfiles left around
2728 for tfile in self.tempfiles:
2729 for tfile in self.tempfiles:
2729 try:
2730 try:
2730 os.unlink(tfile)
2731 os.unlink(tfile)
2731 except OSError:
2732 except OSError:
2732 pass
2733 pass
2733
2734
2734 # Clear all user namespaces to release all references cleanly.
2735 # Clear all user namespaces to release all references cleanly.
2735 self.reset(new_session=False)
2736 self.reset(new_session=False)
2736
2737
2737 # Run user hooks
2738 # Run user hooks
2738 self.hooks.shutdown_hook()
2739 self.hooks.shutdown_hook()
2739
2740
2740 def cleanup(self):
2741 def cleanup(self):
2741 self.restore_sys_module_state()
2742 self.restore_sys_module_state()
2742
2743
2743
2744
2744 class InteractiveShellABC(object):
2745 class InteractiveShellABC(object):
2745 """An abstract base class for InteractiveShell."""
2746 """An abstract base class for InteractiveShell."""
2746 __metaclass__ = abc.ABCMeta
2747 __metaclass__ = abc.ABCMeta
2747
2748
2748 InteractiveShellABC.register(InteractiveShell)
2749 InteractiveShellABC.register(InteractiveShell)
@@ -1,3700 +1,3757 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2011 The IPython Development Team
8 # Copyright (C) 2008-2011 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__ as builtin_mod
18 import __builtin__ as builtin_mod
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import imp
22 import imp
23 import os
23 import os
24 import sys
24 import sys
25 import shutil
25 import shutil
26 import re
26 import re
27 import time
27 import time
28 import gc
28 from StringIO import StringIO
29 from StringIO import StringIO
29 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
30 from pprint import pformat
31 from pprint import pformat
31 from xmlrpclib import ServerProxy
32 from xmlrpclib import ServerProxy
32
33
33 # cProfile was added in Python2.5
34 # cProfile was added in Python2.5
34 try:
35 try:
35 import cProfile as profile
36 import cProfile as profile
36 import pstats
37 import pstats
37 except ImportError:
38 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
39 try:
40 try:
40 import profile,pstats
41 import profile,pstats
41 except ImportError:
42 except ImportError:
42 profile = pstats = None
43 profile = pstats = None
43
44
44 import IPython
45 import IPython
45 from IPython.core import debugger, oinspect
46 from IPython.core import debugger, oinspect
46 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
47 from IPython.core.error import UsageError
48 from IPython.core.error import UsageError
48 from IPython.core.error import StdinNotImplementedError
49 from IPython.core.error import StdinNotImplementedError
49 from IPython.core.fakemodule import FakeModule
50 from IPython.core.fakemodule import FakeModule
50 from IPython.core.profiledir import ProfileDir
51 from IPython.core.profiledir import ProfileDir
51 from IPython.core.macro import Macro
52 from IPython.core.macro import Macro
52 from IPython.core import magic_arguments, page
53 from IPython.core import magic_arguments, page
53 from IPython.core.prefilter import ESC_MAGIC
54 from IPython.core.prefilter import ESC_MAGIC
54 from IPython.core.pylabtools import mpl_runner
55 from IPython.core.pylabtools import mpl_runner
55 from IPython.testing.skipdoctest import skip_doctest
56 from IPython.testing.skipdoctest import skip_doctest
56 from IPython.utils import py3compat
57 from IPython.utils import py3compat
57 from IPython.utils.io import file_read, nlprint
58 from IPython.utils.io import file_read, nlprint
58 from IPython.utils.module_paths import find_mod
59 from IPython.utils.module_paths import find_mod
59 from IPython.utils.path import get_py_filename, unquote_filename
60 from IPython.utils.path import get_py_filename, unquote_filename
60 from IPython.utils.process import arg_split, abbrev_cwd
61 from IPython.utils.process import arg_split, abbrev_cwd
61 from IPython.utils.terminal import set_term_title
62 from IPython.utils.terminal import set_term_title
62 from IPython.utils.text import LSString, SList, format_screen
63 from IPython.utils.text import LSString, SList, format_screen
63 from IPython.utils.timing import clock, clock2
64 from IPython.utils.timing import clock, clock2
64 from IPython.utils.warn import warn, error
65 from IPython.utils.warn import warn, error
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
66 from IPython.config.application import Application
67 from IPython.config.application import Application
67
68
68 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
69 # Utility functions
70 # Utility functions
70 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
71
72
72 def on_off(tag):
73 def on_off(tag):
73 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
74 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
74 return ['OFF','ON'][tag]
75 return ['OFF','ON'][tag]
75
76
76 class Bunch: pass
77 class Bunch: pass
77
78
78 def compress_dhist(dh):
79 def compress_dhist(dh):
79 head, tail = dh[:-10], dh[-10:]
80 head, tail = dh[:-10], dh[-10:]
80
81
81 newhead = []
82 newhead = []
82 done = set()
83 done = set()
83 for h in head:
84 for h in head:
84 if h in done:
85 if h in done:
85 continue
86 continue
86 newhead.append(h)
87 newhead.append(h)
87 done.add(h)
88 done.add(h)
88
89
89 return newhead + tail
90 return newhead + tail
90
91
91 def needs_local_scope(func):
92 def needs_local_scope(func):
92 """Decorator to mark magic functions which need to local scope to run."""
93 """Decorator to mark magic functions which need to local scope to run."""
93 func.needs_local_scope = True
94 func.needs_local_scope = True
94 return func
95 return func
95
96
96
97
97 # Used for exception handling in magic_edit
98 # Used for exception handling in magic_edit
98 class MacroToEdit(ValueError): pass
99 class MacroToEdit(ValueError): pass
99
100
100 # Taken from PEP 263, this is the official encoding regexp.
101 # Taken from PEP 263, this is the official encoding regexp.
101 _encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
102 _encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
102
103
103 #***************************************************************************
104 #***************************************************************************
104 # Main class implementing Magic functionality
105 # Main class implementing Magic functionality
105
106
106 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
107 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
107 # on construction of the main InteractiveShell object. Something odd is going
108 # on construction of the main InteractiveShell object. Something odd is going
108 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
109 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
109 # eventually this needs to be clarified.
110 # eventually this needs to be clarified.
110 # BG: This is because InteractiveShell inherits from this, but is itself a
111 # BG: This is because InteractiveShell inherits from this, but is itself a
111 # Configurable. This messes up the MRO in some way. The fix is that we need to
112 # Configurable. This messes up the MRO in some way. The fix is that we need to
112 # make Magic a configurable that InteractiveShell does not subclass.
113 # make Magic a configurable that InteractiveShell does not subclass.
113
114
114 class Magic:
115 class Magic:
115 """Magic functions for InteractiveShell.
116 """Magic functions for InteractiveShell.
116
117
117 Shell functions which can be reached as %function_name. All magic
118 Shell functions which can be reached as %function_name. All magic
118 functions should accept a string, which they can parse for their own
119 functions should accept a string, which they can parse for their own
119 needs. This can make some functions easier to type, eg `%cd ../`
120 needs. This can make some functions easier to type, eg `%cd ../`
120 vs. `%cd("../")`
121 vs. `%cd("../")`
121
122
122 ALL definitions MUST begin with the prefix magic_. The user won't need it
123 ALL definitions MUST begin with the prefix magic_. The user won't need it
123 at the command line, but it is is needed in the definition. """
124 at the command line, but it is is needed in the definition. """
124
125
125 # class globals
126 # class globals
126 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
127 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
127 'Automagic is ON, % prefix NOT needed for magic functions.']
128 'Automagic is ON, % prefix NOT needed for magic functions.']
128
129
129
130
130 configurables = None
131 configurables = None
131 #......................................................................
132 #......................................................................
132 # some utility functions
133 # some utility functions
133
134
134 def __init__(self,shell):
135 def __init__(self,shell):
135
136
136 self.options_table = {}
137 self.options_table = {}
137 if profile is None:
138 if profile is None:
138 self.magic_prun = self.profile_missing_notice
139 self.magic_prun = self.profile_missing_notice
139 self.shell = shell
140 self.shell = shell
140 if self.configurables is None:
141 if self.configurables is None:
141 self.configurables = []
142 self.configurables = []
142
143
143 # namespace for holding state we may need
144 # namespace for holding state we may need
144 self._magic_state = Bunch()
145 self._magic_state = Bunch()
145
146
146 def profile_missing_notice(self, *args, **kwargs):
147 def profile_missing_notice(self, *args, **kwargs):
147 error("""\
148 error("""\
148 The profile module could not be found. It has been removed from the standard
149 The profile module could not be found. It has been removed from the standard
149 python packages because of its non-free license. To use profiling, install the
150 python packages because of its non-free license. To use profiling, install the
150 python-profiler package from non-free.""")
151 python-profiler package from non-free.""")
151
152
152 def default_option(self,fn,optstr):
153 def default_option(self,fn,optstr):
153 """Make an entry in the options_table for fn, with value optstr"""
154 """Make an entry in the options_table for fn, with value optstr"""
154
155
155 if fn not in self.lsmagic():
156 if fn not in self.lsmagic():
156 error("%s is not a magic function" % fn)
157 error("%s is not a magic function" % fn)
157 self.options_table[fn] = optstr
158 self.options_table[fn] = optstr
158
159
159 def lsmagic(self):
160 def lsmagic(self):
160 """Return a list of currently available magic functions.
161 """Return a list of currently available magic functions.
161
162
162 Gives a list of the bare names after mangling (['ls','cd', ...], not
163 Gives a list of the bare names after mangling (['ls','cd', ...], not
163 ['magic_ls','magic_cd',...]"""
164 ['magic_ls','magic_cd',...]"""
164
165
165 # FIXME. This needs a cleanup, in the way the magics list is built.
166 # FIXME. This needs a cleanup, in the way the magics list is built.
166
167
167 # magics in class definition
168 # magics in class definition
168 class_magic = lambda fn: fn.startswith('magic_') and \
169 class_magic = lambda fn: fn.startswith('magic_') and \
169 callable(Magic.__dict__[fn])
170 callable(Magic.__dict__[fn])
170 # in instance namespace (run-time user additions)
171 # in instance namespace (run-time user additions)
171 inst_magic = lambda fn: fn.startswith('magic_') and \
172 inst_magic = lambda fn: fn.startswith('magic_') and \
172 callable(self.__dict__[fn])
173 callable(self.__dict__[fn])
173 # and bound magics by user (so they can access self):
174 # and bound magics by user (so they can access self):
174 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
175 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
175 callable(self.__class__.__dict__[fn])
176 callable(self.__class__.__dict__[fn])
176 magics = filter(class_magic,Magic.__dict__.keys()) + \
177 magics = filter(class_magic,Magic.__dict__.keys()) + \
177 filter(inst_magic,self.__dict__.keys()) + \
178 filter(inst_magic,self.__dict__.keys()) + \
178 filter(inst_bound_magic,self.__class__.__dict__.keys())
179 filter(inst_bound_magic,self.__class__.__dict__.keys())
179 out = []
180 out = []
180 for fn in set(magics):
181 for fn in set(magics):
181 out.append(fn.replace('magic_','',1))
182 out.append(fn.replace('magic_','',1))
182 out.sort()
183 out.sort()
183 return out
184 return out
184
185
185 def extract_input_lines(self, range_str, raw=False):
186 def extract_input_lines(self, range_str, raw=False):
186 """Return as a string a set of input history slices.
187 """Return as a string a set of input history slices.
187
188
188 Inputs:
189 Inputs:
189
190
190 - range_str: the set of slices is given as a string, like
191 - range_str: the set of slices is given as a string, like
191 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
192 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
192 which get their arguments as strings. The number before the / is the
193 which get their arguments as strings. The number before the / is the
193 session number: ~n goes n back from the current session.
194 session number: ~n goes n back from the current session.
194
195
195 Optional inputs:
196 Optional inputs:
196
197
197 - raw(False): by default, the processed input is used. If this is
198 - raw(False): by default, the processed input is used. If this is
198 true, the raw input history is used instead.
199 true, the raw input history is used instead.
199
200
200 Note that slices can be called with two notations:
201 Note that slices can be called with two notations:
201
202
202 N:M -> standard python form, means including items N...(M-1).
203 N:M -> standard python form, means including items N...(M-1).
203
204
204 N-M -> include items N..M (closed endpoint)."""
205 N-M -> include items N..M (closed endpoint)."""
205 lines = self.shell.history_manager.\
206 lines = self.shell.history_manager.\
206 get_range_by_str(range_str, raw=raw)
207 get_range_by_str(range_str, raw=raw)
207 return "\n".join(x for _, _, x in lines)
208 return "\n".join(x for _, _, x in lines)
208
209
209 def arg_err(self,func):
210 def arg_err(self,func):
210 """Print docstring if incorrect arguments were passed"""
211 """Print docstring if incorrect arguments were passed"""
211 print 'Error in arguments:'
212 print 'Error in arguments:'
212 print oinspect.getdoc(func)
213 print oinspect.getdoc(func)
213
214
214 def format_latex(self,strng):
215 def format_latex(self,strng):
215 """Format a string for latex inclusion."""
216 """Format a string for latex inclusion."""
216
217
217 # Characters that need to be escaped for latex:
218 # Characters that need to be escaped for latex:
218 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
219 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
219 # Magic command names as headers:
220 # Magic command names as headers:
220 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
221 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
221 re.MULTILINE)
222 re.MULTILINE)
222 # Magic commands
223 # Magic commands
223 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
224 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
224 re.MULTILINE)
225 re.MULTILINE)
225 # Paragraph continue
226 # Paragraph continue
226 par_re = re.compile(r'\\$',re.MULTILINE)
227 par_re = re.compile(r'\\$',re.MULTILINE)
227
228
228 # The "\n" symbol
229 # The "\n" symbol
229 newline_re = re.compile(r'\\n')
230 newline_re = re.compile(r'\\n')
230
231
231 # Now build the string for output:
232 # Now build the string for output:
232 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
233 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
233 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
234 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
234 strng)
235 strng)
235 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
236 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
236 strng = par_re.sub(r'\\\\',strng)
237 strng = par_re.sub(r'\\\\',strng)
237 strng = escape_re.sub(r'\\\1',strng)
238 strng = escape_re.sub(r'\\\1',strng)
238 strng = newline_re.sub(r'\\textbackslash{}n',strng)
239 strng = newline_re.sub(r'\\textbackslash{}n',strng)
239 return strng
240 return strng
240
241
241 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
242 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
242 """Parse options passed to an argument string.
243 """Parse options passed to an argument string.
243
244
244 The interface is similar to that of getopt(), but it returns back a
245 The interface is similar to that of getopt(), but it returns back a
245 Struct with the options as keys and the stripped argument string still
246 Struct with the options as keys and the stripped argument string still
246 as a string.
247 as a string.
247
248
248 arg_str is quoted as a true sys.argv vector by using shlex.split.
249 arg_str is quoted as a true sys.argv vector by using shlex.split.
249 This allows us to easily expand variables, glob files, quote
250 This allows us to easily expand variables, glob files, quote
250 arguments, etc.
251 arguments, etc.
251
252
252 Options:
253 Options:
253 -mode: default 'string'. If given as 'list', the argument string is
254 -mode: default 'string'. If given as 'list', the argument string is
254 returned as a list (split on whitespace) instead of a string.
255 returned as a list (split on whitespace) instead of a string.
255
256
256 -list_all: put all option values in lists. Normally only options
257 -list_all: put all option values in lists. Normally only options
257 appearing more than once are put in a list.
258 appearing more than once are put in a list.
258
259
259 -posix (True): whether to split the input line in POSIX mode or not,
260 -posix (True): whether to split the input line in POSIX mode or not,
260 as per the conventions outlined in the shlex module from the
261 as per the conventions outlined in the shlex module from the
261 standard library."""
262 standard library."""
262
263
263 # inject default options at the beginning of the input line
264 # inject default options at the beginning of the input line
264 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
265 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
265 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
266 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
266
267
267 mode = kw.get('mode','string')
268 mode = kw.get('mode','string')
268 if mode not in ['string','list']:
269 if mode not in ['string','list']:
269 raise ValueError,'incorrect mode given: %s' % mode
270 raise ValueError,'incorrect mode given: %s' % mode
270 # Get options
271 # Get options
271 list_all = kw.get('list_all',0)
272 list_all = kw.get('list_all',0)
272 posix = kw.get('posix', os.name == 'posix')
273 posix = kw.get('posix', os.name == 'posix')
273 strict = kw.get('strict', True)
274 strict = kw.get('strict', True)
274
275
275 # Check if we have more than one argument to warrant extra processing:
276 # Check if we have more than one argument to warrant extra processing:
276 odict = {} # Dictionary with options
277 odict = {} # Dictionary with options
277 args = arg_str.split()
278 args = arg_str.split()
278 if len(args) >= 1:
279 if len(args) >= 1:
279 # If the list of inputs only has 0 or 1 thing in it, there's no
280 # If the list of inputs only has 0 or 1 thing in it, there's no
280 # need to look for options
281 # need to look for options
281 argv = arg_split(arg_str, posix, strict)
282 argv = arg_split(arg_str, posix, strict)
282 # Do regular option processing
283 # Do regular option processing
283 try:
284 try:
284 opts,args = getopt(argv,opt_str,*long_opts)
285 opts,args = getopt(argv,opt_str,*long_opts)
285 except GetoptError,e:
286 except GetoptError,e:
286 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
287 " ".join(long_opts)))
288 " ".join(long_opts)))
288 for o,a in opts:
289 for o,a in opts:
289 if o.startswith('--'):
290 if o.startswith('--'):
290 o = o[2:]
291 o = o[2:]
291 else:
292 else:
292 o = o[1:]
293 o = o[1:]
293 try:
294 try:
294 odict[o].append(a)
295 odict[o].append(a)
295 except AttributeError:
296 except AttributeError:
296 odict[o] = [odict[o],a]
297 odict[o] = [odict[o],a]
297 except KeyError:
298 except KeyError:
298 if list_all:
299 if list_all:
299 odict[o] = [a]
300 odict[o] = [a]
300 else:
301 else:
301 odict[o] = a
302 odict[o] = a
302
303
303 # Prepare opts,args for return
304 # Prepare opts,args for return
304 opts = Struct(odict)
305 opts = Struct(odict)
305 if mode == 'string':
306 if mode == 'string':
306 args = ' '.join(args)
307 args = ' '.join(args)
307
308
308 return opts,args
309 return opts,args
309
310
310 #......................................................................
311 #......................................................................
311 # And now the actual magic functions
312 # And now the actual magic functions
312
313
313 # Functions for IPython shell work (vars,funcs, config, etc)
314 # Functions for IPython shell work (vars,funcs, config, etc)
314 def magic_lsmagic(self, parameter_s = ''):
315 def magic_lsmagic(self, parameter_s = ''):
315 """List currently available magic functions."""
316 """List currently available magic functions."""
316 mesc = ESC_MAGIC
317 mesc = ESC_MAGIC
317 print 'Available magic functions:\n'+mesc+\
318 print 'Available magic functions:\n'+mesc+\
318 (' '+mesc).join(self.lsmagic())
319 (' '+mesc).join(self.lsmagic())
319 print '\n' + Magic.auto_status[self.shell.automagic]
320 print '\n' + Magic.auto_status[self.shell.automagic]
320 return None
321 return None
321
322
322 def magic_magic(self, parameter_s = ''):
323 def magic_magic(self, parameter_s = ''):
323 """Print information about the magic function system.
324 """Print information about the magic function system.
324
325
325 Supported formats: -latex, -brief, -rest
326 Supported formats: -latex, -brief, -rest
326 """
327 """
327
328
328 mode = ''
329 mode = ''
329 try:
330 try:
330 if parameter_s.split()[0] == '-latex':
331 if parameter_s.split()[0] == '-latex':
331 mode = 'latex'
332 mode = 'latex'
332 if parameter_s.split()[0] == '-brief':
333 if parameter_s.split()[0] == '-brief':
333 mode = 'brief'
334 mode = 'brief'
334 if parameter_s.split()[0] == '-rest':
335 if parameter_s.split()[0] == '-rest':
335 mode = 'rest'
336 mode = 'rest'
336 rest_docs = []
337 rest_docs = []
337 except:
338 except:
338 pass
339 pass
339
340
340 magic_docs = []
341 magic_docs = []
341 for fname in self.lsmagic():
342 for fname in self.lsmagic():
342 mname = 'magic_' + fname
343 mname = 'magic_' + fname
343 for space in (Magic,self,self.__class__):
344 for space in (Magic,self,self.__class__):
344 try:
345 try:
345 fn = space.__dict__[mname]
346 fn = space.__dict__[mname]
346 except KeyError:
347 except KeyError:
347 pass
348 pass
348 else:
349 else:
349 break
350 break
350 if mode == 'brief':
351 if mode == 'brief':
351 # only first line
352 # only first line
352 if fn.__doc__:
353 if fn.__doc__:
353 fndoc = fn.__doc__.split('\n',1)[0]
354 fndoc = fn.__doc__.split('\n',1)[0]
354 else:
355 else:
355 fndoc = 'No documentation'
356 fndoc = 'No documentation'
356 else:
357 else:
357 if fn.__doc__:
358 if fn.__doc__:
358 fndoc = fn.__doc__.rstrip()
359 fndoc = fn.__doc__.rstrip()
359 else:
360 else:
360 fndoc = 'No documentation'
361 fndoc = 'No documentation'
361
362
362
363
363 if mode == 'rest':
364 if mode == 'rest':
364 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
365 fname,fndoc))
366 fname,fndoc))
366
367
367 else:
368 else:
368 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
369 fname,fndoc))
370 fname,fndoc))
370
371
371 magic_docs = ''.join(magic_docs)
372 magic_docs = ''.join(magic_docs)
372
373
373 if mode == 'rest':
374 if mode == 'rest':
374 return "".join(rest_docs)
375 return "".join(rest_docs)
375
376
376 if mode == 'latex':
377 if mode == 'latex':
377 print self.format_latex(magic_docs)
378 print self.format_latex(magic_docs)
378 return
379 return
379 else:
380 else:
380 magic_docs = format_screen(magic_docs)
381 magic_docs = format_screen(magic_docs)
381 if mode == 'brief':
382 if mode == 'brief':
382 return magic_docs
383 return magic_docs
383
384
384 outmsg = """
385 outmsg = """
385 IPython's 'magic' functions
386 IPython's 'magic' functions
386 ===========================
387 ===========================
387
388
388 The magic function system provides a series of functions which allow you to
389 The magic function system provides a series of functions which allow you to
389 control the behavior of IPython itself, plus a lot of system-type
390 control the behavior of IPython itself, plus a lot of system-type
390 features. All these functions are prefixed with a % character, but parameters
391 features. All these functions are prefixed with a % character, but parameters
391 are given without parentheses or quotes.
392 are given without parentheses or quotes.
392
393
393 NOTE: If you have 'automagic' enabled (via the command line option or with the
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
394 %automagic function), you don't need to type in the % explicitly. By default,
395 %automagic function), you don't need to type in the % explicitly. By default,
395 IPython ships with automagic on, so you should only rarely need the % escape.
396 IPython ships with automagic on, so you should only rarely need the % escape.
396
397
397 Example: typing '%cd mydir' (without the quotes) changes you working directory
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
398 to 'mydir', if it exists.
399 to 'mydir', if it exists.
399
400
400 For a list of the available magic functions, use %lsmagic. For a description
401 For a list of the available magic functions, use %lsmagic. For a description
401 of any of them, type %magic_name?, e.g. '%cd?'.
402 of any of them, type %magic_name?, e.g. '%cd?'.
402
403
403 Currently the magic system has the following functions:\n"""
404 Currently the magic system has the following functions:\n"""
404
405
405 mesc = ESC_MAGIC
406 mesc = ESC_MAGIC
406 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
407 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
407 "\n\n%s%s\n\n%s" % (outmsg,
408 "\n\n%s%s\n\n%s" % (outmsg,
408 magic_docs,mesc,mesc,
409 magic_docs,mesc,mesc,
409 (' '+mesc).join(self.lsmagic()),
410 (' '+mesc).join(self.lsmagic()),
410 Magic.auto_status[self.shell.automagic] ) )
411 Magic.auto_status[self.shell.automagic] ) )
411 page.page(outmsg)
412 page.page(outmsg)
412
413
413 def magic_automagic(self, parameter_s = ''):
414 def magic_automagic(self, parameter_s = ''):
414 """Make magic functions callable without having to type the initial %.
415 """Make magic functions callable without having to type the initial %.
415
416
416 Without argumentsl toggles on/off (when off, you must call it as
417 Without argumentsl toggles on/off (when off, you must call it as
417 %automagic, of course). With arguments it sets the value, and you can
418 %automagic, of course). With arguments it sets the value, and you can
418 use any of (case insensitive):
419 use any of (case insensitive):
419
420
420 - on,1,True: to activate
421 - on,1,True: to activate
421
422
422 - off,0,False: to deactivate.
423 - off,0,False: to deactivate.
423
424
424 Note that magic functions have lowest priority, so if there's a
425 Note that magic functions have lowest priority, so if there's a
425 variable whose name collides with that of a magic fn, automagic won't
426 variable whose name collides with that of a magic fn, automagic won't
426 work for that function (you get the variable instead). However, if you
427 work for that function (you get the variable instead). However, if you
427 delete the variable (del var), the previously shadowed magic function
428 delete the variable (del var), the previously shadowed magic function
428 becomes visible to automagic again."""
429 becomes visible to automagic again."""
429
430
430 arg = parameter_s.lower()
431 arg = parameter_s.lower()
431 if parameter_s in ('on','1','true'):
432 if parameter_s in ('on','1','true'):
432 self.shell.automagic = True
433 self.shell.automagic = True
433 elif parameter_s in ('off','0','false'):
434 elif parameter_s in ('off','0','false'):
434 self.shell.automagic = False
435 self.shell.automagic = False
435 else:
436 else:
436 self.shell.automagic = not self.shell.automagic
437 self.shell.automagic = not self.shell.automagic
437 print '\n' + Magic.auto_status[self.shell.automagic]
438 print '\n' + Magic.auto_status[self.shell.automagic]
438
439
439 @skip_doctest
440 @skip_doctest
440 def magic_autocall(self, parameter_s = ''):
441 def magic_autocall(self, parameter_s = ''):
441 """Make functions callable without having to type parentheses.
442 """Make functions callable without having to type parentheses.
442
443
443 Usage:
444 Usage:
444
445
445 %autocall [mode]
446 %autocall [mode]
446
447
447 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
448 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
448 value is toggled on and off (remembering the previous state).
449 value is toggled on and off (remembering the previous state).
449
450
450 In more detail, these values mean:
451 In more detail, these values mean:
451
452
452 0 -> fully disabled
453 0 -> fully disabled
453
454
454 1 -> active, but do not apply if there are no arguments on the line.
455 1 -> active, but do not apply if there are no arguments on the line.
455
456
456 In this mode, you get:
457 In this mode, you get:
457
458
458 In [1]: callable
459 In [1]: callable
459 Out[1]: <built-in function callable>
460 Out[1]: <built-in function callable>
460
461
461 In [2]: callable 'hello'
462 In [2]: callable 'hello'
462 ------> callable('hello')
463 ------> callable('hello')
463 Out[2]: False
464 Out[2]: False
464
465
465 2 -> Active always. Even if no arguments are present, the callable
466 2 -> Active always. Even if no arguments are present, the callable
466 object is called:
467 object is called:
467
468
468 In [2]: float
469 In [2]: float
469 ------> float()
470 ------> float()
470 Out[2]: 0.0
471 Out[2]: 0.0
471
472
472 Note that even with autocall off, you can still use '/' at the start of
473 Note that even with autocall off, you can still use '/' at the start of
473 a line to treat the first argument on the command line as a function
474 a line to treat the first argument on the command line as a function
474 and add parentheses to it:
475 and add parentheses to it:
475
476
476 In [8]: /str 43
477 In [8]: /str 43
477 ------> str(43)
478 ------> str(43)
478 Out[8]: '43'
479 Out[8]: '43'
479
480
480 # all-random (note for auto-testing)
481 # all-random (note for auto-testing)
481 """
482 """
482
483
483 if parameter_s:
484 if parameter_s:
484 arg = int(parameter_s)
485 arg = int(parameter_s)
485 else:
486 else:
486 arg = 'toggle'
487 arg = 'toggle'
487
488
488 if not arg in (0,1,2,'toggle'):
489 if not arg in (0,1,2,'toggle'):
489 error('Valid modes: (0->Off, 1->Smart, 2->Full')
490 error('Valid modes: (0->Off, 1->Smart, 2->Full')
490 return
491 return
491
492
492 if arg in (0,1,2):
493 if arg in (0,1,2):
493 self.shell.autocall = arg
494 self.shell.autocall = arg
494 else: # toggle
495 else: # toggle
495 if self.shell.autocall:
496 if self.shell.autocall:
496 self._magic_state.autocall_save = self.shell.autocall
497 self._magic_state.autocall_save = self.shell.autocall
497 self.shell.autocall = 0
498 self.shell.autocall = 0
498 else:
499 else:
499 try:
500 try:
500 self.shell.autocall = self._magic_state.autocall_save
501 self.shell.autocall = self._magic_state.autocall_save
501 except AttributeError:
502 except AttributeError:
502 self.shell.autocall = self._magic_state.autocall_save = 1
503 self.shell.autocall = self._magic_state.autocall_save = 1
503
504
504 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
505 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
505
506
506
507
507 def magic_page(self, parameter_s=''):
508 def magic_page(self, parameter_s=''):
508 """Pretty print the object and display it through a pager.
509 """Pretty print the object and display it through a pager.
509
510
510 %page [options] OBJECT
511 %page [options] OBJECT
511
512
512 If no object is given, use _ (last output).
513 If no object is given, use _ (last output).
513
514
514 Options:
515 Options:
515
516
516 -r: page str(object), don't pretty-print it."""
517 -r: page str(object), don't pretty-print it."""
517
518
518 # After a function contributed by Olivier Aubert, slightly modified.
519 # After a function contributed by Olivier Aubert, slightly modified.
519
520
520 # Process options/args
521 # Process options/args
521 opts,args = self.parse_options(parameter_s,'r')
522 opts,args = self.parse_options(parameter_s,'r')
522 raw = 'r' in opts
523 raw = 'r' in opts
523
524
524 oname = args and args or '_'
525 oname = args and args or '_'
525 info = self._ofind(oname)
526 info = self._ofind(oname)
526 if info['found']:
527 if info['found']:
527 txt = (raw and str or pformat)( info['obj'] )
528 txt = (raw and str or pformat)( info['obj'] )
528 page.page(txt)
529 page.page(txt)
529 else:
530 else:
530 print 'Object `%s` not found' % oname
531 print 'Object `%s` not found' % oname
531
532
532 def magic_profile(self, parameter_s=''):
533 def magic_profile(self, parameter_s=''):
533 """Print your currently active IPython profile."""
534 """Print your currently active IPython profile."""
534 from IPython.core.application import BaseIPythonApplication
535 from IPython.core.application import BaseIPythonApplication
535 if BaseIPythonApplication.initialized():
536 if BaseIPythonApplication.initialized():
536 print BaseIPythonApplication.instance().profile
537 print BaseIPythonApplication.instance().profile
537 else:
538 else:
538 error("profile is an application-level value, but you don't appear to be in an IPython application")
539 error("profile is an application-level value, but you don't appear to be in an IPython application")
539
540
540 def magic_pinfo(self, parameter_s='', namespaces=None):
541 def magic_pinfo(self, parameter_s='', namespaces=None):
541 """Provide detailed information about an object.
542 """Provide detailed information about an object.
542
543
543 '%pinfo object' is just a synonym for object? or ?object."""
544 '%pinfo object' is just a synonym for object? or ?object."""
544
545
545 #print 'pinfo par: <%s>' % parameter_s # dbg
546 #print 'pinfo par: <%s>' % parameter_s # dbg
546
547
547
548
548 # detail_level: 0 -> obj? , 1 -> obj??
549 # detail_level: 0 -> obj? , 1 -> obj??
549 detail_level = 0
550 detail_level = 0
550 # We need to detect if we got called as 'pinfo pinfo foo', which can
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
551 # happen if the user types 'pinfo foo?' at the cmd line.
552 # happen if the user types 'pinfo foo?' at the cmd line.
552 pinfo,qmark1,oname,qmark2 = \
553 pinfo,qmark1,oname,qmark2 = \
553 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
554 if pinfo or qmark1 or qmark2:
555 if pinfo or qmark1 or qmark2:
555 detail_level = 1
556 detail_level = 1
556 if "*" in oname:
557 if "*" in oname:
557 self.magic_psearch(oname)
558 self.magic_psearch(oname)
558 else:
559 else:
559 self.shell._inspect('pinfo', oname, detail_level=detail_level,
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
560 namespaces=namespaces)
561 namespaces=namespaces)
561
562
562 def magic_pinfo2(self, parameter_s='', namespaces=None):
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
563 """Provide extra detailed information about an object.
564 """Provide extra detailed information about an object.
564
565
565 '%pinfo2 object' is just a synonym for object?? or ??object."""
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
566 self.shell._inspect('pinfo', parameter_s, detail_level=1,
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
567 namespaces=namespaces)
568 namespaces=namespaces)
568
569
569 @skip_doctest
570 @skip_doctest
570 def magic_pdef(self, parameter_s='', namespaces=None):
571 def magic_pdef(self, parameter_s='', namespaces=None):
571 """Print the definition header for any callable object.
572 """Print the definition header for any callable object.
572
573
573 If the object is a class, print the constructor information.
574 If the object is a class, print the constructor information.
574
575
575 Examples
576 Examples
576 --------
577 --------
577 ::
578 ::
578
579
579 In [3]: %pdef urllib.urlopen
580 In [3]: %pdef urllib.urlopen
580 urllib.urlopen(url, data=None, proxies=None)
581 urllib.urlopen(url, data=None, proxies=None)
581 """
582 """
582 self._inspect('pdef',parameter_s, namespaces)
583 self._inspect('pdef',parameter_s, namespaces)
583
584
584 def magic_pdoc(self, parameter_s='', namespaces=None):
585 def magic_pdoc(self, parameter_s='', namespaces=None):
585 """Print the docstring for an object.
586 """Print the docstring for an object.
586
587
587 If the given object is a class, it will print both the class and the
588 If the given object is a class, it will print both the class and the
588 constructor docstrings."""
589 constructor docstrings."""
589 self._inspect('pdoc',parameter_s, namespaces)
590 self._inspect('pdoc',parameter_s, namespaces)
590
591
591 def magic_psource(self, parameter_s='', namespaces=None):
592 def magic_psource(self, parameter_s='', namespaces=None):
592 """Print (or run through pager) the source code for an object."""
593 """Print (or run through pager) the source code for an object."""
593 self._inspect('psource',parameter_s, namespaces)
594 self._inspect('psource',parameter_s, namespaces)
594
595
595 def magic_pfile(self, parameter_s=''):
596 def magic_pfile(self, parameter_s=''):
596 """Print (or run through pager) the file where an object is defined.
597 """Print (or run through pager) the file where an object is defined.
597
598
598 The file opens at the line where the object definition begins. IPython
599 The file opens at the line where the object definition begins. IPython
599 will honor the environment variable PAGER if set, and otherwise will
600 will honor the environment variable PAGER if set, and otherwise will
600 do its best to print the file in a convenient form.
601 do its best to print the file in a convenient form.
601
602
602 If the given argument is not an object currently defined, IPython will
603 If the given argument is not an object currently defined, IPython will
603 try to interpret it as a filename (automatically adding a .py extension
604 try to interpret it as a filename (automatically adding a .py extension
604 if needed). You can thus use %pfile as a syntax highlighting code
605 if needed). You can thus use %pfile as a syntax highlighting code
605 viewer."""
606 viewer."""
606
607
607 # first interpret argument as an object name
608 # first interpret argument as an object name
608 out = self._inspect('pfile',parameter_s)
609 out = self._inspect('pfile',parameter_s)
609 # if not, try the input as a filename
610 # if not, try the input as a filename
610 if out == 'not found':
611 if out == 'not found':
611 try:
612 try:
612 filename = get_py_filename(parameter_s)
613 filename = get_py_filename(parameter_s)
613 except IOError,msg:
614 except IOError,msg:
614 print msg
615 print msg
615 return
616 return
616 page.page(self.shell.inspector.format(file(filename).read()))
617 page.page(self.shell.inspector.format(file(filename).read()))
617
618
618 def magic_psearch(self, parameter_s=''):
619 def magic_psearch(self, parameter_s=''):
619 """Search for object in namespaces by wildcard.
620 """Search for object in namespaces by wildcard.
620
621
621 %psearch [options] PATTERN [OBJECT TYPE]
622 %psearch [options] PATTERN [OBJECT TYPE]
622
623
623 Note: ? can be used as a synonym for %psearch, at the beginning or at
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
624 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
625 rest of the command line must be unchanged (options come first), so
626 rest of the command line must be unchanged (options come first), so
626 for example the following forms are equivalent
627 for example the following forms are equivalent
627
628
628 %psearch -i a* function
629 %psearch -i a* function
629 -i a* function?
630 -i a* function?
630 ?-i a* function
631 ?-i a* function
631
632
632 Arguments:
633 Arguments:
633
634
634 PATTERN
635 PATTERN
635
636
636 where PATTERN is a string containing * as a wildcard similar to its
637 where PATTERN is a string containing * as a wildcard similar to its
637 use in a shell. The pattern is matched in all namespaces on the
638 use in a shell. The pattern is matched in all namespaces on the
638 search path. By default objects starting with a single _ are not
639 search path. By default objects starting with a single _ are not
639 matched, many IPython generated objects have a single
640 matched, many IPython generated objects have a single
640 underscore. The default is case insensitive matching. Matching is
641 underscore. The default is case insensitive matching. Matching is
641 also done on the attributes of objects and not only on the objects
642 also done on the attributes of objects and not only on the objects
642 in a module.
643 in a module.
643
644
644 [OBJECT TYPE]
645 [OBJECT TYPE]
645
646
646 Is the name of a python type from the types module. The name is
647 Is the name of a python type from the types module. The name is
647 given in lowercase without the ending type, ex. StringType is
648 given in lowercase without the ending type, ex. StringType is
648 written string. By adding a type here only objects matching the
649 written string. By adding a type here only objects matching the
649 given type are matched. Using all here makes the pattern match all
650 given type are matched. Using all here makes the pattern match all
650 types (this is the default).
651 types (this is the default).
651
652
652 Options:
653 Options:
653
654
654 -a: makes the pattern match even objects whose names start with a
655 -a: makes the pattern match even objects whose names start with a
655 single underscore. These names are normally omitted from the
656 single underscore. These names are normally omitted from the
656 search.
657 search.
657
658
658 -i/-c: make the pattern case insensitive/sensitive. If neither of
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
659 these options are given, the default is read from your configuration
660 these options are given, the default is read from your configuration
660 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
661 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
661 If this option is not specified in your configuration file, IPython's
662 If this option is not specified in your configuration file, IPython's
662 internal default is to do a case sensitive search.
663 internal default is to do a case sensitive search.
663
664
664 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
665 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
665 specify can be searched in any of the following namespaces:
666 specify can be searched in any of the following namespaces:
666 'builtin', 'user', 'user_global','internal', 'alias', where
667 'builtin', 'user', 'user_global','internal', 'alias', where
667 'builtin' and 'user' are the search defaults. Note that you should
668 'builtin' and 'user' are the search defaults. Note that you should
668 not use quotes when specifying namespaces.
669 not use quotes when specifying namespaces.
669
670
670 'Builtin' contains the python module builtin, 'user' contains all
671 'Builtin' contains the python module builtin, 'user' contains all
671 user data, 'alias' only contain the shell aliases and no python
672 user data, 'alias' only contain the shell aliases and no python
672 objects, 'internal' contains objects used by IPython. The
673 objects, 'internal' contains objects used by IPython. The
673 'user_global' namespace is only used by embedded IPython instances,
674 'user_global' namespace is only used by embedded IPython instances,
674 and it contains module-level globals. You can add namespaces to the
675 and it contains module-level globals. You can add namespaces to the
675 search with -s or exclude them with -e (these options can be given
676 search with -s or exclude them with -e (these options can be given
676 more than once).
677 more than once).
677
678
678 Examples:
679 Examples:
679
680
680 %psearch a* -> objects beginning with an a
681 %psearch a* -> objects beginning with an a
681 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
682 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
682 %psearch a* function -> all functions beginning with an a
683 %psearch a* function -> all functions beginning with an a
683 %psearch re.e* -> objects beginning with an e in module re
684 %psearch re.e* -> objects beginning with an e in module re
684 %psearch r*.e* -> objects that start with e in modules starting in r
685 %psearch r*.e* -> objects that start with e in modules starting in r
685 %psearch r*.* string -> all strings in modules beginning with r
686 %psearch r*.* string -> all strings in modules beginning with r
686
687
687 Case sensitive search:
688 Case sensitive search:
688
689
689 %psearch -c a* list all object beginning with lower case a
690 %psearch -c a* list all object beginning with lower case a
690
691
691 Show objects beginning with a single _:
692 Show objects beginning with a single _:
692
693
693 %psearch -a _* list objects beginning with a single underscore"""
694 %psearch -a _* list objects beginning with a single underscore"""
694 try:
695 try:
695 parameter_s.encode('ascii')
696 parameter_s.encode('ascii')
696 except UnicodeEncodeError:
697 except UnicodeEncodeError:
697 print 'Python identifiers can only contain ascii characters.'
698 print 'Python identifiers can only contain ascii characters.'
698 return
699 return
699
700
700 # default namespaces to be searched
701 # default namespaces to be searched
701 def_search = ['user_local', 'user_global', 'builtin']
702 def_search = ['user_local', 'user_global', 'builtin']
702
703
703 # Process options/args
704 # Process options/args
704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
705 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
705 opt = opts.get
706 opt = opts.get
706 shell = self.shell
707 shell = self.shell
707 psearch = shell.inspector.psearch
708 psearch = shell.inspector.psearch
708
709
709 # select case options
710 # select case options
710 if opts.has_key('i'):
711 if opts.has_key('i'):
711 ignore_case = True
712 ignore_case = True
712 elif opts.has_key('c'):
713 elif opts.has_key('c'):
713 ignore_case = False
714 ignore_case = False
714 else:
715 else:
715 ignore_case = not shell.wildcards_case_sensitive
716 ignore_case = not shell.wildcards_case_sensitive
716
717
717 # Build list of namespaces to search from user options
718 # Build list of namespaces to search from user options
718 def_search.extend(opt('s',[]))
719 def_search.extend(opt('s',[]))
719 ns_exclude = ns_exclude=opt('e',[])
720 ns_exclude = ns_exclude=opt('e',[])
720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
721 ns_search = [nm for nm in def_search if nm not in ns_exclude]
721
722
722 # Call the actual search
723 # Call the actual search
723 try:
724 try:
724 psearch(args,shell.ns_table,ns_search,
725 psearch(args,shell.ns_table,ns_search,
725 show_all=opt('a'),ignore_case=ignore_case)
726 show_all=opt('a'),ignore_case=ignore_case)
726 except:
727 except:
727 shell.showtraceback()
728 shell.showtraceback()
728
729
729 @skip_doctest
730 @skip_doctest
730 def magic_who_ls(self, parameter_s=''):
731 def magic_who_ls(self, parameter_s=''):
731 """Return a sorted list of all interactive variables.
732 """Return a sorted list of all interactive variables.
732
733
733 If arguments are given, only variables of types matching these
734 If arguments are given, only variables of types matching these
734 arguments are returned.
735 arguments are returned.
735
736
736 Examples
737 Examples
737 --------
738 --------
738
739
739 Define two variables and list them with who_ls::
740 Define two variables and list them with who_ls::
740
741
741 In [1]: alpha = 123
742 In [1]: alpha = 123
742
743
743 In [2]: beta = 'test'
744 In [2]: beta = 'test'
744
745
745 In [3]: %who_ls
746 In [3]: %who_ls
746 Out[3]: ['alpha', 'beta']
747 Out[3]: ['alpha', 'beta']
747
748
748 In [4]: %who_ls int
749 In [4]: %who_ls int
749 Out[4]: ['alpha']
750 Out[4]: ['alpha']
750
751
751 In [5]: %who_ls str
752 In [5]: %who_ls str
752 Out[5]: ['beta']
753 Out[5]: ['beta']
753 """
754 """
754
755
755 user_ns = self.shell.user_ns
756 user_ns = self.shell.user_ns
756 user_ns_hidden = self.shell.user_ns_hidden
757 user_ns_hidden = self.shell.user_ns_hidden
757 out = [ i for i in user_ns
758 out = [ i for i in user_ns
758 if not i.startswith('_') \
759 if not i.startswith('_') \
759 and not i in user_ns_hidden ]
760 and not i in user_ns_hidden ]
760
761
761 typelist = parameter_s.split()
762 typelist = parameter_s.split()
762 if typelist:
763 if typelist:
763 typeset = set(typelist)
764 typeset = set(typelist)
764 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
765 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
765
766
766 out.sort()
767 out.sort()
767 return out
768 return out
768
769
769 @skip_doctest
770 @skip_doctest
770 def magic_who(self, parameter_s=''):
771 def magic_who(self, parameter_s=''):
771 """Print all interactive variables, with some minimal formatting.
772 """Print all interactive variables, with some minimal formatting.
772
773
773 If any arguments are given, only variables whose type matches one of
774 If any arguments are given, only variables whose type matches one of
774 these are printed. For example:
775 these are printed. For example:
775
776
776 %who function str
777 %who function str
777
778
778 will only list functions and strings, excluding all other types of
779 will only list functions and strings, excluding all other types of
779 variables. To find the proper type names, simply use type(var) at a
780 variables. To find the proper type names, simply use type(var) at a
780 command line to see how python prints type names. For example:
781 command line to see how python prints type names. For example:
781
782
782 In [1]: type('hello')\\
783 In [1]: type('hello')\\
783 Out[1]: <type 'str'>
784 Out[1]: <type 'str'>
784
785
785 indicates that the type name for strings is 'str'.
786 indicates that the type name for strings is 'str'.
786
787
787 %who always excludes executed names loaded through your configuration
788 %who always excludes executed names loaded through your configuration
788 file and things which are internal to IPython.
789 file and things which are internal to IPython.
789
790
790 This is deliberate, as typically you may load many modules and the
791 This is deliberate, as typically you may load many modules and the
791 purpose of %who is to show you only what you've manually defined.
792 purpose of %who is to show you only what you've manually defined.
792
793
793 Examples
794 Examples
794 --------
795 --------
795
796
796 Define two variables and list them with who::
797 Define two variables and list them with who::
797
798
798 In [1]: alpha = 123
799 In [1]: alpha = 123
799
800
800 In [2]: beta = 'test'
801 In [2]: beta = 'test'
801
802
802 In [3]: %who
803 In [3]: %who
803 alpha beta
804 alpha beta
804
805
805 In [4]: %who int
806 In [4]: %who int
806 alpha
807 alpha
807
808
808 In [5]: %who str
809 In [5]: %who str
809 beta
810 beta
810 """
811 """
811
812
812 varlist = self.magic_who_ls(parameter_s)
813 varlist = self.magic_who_ls(parameter_s)
813 if not varlist:
814 if not varlist:
814 if parameter_s:
815 if parameter_s:
815 print 'No variables match your requested type.'
816 print 'No variables match your requested type.'
816 else:
817 else:
817 print 'Interactive namespace is empty.'
818 print 'Interactive namespace is empty.'
818 return
819 return
819
820
820 # if we have variables, move on...
821 # if we have variables, move on...
821 count = 0
822 count = 0
822 for i in varlist:
823 for i in varlist:
823 print i+'\t',
824 print i+'\t',
824 count += 1
825 count += 1
825 if count > 8:
826 if count > 8:
826 count = 0
827 count = 0
827 print
828 print
828 print
829 print
829
830
830 @skip_doctest
831 @skip_doctest
831 def magic_whos(self, parameter_s=''):
832 def magic_whos(self, parameter_s=''):
832 """Like %who, but gives some extra information about each variable.
833 """Like %who, but gives some extra information about each variable.
833
834
834 The same type filtering of %who can be applied here.
835 The same type filtering of %who can be applied here.
835
836
836 For all variables, the type is printed. Additionally it prints:
837 For all variables, the type is printed. Additionally it prints:
837
838
838 - For {},[],(): their length.
839 - For {},[],(): their length.
839
840
840 - For numpy arrays, a summary with shape, number of
841 - For numpy arrays, a summary with shape, number of
841 elements, typecode and size in memory.
842 elements, typecode and size in memory.
842
843
843 - Everything else: a string representation, snipping their middle if
844 - Everything else: a string representation, snipping their middle if
844 too long.
845 too long.
845
846
846 Examples
847 Examples
847 --------
848 --------
848
849
849 Define two variables and list them with whos::
850 Define two variables and list them with whos::
850
851
851 In [1]: alpha = 123
852 In [1]: alpha = 123
852
853
853 In [2]: beta = 'test'
854 In [2]: beta = 'test'
854
855
855 In [3]: %whos
856 In [3]: %whos
856 Variable Type Data/Info
857 Variable Type Data/Info
857 --------------------------------
858 --------------------------------
858 alpha int 123
859 alpha int 123
859 beta str test
860 beta str test
860 """
861 """
861
862
862 varnames = self.magic_who_ls(parameter_s)
863 varnames = self.magic_who_ls(parameter_s)
863 if not varnames:
864 if not varnames:
864 if parameter_s:
865 if parameter_s:
865 print 'No variables match your requested type.'
866 print 'No variables match your requested type.'
866 else:
867 else:
867 print 'Interactive namespace is empty.'
868 print 'Interactive namespace is empty.'
868 return
869 return
869
870
870 # if we have variables, move on...
871 # if we have variables, move on...
871
872
872 # for these types, show len() instead of data:
873 # for these types, show len() instead of data:
873 seq_types = ['dict', 'list', 'tuple']
874 seq_types = ['dict', 'list', 'tuple']
874
875
875 # for numpy arrays, display summary info
876 # for numpy arrays, display summary info
876 ndarray_type = None
877 ndarray_type = None
877 if 'numpy' in sys.modules:
878 if 'numpy' in sys.modules:
878 try:
879 try:
879 from numpy import ndarray
880 from numpy import ndarray
880 except ImportError:
881 except ImportError:
881 pass
882 pass
882 else:
883 else:
883 ndarray_type = ndarray.__name__
884 ndarray_type = ndarray.__name__
884
885
885 # Find all variable names and types so we can figure out column sizes
886 # Find all variable names and types so we can figure out column sizes
886 def get_vars(i):
887 def get_vars(i):
887 return self.shell.user_ns[i]
888 return self.shell.user_ns[i]
888
889
889 # some types are well known and can be shorter
890 # some types are well known and can be shorter
890 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
891 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
891 def type_name(v):
892 def type_name(v):
892 tn = type(v).__name__
893 tn = type(v).__name__
893 return abbrevs.get(tn,tn)
894 return abbrevs.get(tn,tn)
894
895
895 varlist = map(get_vars,varnames)
896 varlist = map(get_vars,varnames)
896
897
897 typelist = []
898 typelist = []
898 for vv in varlist:
899 for vv in varlist:
899 tt = type_name(vv)
900 tt = type_name(vv)
900
901
901 if tt=='instance':
902 if tt=='instance':
902 typelist.append( abbrevs.get(str(vv.__class__),
903 typelist.append( abbrevs.get(str(vv.__class__),
903 str(vv.__class__)))
904 str(vv.__class__)))
904 else:
905 else:
905 typelist.append(tt)
906 typelist.append(tt)
906
907
907 # column labels and # of spaces as separator
908 # column labels and # of spaces as separator
908 varlabel = 'Variable'
909 varlabel = 'Variable'
909 typelabel = 'Type'
910 typelabel = 'Type'
910 datalabel = 'Data/Info'
911 datalabel = 'Data/Info'
911 colsep = 3
912 colsep = 3
912 # variable format strings
913 # variable format strings
913 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
914 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
914 aformat = "%s: %s elems, type `%s`, %s bytes"
915 aformat = "%s: %s elems, type `%s`, %s bytes"
915 # find the size of the columns to format the output nicely
916 # find the size of the columns to format the output nicely
916 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
917 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
917 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
918 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
918 # table header
919 # table header
919 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
920 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
920 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
921 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
921 # and the table itself
922 # and the table itself
922 kb = 1024
923 kb = 1024
923 Mb = 1048576 # kb**2
924 Mb = 1048576 # kb**2
924 for vname,var,vtype in zip(varnames,varlist,typelist):
925 for vname,var,vtype in zip(varnames,varlist,typelist):
925 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
926 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
926 if vtype in seq_types:
927 if vtype in seq_types:
927 print "n="+str(len(var))
928 print "n="+str(len(var))
928 elif vtype == ndarray_type:
929 elif vtype == ndarray_type:
929 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
930 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
930 if vtype==ndarray_type:
931 if vtype==ndarray_type:
931 # numpy
932 # numpy
932 vsize = var.size
933 vsize = var.size
933 vbytes = vsize*var.itemsize
934 vbytes = vsize*var.itemsize
934 vdtype = var.dtype
935 vdtype = var.dtype
935 else:
936 else:
936 # Numeric
937 # Numeric
937 vsize = Numeric.size(var)
938 vsize = Numeric.size(var)
938 vbytes = vsize*var.itemsize()
939 vbytes = vsize*var.itemsize()
939 vdtype = var.typecode()
940 vdtype = var.typecode()
940
941
941 if vbytes < 100000:
942 if vbytes < 100000:
942 print aformat % (vshape,vsize,vdtype,vbytes)
943 print aformat % (vshape,vsize,vdtype,vbytes)
943 else:
944 else:
944 print aformat % (vshape,vsize,vdtype,vbytes),
945 print aformat % (vshape,vsize,vdtype,vbytes),
945 if vbytes < Mb:
946 if vbytes < Mb:
946 print '(%s kb)' % (vbytes/kb,)
947 print '(%s kb)' % (vbytes/kb,)
947 else:
948 else:
948 print '(%s Mb)' % (vbytes/Mb,)
949 print '(%s Mb)' % (vbytes/Mb,)
949 else:
950 else:
950 try:
951 try:
951 vstr = str(var)
952 vstr = str(var)
952 except UnicodeEncodeError:
953 except UnicodeEncodeError:
953 vstr = unicode(var).encode(sys.getdefaultencoding(),
954 vstr = unicode(var).encode(sys.getdefaultencoding(),
954 'backslashreplace')
955 'backslashreplace')
955 vstr = vstr.replace('\n','\\n')
956 vstr = vstr.replace('\n','\\n')
956 if len(vstr) < 50:
957 if len(vstr) < 50:
957 print vstr
958 print vstr
958 else:
959 else:
959 print vstr[:25] + "<...>" + vstr[-25:]
960 print vstr[:25] + "<...>" + vstr[-25:]
960
961
961 def magic_reset(self, parameter_s=''):
962 def magic_reset(self, parameter_s=''):
962 """Resets the namespace by removing all names defined by the user.
963 """Resets the namespace by removing all names defined by the user.
963
964
964 Parameters
965 Parameters
965 ----------
966 ----------
966 -f : force reset without asking for confirmation.
967 -f : force reset without asking for confirmation.
967
968
968 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
969 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
969 References to objects may be kept. By default (without this option),
970 References to objects may be kept. By default (without this option),
970 we do a 'hard' reset, giving you a new session and removing all
971 we do a 'hard' reset, giving you a new session and removing all
971 references to objects from the current session.
972 references to objects from the current session.
972
973
973 Examples
974 Examples
974 --------
975 --------
975 In [6]: a = 1
976 In [6]: a = 1
976
977
977 In [7]: a
978 In [7]: a
978 Out[7]: 1
979 Out[7]: 1
979
980
980 In [8]: 'a' in _ip.user_ns
981 In [8]: 'a' in _ip.user_ns
981 Out[8]: True
982 Out[8]: True
982
983
983 In [9]: %reset -f
984 In [9]: %reset -f
984
985
985 In [1]: 'a' in _ip.user_ns
986 In [1]: 'a' in _ip.user_ns
986 Out[1]: False
987 Out[1]: False
987
988
988 Notes
989 Notes
989 -----
990 -----
990 Calling this magic from clients that do not implement standard input,
991 Calling this magic from clients that do not implement standard input,
991 such as the ipython notebook interface, will reset the namespace
992 such as the ipython notebook interface, will reset the namespace
992 without confirmation.
993 without confirmation.
993 """
994 """
994 opts, args = self.parse_options(parameter_s,'sf')
995 opts, args = self.parse_options(parameter_s,'sf')
995 if 'f' in opts:
996 if 'f' in opts:
996 ans = True
997 ans = True
997 else:
998 else:
998 try:
999 try:
999 ans = self.shell.ask_yes_no(
1000 ans = self.shell.ask_yes_no(
1000 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1001 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1001 except StdinNotImplementedError:
1002 except StdinNotImplementedError:
1002 ans = True
1003 ans = True
1003 if not ans:
1004 if not ans:
1004 print 'Nothing done.'
1005 print 'Nothing done.'
1005 return
1006 return
1006
1007
1007 if 's' in opts: # Soft reset
1008 if 's' in opts: # Soft reset
1008 user_ns = self.shell.user_ns
1009 user_ns = self.shell.user_ns
1009 for i in self.magic_who_ls():
1010 for i in self.magic_who_ls():
1010 del(user_ns[i])
1011 del(user_ns[i])
1011
1012
1012 else: # Hard reset
1013 else: # Hard reset
1013 self.shell.reset(new_session = False)
1014 self.shell.reset(new_session = False)
1014
1015
1015
1016
1016
1017
1017 def magic_reset_selective(self, parameter_s=''):
1018 def magic_reset_selective(self, parameter_s=''):
1018 """Resets the namespace by removing names defined by the user.
1019 """Resets the namespace by removing names defined by the user.
1019
1020
1020 Input/Output history are left around in case you need them.
1021 Input/Output history are left around in case you need them.
1021
1022
1022 %reset_selective [-f] regex
1023 %reset_selective [-f] regex
1023
1024
1024 No action is taken if regex is not included
1025 No action is taken if regex is not included
1025
1026
1026 Options
1027 Options
1027 -f : force reset without asking for confirmation.
1028 -f : force reset without asking for confirmation.
1028
1029
1029 Examples
1030 Examples
1030 --------
1031 --------
1031
1032
1032 We first fully reset the namespace so your output looks identical to
1033 We first fully reset the namespace so your output looks identical to
1033 this example for pedagogical reasons; in practice you do not need a
1034 this example for pedagogical reasons; in practice you do not need a
1034 full reset.
1035 full reset.
1035
1036
1036 In [1]: %reset -f
1037 In [1]: %reset -f
1037
1038
1038 Now, with a clean namespace we can make a few variables and use
1039 Now, with a clean namespace we can make a few variables and use
1039 %reset_selective to only delete names that match our regexp:
1040 %reset_selective to only delete names that match our regexp:
1040
1041
1041 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1042 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1042
1043
1043 In [3]: who_ls
1044 In [3]: who_ls
1044 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1045 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1045
1046
1046 In [4]: %reset_selective -f b[2-3]m
1047 In [4]: %reset_selective -f b[2-3]m
1047
1048
1048 In [5]: who_ls
1049 In [5]: who_ls
1049 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1050 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1050
1051
1051 In [6]: %reset_selective -f d
1052 In [6]: %reset_selective -f d
1052
1053
1053 In [7]: who_ls
1054 In [7]: who_ls
1054 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1055 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1055
1056
1056 In [8]: %reset_selective -f c
1057 In [8]: %reset_selective -f c
1057
1058
1058 In [9]: who_ls
1059 In [9]: who_ls
1059 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1060 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1060
1061
1061 In [10]: %reset_selective -f b
1062 In [10]: %reset_selective -f b
1062
1063
1063 In [11]: who_ls
1064 In [11]: who_ls
1064 Out[11]: ['a']
1065 Out[11]: ['a']
1065
1066
1066 Notes
1067 Notes
1067 -----
1068 -----
1068 Calling this magic from clients that do not implement standard input,
1069 Calling this magic from clients that do not implement standard input,
1069 such as the ipython notebook interface, will reset the namespace
1070 such as the ipython notebook interface, will reset the namespace
1070 without confirmation.
1071 without confirmation.
1071 """
1072 """
1072
1073
1073 opts, regex = self.parse_options(parameter_s,'f')
1074 opts, regex = self.parse_options(parameter_s,'f')
1074
1075
1075 if opts.has_key('f'):
1076 if opts.has_key('f'):
1076 ans = True
1077 ans = True
1077 else:
1078 else:
1078 try:
1079 try:
1079 ans = self.shell.ask_yes_no(
1080 ans = self.shell.ask_yes_no(
1080 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1081 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1081 default='n')
1082 default='n')
1082 except StdinNotImplementedError:
1083 except StdinNotImplementedError:
1083 ans = True
1084 ans = True
1084 if not ans:
1085 if not ans:
1085 print 'Nothing done.'
1086 print 'Nothing done.'
1086 return
1087 return
1087 user_ns = self.shell.user_ns
1088 user_ns = self.shell.user_ns
1088 if not regex:
1089 if not regex:
1089 print 'No regex pattern specified. Nothing done.'
1090 print 'No regex pattern specified. Nothing done.'
1090 return
1091 return
1091 else:
1092 else:
1092 try:
1093 try:
1093 m = re.compile(regex)
1094 m = re.compile(regex)
1094 except TypeError:
1095 except TypeError:
1095 raise TypeError('regex must be a string or compiled pattern')
1096 raise TypeError('regex must be a string or compiled pattern')
1096 for i in self.magic_who_ls():
1097 for i in self.magic_who_ls():
1097 if m.search(i):
1098 if m.search(i):
1098 del(user_ns[i])
1099 del(user_ns[i])
1099
1100
1100 def magic_xdel(self, parameter_s=''):
1101 def magic_xdel(self, parameter_s=''):
1101 """Delete a variable, trying to clear it from anywhere that
1102 """Delete a variable, trying to clear it from anywhere that
1102 IPython's machinery has references to it. By default, this uses
1103 IPython's machinery has references to it. By default, this uses
1103 the identity of the named object in the user namespace to remove
1104 the identity of the named object in the user namespace to remove
1104 references held under other names. The object is also removed
1105 references held under other names. The object is also removed
1105 from the output history.
1106 from the output history.
1106
1107
1107 Options
1108 Options
1108 -n : Delete the specified name from all namespaces, without
1109 -n : Delete the specified name from all namespaces, without
1109 checking their identity.
1110 checking their identity.
1110 """
1111 """
1111 opts, varname = self.parse_options(parameter_s,'n')
1112 opts, varname = self.parse_options(parameter_s,'n')
1112 try:
1113 try:
1113 self.shell.del_var(varname, ('n' in opts))
1114 self.shell.del_var(varname, ('n' in opts))
1114 except (NameError, ValueError) as e:
1115 except (NameError, ValueError) as e:
1115 print type(e).__name__ +": "+ str(e)
1116 print type(e).__name__ +": "+ str(e)
1116
1117
1117 def magic_logstart(self,parameter_s=''):
1118 def magic_logstart(self,parameter_s=''):
1118 """Start logging anywhere in a session.
1119 """Start logging anywhere in a session.
1119
1120
1120 %logstart [-o|-r|-t] [log_name [log_mode]]
1121 %logstart [-o|-r|-t] [log_name [log_mode]]
1121
1122
1122 If no name is given, it defaults to a file named 'ipython_log.py' in your
1123 If no name is given, it defaults to a file named 'ipython_log.py' in your
1123 current directory, in 'rotate' mode (see below).
1124 current directory, in 'rotate' mode (see below).
1124
1125
1125 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1126 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1126 history up to that point and then continues logging.
1127 history up to that point and then continues logging.
1127
1128
1128 %logstart takes a second optional parameter: logging mode. This can be one
1129 %logstart takes a second optional parameter: logging mode. This can be one
1129 of (note that the modes are given unquoted):\\
1130 of (note that the modes are given unquoted):\\
1130 append: well, that says it.\\
1131 append: well, that says it.\\
1131 backup: rename (if exists) to name~ and start name.\\
1132 backup: rename (if exists) to name~ and start name.\\
1132 global: single logfile in your home dir, appended to.\\
1133 global: single logfile in your home dir, appended to.\\
1133 over : overwrite existing log.\\
1134 over : overwrite existing log.\\
1134 rotate: create rotating logs name.1~, name.2~, etc.
1135 rotate: create rotating logs name.1~, name.2~, etc.
1135
1136
1136 Options:
1137 Options:
1137
1138
1138 -o: log also IPython's output. In this mode, all commands which
1139 -o: log also IPython's output. In this mode, all commands which
1139 generate an Out[NN] prompt are recorded to the logfile, right after
1140 generate an Out[NN] prompt are recorded to the logfile, right after
1140 their corresponding input line. The output lines are always
1141 their corresponding input line. The output lines are always
1141 prepended with a '#[Out]# ' marker, so that the log remains valid
1142 prepended with a '#[Out]# ' marker, so that the log remains valid
1142 Python code.
1143 Python code.
1143
1144
1144 Since this marker is always the same, filtering only the output from
1145 Since this marker is always the same, filtering only the output from
1145 a log is very easy, using for example a simple awk call:
1146 a log is very easy, using for example a simple awk call:
1146
1147
1147 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1148 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1148
1149
1149 -r: log 'raw' input. Normally, IPython's logs contain the processed
1150 -r: log 'raw' input. Normally, IPython's logs contain the processed
1150 input, so that user lines are logged in their final form, converted
1151 input, so that user lines are logged in their final form, converted
1151 into valid Python. For example, %Exit is logged as
1152 into valid Python. For example, %Exit is logged as
1152 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1153 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1153 exactly as typed, with no transformations applied.
1154 exactly as typed, with no transformations applied.
1154
1155
1155 -t: put timestamps before each input line logged (these are put in
1156 -t: put timestamps before each input line logged (these are put in
1156 comments)."""
1157 comments)."""
1157
1158
1158 opts,par = self.parse_options(parameter_s,'ort')
1159 opts,par = self.parse_options(parameter_s,'ort')
1159 log_output = 'o' in opts
1160 log_output = 'o' in opts
1160 log_raw_input = 'r' in opts
1161 log_raw_input = 'r' in opts
1161 timestamp = 't' in opts
1162 timestamp = 't' in opts
1162
1163
1163 logger = self.shell.logger
1164 logger = self.shell.logger
1164
1165
1165 # if no args are given, the defaults set in the logger constructor by
1166 # if no args are given, the defaults set in the logger constructor by
1166 # ipython remain valid
1167 # ipython remain valid
1167 if par:
1168 if par:
1168 try:
1169 try:
1169 logfname,logmode = par.split()
1170 logfname,logmode = par.split()
1170 except:
1171 except:
1171 logfname = par
1172 logfname = par
1172 logmode = 'backup'
1173 logmode = 'backup'
1173 else:
1174 else:
1174 logfname = logger.logfname
1175 logfname = logger.logfname
1175 logmode = logger.logmode
1176 logmode = logger.logmode
1176 # put logfname into rc struct as if it had been called on the command
1177 # put logfname into rc struct as if it had been called on the command
1177 # line, so it ends up saved in the log header Save it in case we need
1178 # line, so it ends up saved in the log header Save it in case we need
1178 # to restore it...
1179 # to restore it...
1179 old_logfile = self.shell.logfile
1180 old_logfile = self.shell.logfile
1180 if logfname:
1181 if logfname:
1181 logfname = os.path.expanduser(logfname)
1182 logfname = os.path.expanduser(logfname)
1182 self.shell.logfile = logfname
1183 self.shell.logfile = logfname
1183
1184
1184 loghead = '# IPython log file\n\n'
1185 loghead = '# IPython log file\n\n'
1185 try:
1186 try:
1186 started = logger.logstart(logfname,loghead,logmode,
1187 started = logger.logstart(logfname,loghead,logmode,
1187 log_output,timestamp,log_raw_input)
1188 log_output,timestamp,log_raw_input)
1188 except:
1189 except:
1189 self.shell.logfile = old_logfile
1190 self.shell.logfile = old_logfile
1190 warn("Couldn't start log: %s" % sys.exc_info()[1])
1191 warn("Couldn't start log: %s" % sys.exc_info()[1])
1191 else:
1192 else:
1192 # log input history up to this point, optionally interleaving
1193 # log input history up to this point, optionally interleaving
1193 # output if requested
1194 # output if requested
1194
1195
1195 if timestamp:
1196 if timestamp:
1196 # disable timestamping for the previous history, since we've
1197 # disable timestamping for the previous history, since we've
1197 # lost those already (no time machine here).
1198 # lost those already (no time machine here).
1198 logger.timestamp = False
1199 logger.timestamp = False
1199
1200
1200 if log_raw_input:
1201 if log_raw_input:
1201 input_hist = self.shell.history_manager.input_hist_raw
1202 input_hist = self.shell.history_manager.input_hist_raw
1202 else:
1203 else:
1203 input_hist = self.shell.history_manager.input_hist_parsed
1204 input_hist = self.shell.history_manager.input_hist_parsed
1204
1205
1205 if log_output:
1206 if log_output:
1206 log_write = logger.log_write
1207 log_write = logger.log_write
1207 output_hist = self.shell.history_manager.output_hist
1208 output_hist = self.shell.history_manager.output_hist
1208 for n in range(1,len(input_hist)-1):
1209 for n in range(1,len(input_hist)-1):
1209 log_write(input_hist[n].rstrip() + '\n')
1210 log_write(input_hist[n].rstrip() + '\n')
1210 if n in output_hist:
1211 if n in output_hist:
1211 log_write(repr(output_hist[n]),'output')
1212 log_write(repr(output_hist[n]),'output')
1212 else:
1213 else:
1213 logger.log_write('\n'.join(input_hist[1:]))
1214 logger.log_write('\n'.join(input_hist[1:]))
1214 logger.log_write('\n')
1215 logger.log_write('\n')
1215 if timestamp:
1216 if timestamp:
1216 # re-enable timestamping
1217 # re-enable timestamping
1217 logger.timestamp = True
1218 logger.timestamp = True
1218
1219
1219 print ('Activating auto-logging. '
1220 print ('Activating auto-logging. '
1220 'Current session state plus future input saved.')
1221 'Current session state plus future input saved.')
1221 logger.logstate()
1222 logger.logstate()
1222
1223
1223 def magic_logstop(self,parameter_s=''):
1224 def magic_logstop(self,parameter_s=''):
1224 """Fully stop logging and close log file.
1225 """Fully stop logging and close log file.
1225
1226
1226 In order to start logging again, a new %logstart call needs to be made,
1227 In order to start logging again, a new %logstart call needs to be made,
1227 possibly (though not necessarily) with a new filename, mode and other
1228 possibly (though not necessarily) with a new filename, mode and other
1228 options."""
1229 options."""
1229 self.logger.logstop()
1230 self.logger.logstop()
1230
1231
1231 def magic_logoff(self,parameter_s=''):
1232 def magic_logoff(self,parameter_s=''):
1232 """Temporarily stop logging.
1233 """Temporarily stop logging.
1233
1234
1234 You must have previously started logging."""
1235 You must have previously started logging."""
1235 self.shell.logger.switch_log(0)
1236 self.shell.logger.switch_log(0)
1236
1237
1237 def magic_logon(self,parameter_s=''):
1238 def magic_logon(self,parameter_s=''):
1238 """Restart logging.
1239 """Restart logging.
1239
1240
1240 This function is for restarting logging which you've temporarily
1241 This function is for restarting logging which you've temporarily
1241 stopped with %logoff. For starting logging for the first time, you
1242 stopped with %logoff. For starting logging for the first time, you
1242 must use the %logstart function, which allows you to specify an
1243 must use the %logstart function, which allows you to specify an
1243 optional log filename."""
1244 optional log filename."""
1244
1245
1245 self.shell.logger.switch_log(1)
1246 self.shell.logger.switch_log(1)
1246
1247
1247 def magic_logstate(self,parameter_s=''):
1248 def magic_logstate(self,parameter_s=''):
1248 """Print the status of the logging system."""
1249 """Print the status of the logging system."""
1249
1250
1250 self.shell.logger.logstate()
1251 self.shell.logger.logstate()
1251
1252
1252 def magic_pdb(self, parameter_s=''):
1253 def magic_pdb(self, parameter_s=''):
1253 """Control the automatic calling of the pdb interactive debugger.
1254 """Control the automatic calling of the pdb interactive debugger.
1254
1255
1255 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1256 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1256 argument it works as a toggle.
1257 argument it works as a toggle.
1257
1258
1258 When an exception is triggered, IPython can optionally call the
1259 When an exception is triggered, IPython can optionally call the
1259 interactive pdb debugger after the traceback printout. %pdb toggles
1260 interactive pdb debugger after the traceback printout. %pdb toggles
1260 this feature on and off.
1261 this feature on and off.
1261
1262
1262 The initial state of this feature is set in your configuration
1263 The initial state of this feature is set in your configuration
1263 file (the option is ``InteractiveShell.pdb``).
1264 file (the option is ``InteractiveShell.pdb``).
1264
1265
1265 If you want to just activate the debugger AFTER an exception has fired,
1266 If you want to just activate the debugger AFTER an exception has fired,
1266 without having to type '%pdb on' and rerunning your code, you can use
1267 without having to type '%pdb on' and rerunning your code, you can use
1267 the %debug magic."""
1268 the %debug magic."""
1268
1269
1269 par = parameter_s.strip().lower()
1270 par = parameter_s.strip().lower()
1270
1271
1271 if par:
1272 if par:
1272 try:
1273 try:
1273 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1274 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1274 except KeyError:
1275 except KeyError:
1275 print ('Incorrect argument. Use on/1, off/0, '
1276 print ('Incorrect argument. Use on/1, off/0, '
1276 'or nothing for a toggle.')
1277 'or nothing for a toggle.')
1277 return
1278 return
1278 else:
1279 else:
1279 # toggle
1280 # toggle
1280 new_pdb = not self.shell.call_pdb
1281 new_pdb = not self.shell.call_pdb
1281
1282
1282 # set on the shell
1283 # set on the shell
1283 self.shell.call_pdb = new_pdb
1284 self.shell.call_pdb = new_pdb
1284 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1285 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1285
1286
1286 def magic_debug(self, parameter_s=''):
1287 def magic_debug(self, parameter_s=''):
1287 """Activate the interactive debugger in post-mortem mode.
1288 """Activate the interactive debugger in post-mortem mode.
1288
1289
1289 If an exception has just occurred, this lets you inspect its stack
1290 If an exception has just occurred, this lets you inspect its stack
1290 frames interactively. Note that this will always work only on the last
1291 frames interactively. Note that this will always work only on the last
1291 traceback that occurred, so you must call this quickly after an
1292 traceback that occurred, so you must call this quickly after an
1292 exception that you wish to inspect has fired, because if another one
1293 exception that you wish to inspect has fired, because if another one
1293 occurs, it clobbers the previous one.
1294 occurs, it clobbers the previous one.
1294
1295
1295 If you want IPython to automatically do this on every exception, see
1296 If you want IPython to automatically do this on every exception, see
1296 the %pdb magic for more details.
1297 the %pdb magic for more details.
1297 """
1298 """
1298 self.shell.debugger(force=True)
1299 self.shell.debugger(force=True)
1299
1300
1300 @skip_doctest
1301 @skip_doctest
1301 def magic_prun(self, parameter_s ='',user_mode=1,
1302 def magic_prun(self, parameter_s ='',user_mode=1,
1302 opts=None,arg_lst=None,prog_ns=None):
1303 opts=None,arg_lst=None,prog_ns=None):
1303
1304
1304 """Run a statement through the python code profiler.
1305 """Run a statement through the python code profiler.
1305
1306
1306 Usage:
1307 Usage:
1307 %prun [options] statement
1308 %prun [options] statement
1308
1309
1309 The given statement (which doesn't require quote marks) is run via the
1310 The given statement (which doesn't require quote marks) is run via the
1310 python profiler in a manner similar to the profile.run() function.
1311 python profiler in a manner similar to the profile.run() function.
1311 Namespaces are internally managed to work correctly; profile.run
1312 Namespaces are internally managed to work correctly; profile.run
1312 cannot be used in IPython because it makes certain assumptions about
1313 cannot be used in IPython because it makes certain assumptions about
1313 namespaces which do not hold under IPython.
1314 namespaces which do not hold under IPython.
1314
1315
1315 Options:
1316 Options:
1316
1317
1317 -l <limit>: you can place restrictions on what or how much of the
1318 -l <limit>: you can place restrictions on what or how much of the
1318 profile gets printed. The limit value can be:
1319 profile gets printed. The limit value can be:
1319
1320
1320 * A string: only information for function names containing this string
1321 * A string: only information for function names containing this string
1321 is printed.
1322 is printed.
1322
1323
1323 * An integer: only these many lines are printed.
1324 * An integer: only these many lines are printed.
1324
1325
1325 * A float (between 0 and 1): this fraction of the report is printed
1326 * A float (between 0 and 1): this fraction of the report is printed
1326 (for example, use a limit of 0.4 to see the topmost 40% only).
1327 (for example, use a limit of 0.4 to see the topmost 40% only).
1327
1328
1328 You can combine several limits with repeated use of the option. For
1329 You can combine several limits with repeated use of the option. For
1329 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1330 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1330 information about class constructors.
1331 information about class constructors.
1331
1332
1332 -r: return the pstats.Stats object generated by the profiling. This
1333 -r: return the pstats.Stats object generated by the profiling. This
1333 object has all the information about the profile in it, and you can
1334 object has all the information about the profile in it, and you can
1334 later use it for further analysis or in other functions.
1335 later use it for further analysis or in other functions.
1335
1336
1336 -s <key>: sort profile by given key. You can provide more than one key
1337 -s <key>: sort profile by given key. You can provide more than one key
1337 by using the option several times: '-s key1 -s key2 -s key3...'. The
1338 by using the option several times: '-s key1 -s key2 -s key3...'. The
1338 default sorting key is 'time'.
1339 default sorting key is 'time'.
1339
1340
1340 The following is copied verbatim from the profile documentation
1341 The following is copied verbatim from the profile documentation
1341 referenced below:
1342 referenced below:
1342
1343
1343 When more than one key is provided, additional keys are used as
1344 When more than one key is provided, additional keys are used as
1344 secondary criteria when the there is equality in all keys selected
1345 secondary criteria when the there is equality in all keys selected
1345 before them.
1346 before them.
1346
1347
1347 Abbreviations can be used for any key names, as long as the
1348 Abbreviations can be used for any key names, as long as the
1348 abbreviation is unambiguous. The following are the keys currently
1349 abbreviation is unambiguous. The following are the keys currently
1349 defined:
1350 defined:
1350
1351
1351 Valid Arg Meaning
1352 Valid Arg Meaning
1352 "calls" call count
1353 "calls" call count
1353 "cumulative" cumulative time
1354 "cumulative" cumulative time
1354 "file" file name
1355 "file" file name
1355 "module" file name
1356 "module" file name
1356 "pcalls" primitive call count
1357 "pcalls" primitive call count
1357 "line" line number
1358 "line" line number
1358 "name" function name
1359 "name" function name
1359 "nfl" name/file/line
1360 "nfl" name/file/line
1360 "stdname" standard name
1361 "stdname" standard name
1361 "time" internal time
1362 "time" internal time
1362
1363
1363 Note that all sorts on statistics are in descending order (placing
1364 Note that all sorts on statistics are in descending order (placing
1364 most time consuming items first), where as name, file, and line number
1365 most time consuming items first), where as name, file, and line number
1365 searches are in ascending order (i.e., alphabetical). The subtle
1366 searches are in ascending order (i.e., alphabetical). The subtle
1366 distinction between "nfl" and "stdname" is that the standard name is a
1367 distinction between "nfl" and "stdname" is that the standard name is a
1367 sort of the name as printed, which means that the embedded line
1368 sort of the name as printed, which means that the embedded line
1368 numbers get compared in an odd way. For example, lines 3, 20, and 40
1369 numbers get compared in an odd way. For example, lines 3, 20, and 40
1369 would (if the file names were the same) appear in the string order
1370 would (if the file names were the same) appear in the string order
1370 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1371 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1371 line numbers. In fact, sort_stats("nfl") is the same as
1372 line numbers. In fact, sort_stats("nfl") is the same as
1372 sort_stats("name", "file", "line").
1373 sort_stats("name", "file", "line").
1373
1374
1374 -T <filename>: save profile results as shown on screen to a text
1375 -T <filename>: save profile results as shown on screen to a text
1375 file. The profile is still shown on screen.
1376 file. The profile is still shown on screen.
1376
1377
1377 -D <filename>: save (via dump_stats) profile statistics to given
1378 -D <filename>: save (via dump_stats) profile statistics to given
1378 filename. This data is in a format understood by the pstats module, and
1379 filename. This data is in a format understood by the pstats module, and
1379 is generated by a call to the dump_stats() method of profile
1380 is generated by a call to the dump_stats() method of profile
1380 objects. The profile is still shown on screen.
1381 objects. The profile is still shown on screen.
1381
1382
1382 -q: suppress output to the pager. Best used with -T and/or -D above.
1383 -q: suppress output to the pager. Best used with -T and/or -D above.
1383
1384
1384 If you want to run complete programs under the profiler's control, use
1385 If you want to run complete programs under the profiler's control, use
1385 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1386 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1386 contains profiler specific options as described here.
1387 contains profiler specific options as described here.
1387
1388
1388 You can read the complete documentation for the profile module with::
1389 You can read the complete documentation for the profile module with::
1389
1390
1390 In [1]: import profile; profile.help()
1391 In [1]: import profile; profile.help()
1391 """
1392 """
1392
1393
1393 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1394 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1394 # protect user quote marks
1395 # protect user quote marks
1395 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1396 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1396
1397
1397 if user_mode: # regular user call
1398 if user_mode: # regular user call
1398 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1399 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1399 list_all=1)
1400 list_all=1)
1400 namespace = self.shell.user_ns
1401 namespace = self.shell.user_ns
1401 else: # called to run a program by %run -p
1402 else: # called to run a program by %run -p
1402 try:
1403 try:
1403 filename = get_py_filename(arg_lst[0])
1404 filename = get_py_filename(arg_lst[0])
1404 except IOError as e:
1405 except IOError as e:
1405 try:
1406 try:
1406 msg = str(e)
1407 msg = str(e)
1407 except UnicodeError:
1408 except UnicodeError:
1408 msg = e.message
1409 msg = e.message
1409 error(msg)
1410 error(msg)
1410 return
1411 return
1411
1412
1412 arg_str = 'execfile(filename,prog_ns)'
1413 arg_str = 'execfile(filename,prog_ns)'
1413 namespace = {
1414 namespace = {
1414 'execfile': self.shell.safe_execfile,
1415 'execfile': self.shell.safe_execfile,
1415 'prog_ns': prog_ns,
1416 'prog_ns': prog_ns,
1416 'filename': filename
1417 'filename': filename
1417 }
1418 }
1418
1419
1419 opts.merge(opts_def)
1420 opts.merge(opts_def)
1420
1421
1421 prof = profile.Profile()
1422 prof = profile.Profile()
1422 try:
1423 try:
1423 prof = prof.runctx(arg_str,namespace,namespace)
1424 prof = prof.runctx(arg_str,namespace,namespace)
1424 sys_exit = ''
1425 sys_exit = ''
1425 except SystemExit:
1426 except SystemExit:
1426 sys_exit = """*** SystemExit exception caught in code being profiled."""
1427 sys_exit = """*** SystemExit exception caught in code being profiled."""
1427
1428
1428 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1429 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1429
1430
1430 lims = opts.l
1431 lims = opts.l
1431 if lims:
1432 if lims:
1432 lims = [] # rebuild lims with ints/floats/strings
1433 lims = [] # rebuild lims with ints/floats/strings
1433 for lim in opts.l:
1434 for lim in opts.l:
1434 try:
1435 try:
1435 lims.append(int(lim))
1436 lims.append(int(lim))
1436 except ValueError:
1437 except ValueError:
1437 try:
1438 try:
1438 lims.append(float(lim))
1439 lims.append(float(lim))
1439 except ValueError:
1440 except ValueError:
1440 lims.append(lim)
1441 lims.append(lim)
1441
1442
1442 # Trap output.
1443 # Trap output.
1443 stdout_trap = StringIO()
1444 stdout_trap = StringIO()
1444
1445
1445 if hasattr(stats,'stream'):
1446 if hasattr(stats,'stream'):
1446 # In newer versions of python, the stats object has a 'stream'
1447 # In newer versions of python, the stats object has a 'stream'
1447 # attribute to write into.
1448 # attribute to write into.
1448 stats.stream = stdout_trap
1449 stats.stream = stdout_trap
1449 stats.print_stats(*lims)
1450 stats.print_stats(*lims)
1450 else:
1451 else:
1451 # For older versions, we manually redirect stdout during printing
1452 # For older versions, we manually redirect stdout during printing
1452 sys_stdout = sys.stdout
1453 sys_stdout = sys.stdout
1453 try:
1454 try:
1454 sys.stdout = stdout_trap
1455 sys.stdout = stdout_trap
1455 stats.print_stats(*lims)
1456 stats.print_stats(*lims)
1456 finally:
1457 finally:
1457 sys.stdout = sys_stdout
1458 sys.stdout = sys_stdout
1458
1459
1459 output = stdout_trap.getvalue()
1460 output = stdout_trap.getvalue()
1460 output = output.rstrip()
1461 output = output.rstrip()
1461
1462
1462 if 'q' not in opts:
1463 if 'q' not in opts:
1463 page.page(output)
1464 page.page(output)
1464 print sys_exit,
1465 print sys_exit,
1465
1466
1466 dump_file = opts.D[0]
1467 dump_file = opts.D[0]
1467 text_file = opts.T[0]
1468 text_file = opts.T[0]
1468 if dump_file:
1469 if dump_file:
1469 dump_file = unquote_filename(dump_file)
1470 dump_file = unquote_filename(dump_file)
1470 prof.dump_stats(dump_file)
1471 prof.dump_stats(dump_file)
1471 print '\n*** Profile stats marshalled to file',\
1472 print '\n*** Profile stats marshalled to file',\
1472 `dump_file`+'.',sys_exit
1473 `dump_file`+'.',sys_exit
1473 if text_file:
1474 if text_file:
1474 text_file = unquote_filename(text_file)
1475 text_file = unquote_filename(text_file)
1475 pfile = file(text_file,'w')
1476 pfile = file(text_file,'w')
1476 pfile.write(output)
1477 pfile.write(output)
1477 pfile.close()
1478 pfile.close()
1478 print '\n*** Profile printout saved to text file',\
1479 print '\n*** Profile printout saved to text file',\
1479 `text_file`+'.',sys_exit
1480 `text_file`+'.',sys_exit
1480
1481
1481 if opts.has_key('r'):
1482 if opts.has_key('r'):
1482 return stats
1483 return stats
1483 else:
1484 else:
1484 return None
1485 return None
1485
1486
1486 @skip_doctest
1487 @skip_doctest
1487 def magic_run(self, parameter_s ='', runner=None,
1488 def magic_run(self, parameter_s ='', runner=None,
1488 file_finder=get_py_filename):
1489 file_finder=get_py_filename):
1489 """Run the named file inside IPython as a program.
1490 """Run the named file inside IPython as a program.
1490
1491
1491 Usage:\\
1492 Usage:\\
1492 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1493 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1493
1494
1494 Parameters after the filename are passed as command-line arguments to
1495 Parameters after the filename are passed as command-line arguments to
1495 the program (put in sys.argv). Then, control returns to IPython's
1496 the program (put in sys.argv). Then, control returns to IPython's
1496 prompt.
1497 prompt.
1497
1498
1498 This is similar to running at a system prompt:\\
1499 This is similar to running at a system prompt:\\
1499 $ python file args\\
1500 $ python file args\\
1500 but with the advantage of giving you IPython's tracebacks, and of
1501 but with the advantage of giving you IPython's tracebacks, and of
1501 loading all variables into your interactive namespace for further use
1502 loading all variables into your interactive namespace for further use
1502 (unless -p is used, see below).
1503 (unless -p is used, see below).
1503
1504
1504 The file is executed in a namespace initially consisting only of
1505 The file is executed in a namespace initially consisting only of
1505 __name__=='__main__' and sys.argv constructed as indicated. It thus
1506 __name__=='__main__' and sys.argv constructed as indicated. It thus
1506 sees its environment as if it were being run as a stand-alone program
1507 sees its environment as if it were being run as a stand-alone program
1507 (except for sharing global objects such as previously imported
1508 (except for sharing global objects such as previously imported
1508 modules). But after execution, the IPython interactive namespace gets
1509 modules). But after execution, the IPython interactive namespace gets
1509 updated with all variables defined in the program (except for __name__
1510 updated with all variables defined in the program (except for __name__
1510 and sys.argv). This allows for very convenient loading of code for
1511 and sys.argv). This allows for very convenient loading of code for
1511 interactive work, while giving each program a 'clean sheet' to run in.
1512 interactive work, while giving each program a 'clean sheet' to run in.
1512
1513
1513 Options:
1514 Options:
1514
1515
1515 -n: __name__ is NOT set to '__main__', but to the running file's name
1516 -n: __name__ is NOT set to '__main__', but to the running file's name
1516 without extension (as python does under import). This allows running
1517 without extension (as python does under import). This allows running
1517 scripts and reloading the definitions in them without calling code
1518 scripts and reloading the definitions in them without calling code
1518 protected by an ' if __name__ == "__main__" ' clause.
1519 protected by an ' if __name__ == "__main__" ' clause.
1519
1520
1520 -i: run the file in IPython's namespace instead of an empty one. This
1521 -i: run the file in IPython's namespace instead of an empty one. This
1521 is useful if you are experimenting with code written in a text editor
1522 is useful if you are experimenting with code written in a text editor
1522 which depends on variables defined interactively.
1523 which depends on variables defined interactively.
1523
1524
1524 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1525 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1525 being run. This is particularly useful if IPython is being used to
1526 being run. This is particularly useful if IPython is being used to
1526 run unittests, which always exit with a sys.exit() call. In such
1527 run unittests, which always exit with a sys.exit() call. In such
1527 cases you are interested in the output of the test results, not in
1528 cases you are interested in the output of the test results, not in
1528 seeing a traceback of the unittest module.
1529 seeing a traceback of the unittest module.
1529
1530
1530 -t: print timing information at the end of the run. IPython will give
1531 -t: print timing information at the end of the run. IPython will give
1531 you an estimated CPU time consumption for your script, which under
1532 you an estimated CPU time consumption for your script, which under
1532 Unix uses the resource module to avoid the wraparound problems of
1533 Unix uses the resource module to avoid the wraparound problems of
1533 time.clock(). Under Unix, an estimate of time spent on system tasks
1534 time.clock(). Under Unix, an estimate of time spent on system tasks
1534 is also given (for Windows platforms this is reported as 0.0).
1535 is also given (for Windows platforms this is reported as 0.0).
1535
1536
1536 If -t is given, an additional -N<N> option can be given, where <N>
1537 If -t is given, an additional -N<N> option can be given, where <N>
1537 must be an integer indicating how many times you want the script to
1538 must be an integer indicating how many times you want the script to
1538 run. The final timing report will include total and per run results.
1539 run. The final timing report will include total and per run results.
1539
1540
1540 For example (testing the script uniq_stable.py):
1541 For example (testing the script uniq_stable.py):
1541
1542
1542 In [1]: run -t uniq_stable
1543 In [1]: run -t uniq_stable
1543
1544
1544 IPython CPU timings (estimated):\\
1545 IPython CPU timings (estimated):\\
1545 User : 0.19597 s.\\
1546 User : 0.19597 s.\\
1546 System: 0.0 s.\\
1547 System: 0.0 s.\\
1547
1548
1548 In [2]: run -t -N5 uniq_stable
1549 In [2]: run -t -N5 uniq_stable
1549
1550
1550 IPython CPU timings (estimated):\\
1551 IPython CPU timings (estimated):\\
1551 Total runs performed: 5\\
1552 Total runs performed: 5\\
1552 Times : Total Per run\\
1553 Times : Total Per run\\
1553 User : 0.910862 s, 0.1821724 s.\\
1554 User : 0.910862 s, 0.1821724 s.\\
1554 System: 0.0 s, 0.0 s.
1555 System: 0.0 s, 0.0 s.
1555
1556
1556 -d: run your program under the control of pdb, the Python debugger.
1557 -d: run your program under the control of pdb, the Python debugger.
1557 This allows you to execute your program step by step, watch variables,
1558 This allows you to execute your program step by step, watch variables,
1558 etc. Internally, what IPython does is similar to calling:
1559 etc. Internally, what IPython does is similar to calling:
1559
1560
1560 pdb.run('execfile("YOURFILENAME")')
1561 pdb.run('execfile("YOURFILENAME")')
1561
1562
1562 with a breakpoint set on line 1 of your file. You can change the line
1563 with a breakpoint set on line 1 of your file. You can change the line
1563 number for this automatic breakpoint to be <N> by using the -bN option
1564 number for this automatic breakpoint to be <N> by using the -bN option
1564 (where N must be an integer). For example:
1565 (where N must be an integer). For example:
1565
1566
1566 %run -d -b40 myscript
1567 %run -d -b40 myscript
1567
1568
1568 will set the first breakpoint at line 40 in myscript.py. Note that
1569 will set the first breakpoint at line 40 in myscript.py. Note that
1569 the first breakpoint must be set on a line which actually does
1570 the first breakpoint must be set on a line which actually does
1570 something (not a comment or docstring) for it to stop execution.
1571 something (not a comment or docstring) for it to stop execution.
1571
1572
1572 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1573 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1573 first enter 'c' (without quotes) to start execution up to the first
1574 first enter 'c' (without quotes) to start execution up to the first
1574 breakpoint.
1575 breakpoint.
1575
1576
1576 Entering 'help' gives information about the use of the debugger. You
1577 Entering 'help' gives information about the use of the debugger. You
1577 can easily see pdb's full documentation with "import pdb;pdb.help()"
1578 can easily see pdb's full documentation with "import pdb;pdb.help()"
1578 at a prompt.
1579 at a prompt.
1579
1580
1580 -p: run program under the control of the Python profiler module (which
1581 -p: run program under the control of the Python profiler module (which
1581 prints a detailed report of execution times, function calls, etc).
1582 prints a detailed report of execution times, function calls, etc).
1582
1583
1583 You can pass other options after -p which affect the behavior of the
1584 You can pass other options after -p which affect the behavior of the
1584 profiler itself. See the docs for %prun for details.
1585 profiler itself. See the docs for %prun for details.
1585
1586
1586 In this mode, the program's variables do NOT propagate back to the
1587 In this mode, the program's variables do NOT propagate back to the
1587 IPython interactive namespace (because they remain in the namespace
1588 IPython interactive namespace (because they remain in the namespace
1588 where the profiler executes them).
1589 where the profiler executes them).
1589
1590
1590 Internally this triggers a call to %prun, see its documentation for
1591 Internally this triggers a call to %prun, see its documentation for
1591 details on the options available specifically for profiling.
1592 details on the options available specifically for profiling.
1592
1593
1593 There is one special usage for which the text above doesn't apply:
1594 There is one special usage for which the text above doesn't apply:
1594 if the filename ends with .ipy, the file is run as ipython script,
1595 if the filename ends with .ipy, the file is run as ipython script,
1595 just as if the commands were written on IPython prompt.
1596 just as if the commands were written on IPython prompt.
1596
1597
1597 -m: specify module name to load instead of script path. Similar to
1598 -m: specify module name to load instead of script path. Similar to
1598 the -m option for the python interpreter. Use this option last if you
1599 the -m option for the python interpreter. Use this option last if you
1599 want to combine with other %run options. Unlike the python interpreter
1600 want to combine with other %run options. Unlike the python interpreter
1600 only source modules are allowed no .pyc or .pyo files.
1601 only source modules are allowed no .pyc or .pyo files.
1601 For example:
1602 For example:
1602
1603
1603 %run -m example
1604 %run -m example
1604
1605
1605 will run the example module.
1606 will run the example module.
1606
1607
1607 """
1608 """
1608
1609
1609 # get arguments and set sys.argv for program to be run.
1610 # get arguments and set sys.argv for program to be run.
1610 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1611 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1611 mode='list', list_all=1)
1612 mode='list', list_all=1)
1612 if "m" in opts:
1613 if "m" in opts:
1613 modulename = opts["m"][0]
1614 modulename = opts["m"][0]
1614 modpath = find_mod(modulename)
1615 modpath = find_mod(modulename)
1615 if modpath is None:
1616 if modpath is None:
1616 warn('%r is not a valid modulename on sys.path'%modulename)
1617 warn('%r is not a valid modulename on sys.path'%modulename)
1617 return
1618 return
1618 arg_lst = [modpath] + arg_lst
1619 arg_lst = [modpath] + arg_lst
1619 try:
1620 try:
1620 filename = file_finder(arg_lst[0])
1621 filename = file_finder(arg_lst[0])
1621 except IndexError:
1622 except IndexError:
1622 warn('you must provide at least a filename.')
1623 warn('you must provide at least a filename.')
1623 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1624 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1624 return
1625 return
1625 except IOError as e:
1626 except IOError as e:
1626 try:
1627 try:
1627 msg = str(e)
1628 msg = str(e)
1628 except UnicodeError:
1629 except UnicodeError:
1629 msg = e.message
1630 msg = e.message
1630 error(msg)
1631 error(msg)
1631 return
1632 return
1632
1633
1633 if filename.lower().endswith('.ipy'):
1634 if filename.lower().endswith('.ipy'):
1634 self.shell.safe_execfile_ipy(filename)
1635 self.shell.safe_execfile_ipy(filename)
1635 return
1636 return
1636
1637
1637 # Control the response to exit() calls made by the script being run
1638 # Control the response to exit() calls made by the script being run
1638 exit_ignore = 'e' in opts
1639 exit_ignore = 'e' in opts
1639
1640
1640 # Make sure that the running script gets a proper sys.argv as if it
1641 # Make sure that the running script gets a proper sys.argv as if it
1641 # were run from a system shell.
1642 # were run from a system shell.
1642 save_argv = sys.argv # save it for later restoring
1643 save_argv = sys.argv # save it for later restoring
1643
1644
1644 # simulate shell expansion on arguments, at least tilde expansion
1645 # simulate shell expansion on arguments, at least tilde expansion
1645 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1646 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1646
1647
1647 sys.argv = [filename] + args # put in the proper filename
1648 sys.argv = [filename] + args # put in the proper filename
1648 # protect sys.argv from potential unicode strings on Python 2:
1649 # protect sys.argv from potential unicode strings on Python 2:
1649 if not py3compat.PY3:
1650 if not py3compat.PY3:
1650 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1651 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1651
1652
1652 if 'i' in opts:
1653 if 'i' in opts:
1653 # Run in user's interactive namespace
1654 # Run in user's interactive namespace
1654 prog_ns = self.shell.user_ns
1655 prog_ns = self.shell.user_ns
1655 __name__save = self.shell.user_ns['__name__']
1656 __name__save = self.shell.user_ns['__name__']
1656 prog_ns['__name__'] = '__main__'
1657 prog_ns['__name__'] = '__main__'
1657 main_mod = self.shell.new_main_mod(prog_ns)
1658 main_mod = self.shell.new_main_mod(prog_ns)
1658 else:
1659 else:
1659 # Run in a fresh, empty namespace
1660 # Run in a fresh, empty namespace
1660 if 'n' in opts:
1661 if 'n' in opts:
1661 name = os.path.splitext(os.path.basename(filename))[0]
1662 name = os.path.splitext(os.path.basename(filename))[0]
1662 else:
1663 else:
1663 name = '__main__'
1664 name = '__main__'
1664
1665
1665 main_mod = self.shell.new_main_mod()
1666 main_mod = self.shell.new_main_mod()
1666 prog_ns = main_mod.__dict__
1667 prog_ns = main_mod.__dict__
1667 prog_ns['__name__'] = name
1668 prog_ns['__name__'] = name
1668
1669
1669 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1670 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1670 # set the __file__ global in the script's namespace
1671 # set the __file__ global in the script's namespace
1671 prog_ns['__file__'] = filename
1672 prog_ns['__file__'] = filename
1672
1673
1673 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1674 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1674 # that, if we overwrite __main__, we replace it at the end
1675 # that, if we overwrite __main__, we replace it at the end
1675 main_mod_name = prog_ns['__name__']
1676 main_mod_name = prog_ns['__name__']
1676
1677
1677 if main_mod_name == '__main__':
1678 if main_mod_name == '__main__':
1678 restore_main = sys.modules['__main__']
1679 restore_main = sys.modules['__main__']
1679 else:
1680 else:
1680 restore_main = False
1681 restore_main = False
1681
1682
1682 # This needs to be undone at the end to prevent holding references to
1683 # This needs to be undone at the end to prevent holding references to
1683 # every single object ever created.
1684 # every single object ever created.
1684 sys.modules[main_mod_name] = main_mod
1685 sys.modules[main_mod_name] = main_mod
1685
1686
1686 try:
1687 try:
1687 stats = None
1688 stats = None
1688 with self.readline_no_record:
1689 with self.readline_no_record:
1689 if 'p' in opts:
1690 if 'p' in opts:
1690 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1691 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1691 else:
1692 else:
1692 if 'd' in opts:
1693 if 'd' in opts:
1693 deb = debugger.Pdb(self.shell.colors)
1694 deb = debugger.Pdb(self.shell.colors)
1694 # reset Breakpoint state, which is moronically kept
1695 # reset Breakpoint state, which is moronically kept
1695 # in a class
1696 # in a class
1696 bdb.Breakpoint.next = 1
1697 bdb.Breakpoint.next = 1
1697 bdb.Breakpoint.bplist = {}
1698 bdb.Breakpoint.bplist = {}
1698 bdb.Breakpoint.bpbynumber = [None]
1699 bdb.Breakpoint.bpbynumber = [None]
1699 # Set an initial breakpoint to stop execution
1700 # Set an initial breakpoint to stop execution
1700 maxtries = 10
1701 maxtries = 10
1701 bp = int(opts.get('b', [1])[0])
1702 bp = int(opts.get('b', [1])[0])
1702 checkline = deb.checkline(filename, bp)
1703 checkline = deb.checkline(filename, bp)
1703 if not checkline:
1704 if not checkline:
1704 for bp in range(bp + 1, bp + maxtries + 1):
1705 for bp in range(bp + 1, bp + maxtries + 1):
1705 if deb.checkline(filename, bp):
1706 if deb.checkline(filename, bp):
1706 break
1707 break
1707 else:
1708 else:
1708 msg = ("\nI failed to find a valid line to set "
1709 msg = ("\nI failed to find a valid line to set "
1709 "a breakpoint\n"
1710 "a breakpoint\n"
1710 "after trying up to line: %s.\n"
1711 "after trying up to line: %s.\n"
1711 "Please set a valid breakpoint manually "
1712 "Please set a valid breakpoint manually "
1712 "with the -b option." % bp)
1713 "with the -b option." % bp)
1713 error(msg)
1714 error(msg)
1714 return
1715 return
1715 # if we find a good linenumber, set the breakpoint
1716 # if we find a good linenumber, set the breakpoint
1716 deb.do_break('%s:%s' % (filename, bp))
1717 deb.do_break('%s:%s' % (filename, bp))
1717 # Start file run
1718 # Start file run
1718 print "NOTE: Enter 'c' at the",
1719 print "NOTE: Enter 'c' at the",
1719 print "%s prompt to start your script." % deb.prompt
1720 print "%s prompt to start your script." % deb.prompt
1720 try:
1721 try:
1721 deb.run('execfile("%s")' % filename, prog_ns)
1722 deb.run('execfile("%s")' % filename, prog_ns)
1722
1723
1723 except:
1724 except:
1724 etype, value, tb = sys.exc_info()
1725 etype, value, tb = sys.exc_info()
1725 # Skip three frames in the traceback: the %run one,
1726 # Skip three frames in the traceback: the %run one,
1726 # one inside bdb.py, and the command-line typed by the
1727 # one inside bdb.py, and the command-line typed by the
1727 # user (run by exec in pdb itself).
1728 # user (run by exec in pdb itself).
1728 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1729 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1729 else:
1730 else:
1730 if runner is None:
1731 if runner is None:
1731 runner = self.shell.safe_execfile
1732 runner = self.shell.safe_execfile
1732 if 't' in opts:
1733 if 't' in opts:
1733 # timed execution
1734 # timed execution
1734 try:
1735 try:
1735 nruns = int(opts['N'][0])
1736 nruns = int(opts['N'][0])
1736 if nruns < 1:
1737 if nruns < 1:
1737 error('Number of runs must be >=1')
1738 error('Number of runs must be >=1')
1738 return
1739 return
1739 except (KeyError):
1740 except (KeyError):
1740 nruns = 1
1741 nruns = 1
1741 twall0 = time.time()
1742 twall0 = time.time()
1742 if nruns == 1:
1743 if nruns == 1:
1743 t0 = clock2()
1744 t0 = clock2()
1744 runner(filename, prog_ns, prog_ns,
1745 runner(filename, prog_ns, prog_ns,
1745 exit_ignore=exit_ignore)
1746 exit_ignore=exit_ignore)
1746 t1 = clock2()
1747 t1 = clock2()
1747 t_usr = t1[0] - t0[0]
1748 t_usr = t1[0] - t0[0]
1748 t_sys = t1[1] - t0[1]
1749 t_sys = t1[1] - t0[1]
1749 print "\nIPython CPU timings (estimated):"
1750 print "\nIPython CPU timings (estimated):"
1750 print " User : %10.2f s." % t_usr
1751 print " User : %10.2f s." % t_usr
1751 print " System : %10.2f s." % t_sys
1752 print " System : %10.2f s." % t_sys
1752 else:
1753 else:
1753 runs = range(nruns)
1754 runs = range(nruns)
1754 t0 = clock2()
1755 t0 = clock2()
1755 for nr in runs:
1756 for nr in runs:
1756 runner(filename, prog_ns, prog_ns,
1757 runner(filename, prog_ns, prog_ns,
1757 exit_ignore=exit_ignore)
1758 exit_ignore=exit_ignore)
1758 t1 = clock2()
1759 t1 = clock2()
1759 t_usr = t1[0] - t0[0]
1760 t_usr = t1[0] - t0[0]
1760 t_sys = t1[1] - t0[1]
1761 t_sys = t1[1] - t0[1]
1761 print "\nIPython CPU timings (estimated):"
1762 print "\nIPython CPU timings (estimated):"
1762 print "Total runs performed:", nruns
1763 print "Total runs performed:", nruns
1763 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1764 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1764 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1765 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1765 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1766 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1766 twall1 = time.time()
1767 twall1 = time.time()
1767 print "Wall time: %10.2f s." % (twall1 - twall0)
1768 print "Wall time: %10.2f s." % (twall1 - twall0)
1768
1769
1769 else:
1770 else:
1770 # regular execution
1771 # regular execution
1771 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1772 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1772
1773
1773 if 'i' in opts:
1774 if 'i' in opts:
1774 self.shell.user_ns['__name__'] = __name__save
1775 self.shell.user_ns['__name__'] = __name__save
1775 else:
1776 else:
1776 # The shell MUST hold a reference to prog_ns so after %run
1777 # The shell MUST hold a reference to prog_ns so after %run
1777 # exits, the python deletion mechanism doesn't zero it out
1778 # exits, the python deletion mechanism doesn't zero it out
1778 # (leaving dangling references).
1779 # (leaving dangling references).
1779 self.shell.cache_main_mod(prog_ns, filename)
1780 self.shell.cache_main_mod(prog_ns, filename)
1780 # update IPython interactive namespace
1781 # update IPython interactive namespace
1781
1782
1782 # Some forms of read errors on the file may mean the
1783 # Some forms of read errors on the file may mean the
1783 # __name__ key was never set; using pop we don't have to
1784 # __name__ key was never set; using pop we don't have to
1784 # worry about a possible KeyError.
1785 # worry about a possible KeyError.
1785 prog_ns.pop('__name__', None)
1786 prog_ns.pop('__name__', None)
1786
1787
1787 self.shell.user_ns.update(prog_ns)
1788 self.shell.user_ns.update(prog_ns)
1788 finally:
1789 finally:
1789 # It's a bit of a mystery why, but __builtins__ can change from
1790 # It's a bit of a mystery why, but __builtins__ can change from
1790 # being a module to becoming a dict missing some key data after
1791 # being a module to becoming a dict missing some key data after
1791 # %run. As best I can see, this is NOT something IPython is doing
1792 # %run. As best I can see, this is NOT something IPython is doing
1792 # at all, and similar problems have been reported before:
1793 # at all, and similar problems have been reported before:
1793 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1794 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1794 # Since this seems to be done by the interpreter itself, the best
1795 # Since this seems to be done by the interpreter itself, the best
1795 # we can do is to at least restore __builtins__ for the user on
1796 # we can do is to at least restore __builtins__ for the user on
1796 # exit.
1797 # exit.
1797 self.shell.user_ns['__builtins__'] = builtin_mod
1798 self.shell.user_ns['__builtins__'] = builtin_mod
1798
1799
1799 # Ensure key global structures are restored
1800 # Ensure key global structures are restored
1800 sys.argv = save_argv
1801 sys.argv = save_argv
1801 if restore_main:
1802 if restore_main:
1802 sys.modules['__main__'] = restore_main
1803 sys.modules['__main__'] = restore_main
1803 else:
1804 else:
1804 # Remove from sys.modules the reference to main_mod we'd
1805 # Remove from sys.modules the reference to main_mod we'd
1805 # added. Otherwise it will trap references to objects
1806 # added. Otherwise it will trap references to objects
1806 # contained therein.
1807 # contained therein.
1807 del sys.modules[main_mod_name]
1808 del sys.modules[main_mod_name]
1808
1809
1809 return stats
1810 return stats
1810
1811
1811 @skip_doctest
1812 @skip_doctest
1812 def magic_timeit(self, parameter_s =''):
1813 def magic_timeit(self, parameter_s =''):
1813 """Time execution of a Python statement or expression
1814 """Time execution of a Python statement or expression
1814
1815
1815 Usage:\\
1816 Usage:\\
1816 %timeit [-n<N> -r<R> [-t|-c]] statement
1817 %timeit [-n<N> -r<R> [-t|-c]] statement
1817
1818
1818 Time execution of a Python statement or expression using the timeit
1819 Time execution of a Python statement or expression using the timeit
1819 module.
1820 module.
1820
1821
1821 Options:
1822 Options:
1822 -n<N>: execute the given statement <N> times in a loop. If this value
1823 -n<N>: execute the given statement <N> times in a loop. If this value
1823 is not given, a fitting value is chosen.
1824 is not given, a fitting value is chosen.
1824
1825
1825 -r<R>: repeat the loop iteration <R> times and take the best result.
1826 -r<R>: repeat the loop iteration <R> times and take the best result.
1826 Default: 3
1827 Default: 3
1827
1828
1828 -t: use time.time to measure the time, which is the default on Unix.
1829 -t: use time.time to measure the time, which is the default on Unix.
1829 This function measures wall time.
1830 This function measures wall time.
1830
1831
1831 -c: use time.clock to measure the time, which is the default on
1832 -c: use time.clock to measure the time, which is the default on
1832 Windows and measures wall time. On Unix, resource.getrusage is used
1833 Windows and measures wall time. On Unix, resource.getrusage is used
1833 instead and returns the CPU user time.
1834 instead and returns the CPU user time.
1834
1835
1835 -p<P>: use a precision of <P> digits to display the timing result.
1836 -p<P>: use a precision of <P> digits to display the timing result.
1836 Default: 3
1837 Default: 3
1837
1838
1838
1839
1839 Examples:
1840 Examples:
1840
1841
1841 In [1]: %timeit pass
1842 In [1]: %timeit pass
1842 10000000 loops, best of 3: 53.3 ns per loop
1843 10000000 loops, best of 3: 53.3 ns per loop
1843
1844
1844 In [2]: u = None
1845 In [2]: u = None
1845
1846
1846 In [3]: %timeit u is None
1847 In [3]: %timeit u is None
1847 10000000 loops, best of 3: 184 ns per loop
1848 10000000 loops, best of 3: 184 ns per loop
1848
1849
1849 In [4]: %timeit -r 4 u == None
1850 In [4]: %timeit -r 4 u == None
1850 1000000 loops, best of 4: 242 ns per loop
1851 1000000 loops, best of 4: 242 ns per loop
1851
1852
1852 In [5]: import time
1853 In [5]: import time
1853
1854
1854 In [6]: %timeit -n1 time.sleep(2)
1855 In [6]: %timeit -n1 time.sleep(2)
1855 1 loops, best of 3: 2 s per loop
1856 1 loops, best of 3: 2 s per loop
1856
1857
1857
1858
1858 The times reported by %timeit will be slightly higher than those
1859 The times reported by %timeit will be slightly higher than those
1859 reported by the timeit.py script when variables are accessed. This is
1860 reported by the timeit.py script when variables are accessed. This is
1860 due to the fact that %timeit executes the statement in the namespace
1861 due to the fact that %timeit executes the statement in the namespace
1861 of the shell, compared with timeit.py, which uses a single setup
1862 of the shell, compared with timeit.py, which uses a single setup
1862 statement to import function or create variables. Generally, the bias
1863 statement to import function or create variables. Generally, the bias
1863 does not matter as long as results from timeit.py are not mixed with
1864 does not matter as long as results from timeit.py are not mixed with
1864 those from %timeit."""
1865 those from %timeit."""
1865
1866
1866 import timeit
1867 import timeit
1867 import math
1868 import math
1868
1869
1869 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1870 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1870 # certain terminals. Until we figure out a robust way of
1871 # certain terminals. Until we figure out a robust way of
1871 # auto-detecting if the terminal can deal with it, use plain 'us' for
1872 # auto-detecting if the terminal can deal with it, use plain 'us' for
1872 # microseconds. I am really NOT happy about disabling the proper
1873 # microseconds. I am really NOT happy about disabling the proper
1873 # 'micro' prefix, but crashing is worse... If anyone knows what the
1874 # 'micro' prefix, but crashing is worse... If anyone knows what the
1874 # right solution for this is, I'm all ears...
1875 # right solution for this is, I'm all ears...
1875 #
1876 #
1876 # Note: using
1877 # Note: using
1877 #
1878 #
1878 # s = u'\xb5'
1879 # s = u'\xb5'
1879 # s.encode(sys.getdefaultencoding())
1880 # s.encode(sys.getdefaultencoding())
1880 #
1881 #
1881 # is not sufficient, as I've seen terminals where that fails but
1882 # is not sufficient, as I've seen terminals where that fails but
1882 # print s
1883 # print s
1883 #
1884 #
1884 # succeeds
1885 # succeeds
1885 #
1886 #
1886 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1887 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1887
1888
1888 #units = [u"s", u"ms",u'\xb5',"ns"]
1889 #units = [u"s", u"ms",u'\xb5',"ns"]
1889 units = [u"s", u"ms",u'us',"ns"]
1890 units = [u"s", u"ms",u'us',"ns"]
1890
1891
1891 scaling = [1, 1e3, 1e6, 1e9]
1892 scaling = [1, 1e3, 1e6, 1e9]
1892
1893
1893 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1894 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1894 posix=False, strict=False)
1895 posix=False, strict=False)
1895 if stmt == "":
1896 if stmt == "":
1896 return
1897 return
1897 timefunc = timeit.default_timer
1898 timefunc = timeit.default_timer
1898 number = int(getattr(opts, "n", 0))
1899 number = int(getattr(opts, "n", 0))
1899 repeat = int(getattr(opts, "r", timeit.default_repeat))
1900 repeat = int(getattr(opts, "r", timeit.default_repeat))
1900 precision = int(getattr(opts, "p", 3))
1901 precision = int(getattr(opts, "p", 3))
1901 if hasattr(opts, "t"):
1902 if hasattr(opts, "t"):
1902 timefunc = time.time
1903 timefunc = time.time
1903 if hasattr(opts, "c"):
1904 if hasattr(opts, "c"):
1904 timefunc = clock
1905 timefunc = clock
1905
1906
1906 timer = timeit.Timer(timer=timefunc)
1907 timer = timeit.Timer(timer=timefunc)
1907 # this code has tight coupling to the inner workings of timeit.Timer,
1908 # this code has tight coupling to the inner workings of timeit.Timer,
1908 # but is there a better way to achieve that the code stmt has access
1909 # but is there a better way to achieve that the code stmt has access
1909 # to the shell namespace?
1910 # to the shell namespace?
1910
1911
1911 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1912 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1912 'setup': "pass"}
1913 'setup': "pass"}
1913 # Track compilation time so it can be reported if too long
1914 # Track compilation time so it can be reported if too long
1914 # Minimum time above which compilation time will be reported
1915 # Minimum time above which compilation time will be reported
1915 tc_min = 0.1
1916 tc_min = 0.1
1916
1917
1917 t0 = clock()
1918 t0 = clock()
1918 code = compile(src, "<magic-timeit>", "exec")
1919 code = compile(src, "<magic-timeit>", "exec")
1919 tc = clock()-t0
1920 tc = clock()-t0
1920
1921
1921 ns = {}
1922 ns = {}
1922 exec code in self.shell.user_ns, ns
1923 exec code in self.shell.user_ns, ns
1923 timer.inner = ns["inner"]
1924 timer.inner = ns["inner"]
1924
1925
1925 if number == 0:
1926 if number == 0:
1926 # determine number so that 0.2 <= total time < 2.0
1927 # determine number so that 0.2 <= total time < 2.0
1927 number = 1
1928 number = 1
1928 for i in range(1, 10):
1929 for i in range(1, 10):
1929 if timer.timeit(number) >= 0.2:
1930 if timer.timeit(number) >= 0.2:
1930 break
1931 break
1931 number *= 10
1932 number *= 10
1932
1933
1933 best = min(timer.repeat(repeat, number)) / number
1934 best = min(timer.repeat(repeat, number)) / number
1934
1935
1935 if best > 0.0 and best < 1000.0:
1936 if best > 0.0 and best < 1000.0:
1936 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1937 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1937 elif best >= 1000.0:
1938 elif best >= 1000.0:
1938 order = 0
1939 order = 0
1939 else:
1940 else:
1940 order = 3
1941 order = 3
1941 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1942 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1942 precision,
1943 precision,
1943 best * scaling[order],
1944 best * scaling[order],
1944 units[order])
1945 units[order])
1945 if tc > tc_min:
1946 if tc > tc_min:
1946 print "Compiler time: %.2f s" % tc
1947 print "Compiler time: %.2f s" % tc
1947
1948
1948 @skip_doctest
1949 @skip_doctest
1949 @needs_local_scope
1950 @needs_local_scope
1950 def magic_time(self,parameter_s = ''):
1951 def magic_time(self,parameter_s = ''):
1951 """Time execution of a Python statement or expression.
1952 """Time execution of a Python statement or expression.
1952
1953
1953 The CPU and wall clock times are printed, and the value of the
1954 The CPU and wall clock times are printed, and the value of the
1954 expression (if any) is returned. Note that under Win32, system time
1955 expression (if any) is returned. Note that under Win32, system time
1955 is always reported as 0, since it can not be measured.
1956 is always reported as 0, since it can not be measured.
1956
1957
1957 This function provides very basic timing functionality. In Python
1958 This function provides very basic timing functionality. In Python
1958 2.3, the timeit module offers more control and sophistication, so this
1959 2.3, the timeit module offers more control and sophistication, so this
1959 could be rewritten to use it (patches welcome).
1960 could be rewritten to use it (patches welcome).
1960
1961
1961 Some examples:
1962 Some examples:
1962
1963
1963 In [1]: time 2**128
1964 In [1]: time 2**128
1964 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1965 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1965 Wall time: 0.00
1966 Wall time: 0.00
1966 Out[1]: 340282366920938463463374607431768211456L
1967 Out[1]: 340282366920938463463374607431768211456L
1967
1968
1968 In [2]: n = 1000000
1969 In [2]: n = 1000000
1969
1970
1970 In [3]: time sum(range(n))
1971 In [3]: time sum(range(n))
1971 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1972 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1972 Wall time: 1.37
1973 Wall time: 1.37
1973 Out[3]: 499999500000L
1974 Out[3]: 499999500000L
1974
1975
1975 In [4]: time print 'hello world'
1976 In [4]: time print 'hello world'
1976 hello world
1977 hello world
1977 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1978 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1978 Wall time: 0.00
1979 Wall time: 0.00
1979
1980
1980 Note that the time needed by Python to compile the given expression
1981 Note that the time needed by Python to compile the given expression
1981 will be reported if it is more than 0.1s. In this example, the
1982 will be reported if it is more than 0.1s. In this example, the
1982 actual exponentiation is done by Python at compilation time, so while
1983 actual exponentiation is done by Python at compilation time, so while
1983 the expression can take a noticeable amount of time to compute, that
1984 the expression can take a noticeable amount of time to compute, that
1984 time is purely due to the compilation:
1985 time is purely due to the compilation:
1985
1986
1986 In [5]: time 3**9999;
1987 In [5]: time 3**9999;
1987 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1988 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1988 Wall time: 0.00 s
1989 Wall time: 0.00 s
1989
1990
1990 In [6]: time 3**999999;
1991 In [6]: time 3**999999;
1991 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1992 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1992 Wall time: 0.00 s
1993 Wall time: 0.00 s
1993 Compiler : 0.78 s
1994 Compiler : 0.78 s
1994 """
1995 """
1995
1996
1996 # fail immediately if the given expression can't be compiled
1997 # fail immediately if the given expression can't be compiled
1997
1998
1998 expr = self.shell.prefilter(parameter_s,False)
1999 expr = self.shell.prefilter(parameter_s,False)
1999
2000
2000 # Minimum time above which compilation time will be reported
2001 # Minimum time above which compilation time will be reported
2001 tc_min = 0.1
2002 tc_min = 0.1
2002
2003
2003 try:
2004 try:
2004 mode = 'eval'
2005 mode = 'eval'
2005 t0 = clock()
2006 t0 = clock()
2006 code = compile(expr,'<timed eval>',mode)
2007 code = compile(expr,'<timed eval>',mode)
2007 tc = clock()-t0
2008 tc = clock()-t0
2008 except SyntaxError:
2009 except SyntaxError:
2009 mode = 'exec'
2010 mode = 'exec'
2010 t0 = clock()
2011 t0 = clock()
2011 code = compile(expr,'<timed exec>',mode)
2012 code = compile(expr,'<timed exec>',mode)
2012 tc = clock()-t0
2013 tc = clock()-t0
2013 # skew measurement as little as possible
2014 # skew measurement as little as possible
2014 glob = self.shell.user_ns
2015 glob = self.shell.user_ns
2015 locs = self._magic_locals
2016 locs = self._magic_locals
2016 clk = clock2
2017 clk = clock2
2017 wtime = time.time
2018 wtime = time.time
2018 # time execution
2019 # time execution
2019 wall_st = wtime()
2020 wall_st = wtime()
2020 if mode=='eval':
2021 if mode=='eval':
2021 st = clk()
2022 st = clk()
2022 out = eval(code, glob, locs)
2023 out = eval(code, glob, locs)
2023 end = clk()
2024 end = clk()
2024 else:
2025 else:
2025 st = clk()
2026 st = clk()
2026 exec code in glob, locs
2027 exec code in glob, locs
2027 end = clk()
2028 end = clk()
2028 out = None
2029 out = None
2029 wall_end = wtime()
2030 wall_end = wtime()
2030 # Compute actual times and report
2031 # Compute actual times and report
2031 wall_time = wall_end-wall_st
2032 wall_time = wall_end-wall_st
2032 cpu_user = end[0]-st[0]
2033 cpu_user = end[0]-st[0]
2033 cpu_sys = end[1]-st[1]
2034 cpu_sys = end[1]-st[1]
2034 cpu_tot = cpu_user+cpu_sys
2035 cpu_tot = cpu_user+cpu_sys
2035 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2036 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2036 (cpu_user,cpu_sys,cpu_tot)
2037 (cpu_user,cpu_sys,cpu_tot)
2037 print "Wall time: %.2f s" % wall_time
2038 print "Wall time: %.2f s" % wall_time
2038 if tc > tc_min:
2039 if tc > tc_min:
2039 print "Compiler : %.2f s" % tc
2040 print "Compiler : %.2f s" % tc
2040 return out
2041 return out
2041
2042
2042 @skip_doctest
2043 @skip_doctest
2043 def magic_macro(self,parameter_s = ''):
2044 def magic_macro(self,parameter_s = ''):
2044 """Define a macro for future re-execution. It accepts ranges of history,
2045 """Define a macro for future re-execution. It accepts ranges of history,
2045 filenames or string objects.
2046 filenames or string objects.
2046
2047
2047 Usage:\\
2048 Usage:\\
2048 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2049 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2049
2050
2050 Options:
2051 Options:
2051
2052
2052 -r: use 'raw' input. By default, the 'processed' history is used,
2053 -r: use 'raw' input. By default, the 'processed' history is used,
2053 so that magics are loaded in their transformed version to valid
2054 so that magics are loaded in their transformed version to valid
2054 Python. If this option is given, the raw input as typed as the
2055 Python. If this option is given, the raw input as typed as the
2055 command line is used instead.
2056 command line is used instead.
2056
2057
2057 This will define a global variable called `name` which is a string
2058 This will define a global variable called `name` which is a string
2058 made of joining the slices and lines you specify (n1,n2,... numbers
2059 made of joining the slices and lines you specify (n1,n2,... numbers
2059 above) from your input history into a single string. This variable
2060 above) from your input history into a single string. This variable
2060 acts like an automatic function which re-executes those lines as if
2061 acts like an automatic function which re-executes those lines as if
2061 you had typed them. You just type 'name' at the prompt and the code
2062 you had typed them. You just type 'name' at the prompt and the code
2062 executes.
2063 executes.
2063
2064
2064 The syntax for indicating input ranges is described in %history.
2065 The syntax for indicating input ranges is described in %history.
2065
2066
2066 Note: as a 'hidden' feature, you can also use traditional python slice
2067 Note: as a 'hidden' feature, you can also use traditional python slice
2067 notation, where N:M means numbers N through M-1.
2068 notation, where N:M means numbers N through M-1.
2068
2069
2069 For example, if your history contains (%hist prints it):
2070 For example, if your history contains (%hist prints it):
2070
2071
2071 44: x=1
2072 44: x=1
2072 45: y=3
2073 45: y=3
2073 46: z=x+y
2074 46: z=x+y
2074 47: print x
2075 47: print x
2075 48: a=5
2076 48: a=5
2076 49: print 'x',x,'y',y
2077 49: print 'x',x,'y',y
2077
2078
2078 you can create a macro with lines 44 through 47 (included) and line 49
2079 you can create a macro with lines 44 through 47 (included) and line 49
2079 called my_macro with:
2080 called my_macro with:
2080
2081
2081 In [55]: %macro my_macro 44-47 49
2082 In [55]: %macro my_macro 44-47 49
2082
2083
2083 Now, typing `my_macro` (without quotes) will re-execute all this code
2084 Now, typing `my_macro` (without quotes) will re-execute all this code
2084 in one pass.
2085 in one pass.
2085
2086
2086 You don't need to give the line-numbers in order, and any given line
2087 You don't need to give the line-numbers in order, and any given line
2087 number can appear multiple times. You can assemble macros with any
2088 number can appear multiple times. You can assemble macros with any
2088 lines from your input history in any order.
2089 lines from your input history in any order.
2089
2090
2090 The macro is a simple object which holds its value in an attribute,
2091 The macro is a simple object which holds its value in an attribute,
2091 but IPython's display system checks for macros and executes them as
2092 but IPython's display system checks for macros and executes them as
2092 code instead of printing them when you type their name.
2093 code instead of printing them when you type their name.
2093
2094
2094 You can view a macro's contents by explicitly printing it with:
2095 You can view a macro's contents by explicitly printing it with:
2095
2096
2096 'print macro_name'.
2097 'print macro_name'.
2097
2098
2098 """
2099 """
2099 opts,args = self.parse_options(parameter_s,'r',mode='list')
2100 opts,args = self.parse_options(parameter_s,'r',mode='list')
2100 if not args: # List existing macros
2101 if not args: # List existing macros
2101 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2102 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2102 isinstance(v, Macro))
2103 isinstance(v, Macro))
2103 if len(args) == 1:
2104 if len(args) == 1:
2104 raise UsageError(
2105 raise UsageError(
2105 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2106 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2106 name, codefrom = args[0], " ".join(args[1:])
2107 name, codefrom = args[0], " ".join(args[1:])
2107
2108
2108 #print 'rng',ranges # dbg
2109 #print 'rng',ranges # dbg
2109 try:
2110 try:
2110 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2111 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2111 except (ValueError, TypeError) as e:
2112 except (ValueError, TypeError) as e:
2112 print e.args[0]
2113 print e.args[0]
2113 return
2114 return
2114 macro = Macro(lines)
2115 macro = Macro(lines)
2115 self.shell.define_macro(name, macro)
2116 self.shell.define_macro(name, macro)
2116 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2117 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2117 print '=== Macro contents: ==='
2118 print '=== Macro contents: ==='
2118 print macro,
2119 print macro,
2119
2120
2120 def magic_save(self,parameter_s = ''):
2121 def magic_save(self,parameter_s = ''):
2121 """Save a set of lines or a macro to a given filename.
2122 """Save a set of lines or a macro to a given filename.
2122
2123
2123 Usage:\\
2124 Usage:\\
2124 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2125 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2125
2126
2126 Options:
2127 Options:
2127
2128
2128 -r: use 'raw' input. By default, the 'processed' history is used,
2129 -r: use 'raw' input. By default, the 'processed' history is used,
2129 so that magics are loaded in their transformed version to valid
2130 so that magics are loaded in their transformed version to valid
2130 Python. If this option is given, the raw input as typed as the
2131 Python. If this option is given, the raw input as typed as the
2131 command line is used instead.
2132 command line is used instead.
2132
2133
2133 This function uses the same syntax as %history for input ranges,
2134 This function uses the same syntax as %history for input ranges,
2134 then saves the lines to the filename you specify.
2135 then saves the lines to the filename you specify.
2135
2136
2136 It adds a '.py' extension to the file if you don't do so yourself, and
2137 It adds a '.py' extension to the file if you don't do so yourself, and
2137 it asks for confirmation before overwriting existing files."""
2138 it asks for confirmation before overwriting existing files."""
2138
2139
2139 opts,args = self.parse_options(parameter_s,'r',mode='list')
2140 opts,args = self.parse_options(parameter_s,'r',mode='list')
2140 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2141 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2141 if not fname.endswith('.py'):
2142 if not fname.endswith('.py'):
2142 fname += '.py'
2143 fname += '.py'
2143 if os.path.isfile(fname):
2144 if os.path.isfile(fname):
2144 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2145 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2145 if ans.lower() not in ['y','yes']:
2146 if ans.lower() not in ['y','yes']:
2146 print 'Operation cancelled.'
2147 print 'Operation cancelled.'
2147 return
2148 return
2148 try:
2149 try:
2149 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2150 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2150 except (TypeError, ValueError) as e:
2151 except (TypeError, ValueError) as e:
2151 print e.args[0]
2152 print e.args[0]
2152 return
2153 return
2153 with py3compat.open(fname,'w', encoding="utf-8") as f:
2154 with py3compat.open(fname,'w', encoding="utf-8") as f:
2154 f.write(u"# coding: utf-8\n")
2155 f.write(u"# coding: utf-8\n")
2155 f.write(py3compat.cast_unicode(cmds))
2156 f.write(py3compat.cast_unicode(cmds))
2156 print 'The following commands were written to file `%s`:' % fname
2157 print 'The following commands were written to file `%s`:' % fname
2157 print cmds
2158 print cmds
2158
2159
2159 def magic_pastebin(self, parameter_s = ''):
2160 def magic_pastebin(self, parameter_s = ''):
2160 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2161 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2161 try:
2162 try:
2162 code = self.shell.find_user_code(parameter_s)
2163 code = self.shell.find_user_code(parameter_s)
2163 except (ValueError, TypeError) as e:
2164 except (ValueError, TypeError) as e:
2164 print e.args[0]
2165 print e.args[0]
2165 return
2166 return
2166 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2167 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2167 id = pbserver.pastes.newPaste("python", code)
2168 id = pbserver.pastes.newPaste("python", code)
2168 return "http://paste.pocoo.org/show/" + id
2169 return "http://paste.pocoo.org/show/" + id
2169
2170
2170 def magic_loadpy(self, arg_s):
2171 def magic_loadpy(self, arg_s):
2171 """Load a .py python script into the GUI console.
2172 """Load a .py python script into the GUI console.
2172
2173
2173 This magic command can either take a local filename or a url::
2174 This magic command can either take a local filename or a url::
2174
2175
2175 %loadpy myscript.py
2176 %loadpy myscript.py
2176 %loadpy http://www.example.com/myscript.py
2177 %loadpy http://www.example.com/myscript.py
2177 """
2178 """
2178 arg_s = unquote_filename(arg_s)
2179 arg_s = unquote_filename(arg_s)
2179 remote_url = arg_s.startswith(('http://', 'https://'))
2180 remote_url = arg_s.startswith(('http://', 'https://'))
2180 local_url = not remote_url
2181 local_url = not remote_url
2181 if local_url and not arg_s.endswith('.py'):
2182 if local_url and not arg_s.endswith('.py'):
2182 # Local files must be .py; for remote URLs it's possible that the
2183 # Local files must be .py; for remote URLs it's possible that the
2183 # fetch URL doesn't have a .py in it (many servers have an opaque
2184 # fetch URL doesn't have a .py in it (many servers have an opaque
2184 # URL, such as scipy-central.org).
2185 # URL, such as scipy-central.org).
2185 raise ValueError('%%load only works with .py files: %s' % arg_s)
2186 raise ValueError('%%load only works with .py files: %s' % arg_s)
2186 if remote_url:
2187 if remote_url:
2187 import urllib2
2188 import urllib2
2188 fileobj = urllib2.urlopen(arg_s)
2189 fileobj = urllib2.urlopen(arg_s)
2189 # While responses have a .info().getencoding() way of asking for
2190 # While responses have a .info().getencoding() way of asking for
2190 # their encoding, in *many* cases the return value is bogus. In
2191 # their encoding, in *many* cases the return value is bogus. In
2191 # the wild, servers serving utf-8 but declaring latin-1 are
2192 # the wild, servers serving utf-8 but declaring latin-1 are
2192 # extremely common, as the old HTTP standards specify latin-1 as
2193 # extremely common, as the old HTTP standards specify latin-1 as
2193 # the default but many modern filesystems use utf-8. So we can NOT
2194 # the default but many modern filesystems use utf-8. So we can NOT
2194 # rely on the headers. Short of building complex encoding-guessing
2195 # rely on the headers. Short of building complex encoding-guessing
2195 # logic, going with utf-8 is a simple solution likely to be right
2196 # logic, going with utf-8 is a simple solution likely to be right
2196 # in most real-world cases.
2197 # in most real-world cases.
2197 linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
2198 linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
2198 fileobj.close()
2199 fileobj.close()
2199 else:
2200 else:
2200 with open(arg_s) as fileobj:
2201 with open(arg_s) as fileobj:
2201 linesource = fileobj.read().splitlines()
2202 linesource = fileobj.read().splitlines()
2202
2203
2203 # Strip out encoding declarations
2204 # Strip out encoding declarations
2204 lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
2205 lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
2205
2206
2206 self.set_next_input(os.linesep.join(lines))
2207 self.set_next_input(os.linesep.join(lines))
2207
2208
2208 def _find_edit_target(self, args, opts, last_call):
2209 def _find_edit_target(self, args, opts, last_call):
2209 """Utility method used by magic_edit to find what to edit."""
2210 """Utility method used by magic_edit to find what to edit."""
2210
2211
2211 def make_filename(arg):
2212 def make_filename(arg):
2212 "Make a filename from the given args"
2213 "Make a filename from the given args"
2213 arg = unquote_filename(arg)
2214 arg = unquote_filename(arg)
2214 try:
2215 try:
2215 filename = get_py_filename(arg)
2216 filename = get_py_filename(arg)
2216 except IOError:
2217 except IOError:
2217 # If it ends with .py but doesn't already exist, assume we want
2218 # If it ends with .py but doesn't already exist, assume we want
2218 # a new file.
2219 # a new file.
2219 if arg.endswith('.py'):
2220 if arg.endswith('.py'):
2220 filename = arg
2221 filename = arg
2221 else:
2222 else:
2222 filename = None
2223 filename = None
2223 return filename
2224 return filename
2224
2225
2225 # Set a few locals from the options for convenience:
2226 # Set a few locals from the options for convenience:
2226 opts_prev = 'p' in opts
2227 opts_prev = 'p' in opts
2227 opts_raw = 'r' in opts
2228 opts_raw = 'r' in opts
2228
2229
2229 # custom exceptions
2230 # custom exceptions
2230 class DataIsObject(Exception): pass
2231 class DataIsObject(Exception): pass
2231
2232
2232 # Default line number value
2233 # Default line number value
2233 lineno = opts.get('n',None)
2234 lineno = opts.get('n',None)
2234
2235
2235 if opts_prev:
2236 if opts_prev:
2236 args = '_%s' % last_call[0]
2237 args = '_%s' % last_call[0]
2237 if not self.shell.user_ns.has_key(args):
2238 if not self.shell.user_ns.has_key(args):
2238 args = last_call[1]
2239 args = last_call[1]
2239
2240
2240 # use last_call to remember the state of the previous call, but don't
2241 # use last_call to remember the state of the previous call, but don't
2241 # let it be clobbered by successive '-p' calls.
2242 # let it be clobbered by successive '-p' calls.
2242 try:
2243 try:
2243 last_call[0] = self.shell.displayhook.prompt_count
2244 last_call[0] = self.shell.displayhook.prompt_count
2244 if not opts_prev:
2245 if not opts_prev:
2245 last_call[1] = parameter_s
2246 last_call[1] = parameter_s
2246 except:
2247 except:
2247 pass
2248 pass
2248
2249
2249 # by default this is done with temp files, except when the given
2250 # by default this is done with temp files, except when the given
2250 # arg is a filename
2251 # arg is a filename
2251 use_temp = True
2252 use_temp = True
2252
2253
2253 data = ''
2254 data = ''
2254
2255
2255 # First, see if the arguments should be a filename.
2256 # First, see if the arguments should be a filename.
2256 filename = make_filename(args)
2257 filename = make_filename(args)
2257 if filename:
2258 if filename:
2258 use_temp = False
2259 use_temp = False
2259 elif args:
2260 elif args:
2260 # Mode where user specifies ranges of lines, like in %macro.
2261 # Mode where user specifies ranges of lines, like in %macro.
2261 data = self.extract_input_lines(args, opts_raw)
2262 data = self.extract_input_lines(args, opts_raw)
2262 if not data:
2263 if not data:
2263 try:
2264 try:
2264 # Load the parameter given as a variable. If not a string,
2265 # Load the parameter given as a variable. If not a string,
2265 # process it as an object instead (below)
2266 # process it as an object instead (below)
2266
2267
2267 #print '*** args',args,'type',type(args) # dbg
2268 #print '*** args',args,'type',type(args) # dbg
2268 data = eval(args, self.shell.user_ns)
2269 data = eval(args, self.shell.user_ns)
2269 if not isinstance(data, basestring):
2270 if not isinstance(data, basestring):
2270 raise DataIsObject
2271 raise DataIsObject
2271
2272
2272 except (NameError,SyntaxError):
2273 except (NameError,SyntaxError):
2273 # given argument is not a variable, try as a filename
2274 # given argument is not a variable, try as a filename
2274 filename = make_filename(args)
2275 filename = make_filename(args)
2275 if filename is None:
2276 if filename is None:
2276 warn("Argument given (%s) can't be found as a variable "
2277 warn("Argument given (%s) can't be found as a variable "
2277 "or as a filename." % args)
2278 "or as a filename." % args)
2278 return
2279 return
2279 use_temp = False
2280 use_temp = False
2280
2281
2281 except DataIsObject:
2282 except DataIsObject:
2282 # macros have a special edit function
2283 # macros have a special edit function
2283 if isinstance(data, Macro):
2284 if isinstance(data, Macro):
2284 raise MacroToEdit(data)
2285 raise MacroToEdit(data)
2285
2286
2286 # For objects, try to edit the file where they are defined
2287 # For objects, try to edit the file where they are defined
2287 try:
2288 try:
2288 filename = inspect.getabsfile(data)
2289 filename = inspect.getabsfile(data)
2289 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2290 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2290 # class created by %edit? Try to find source
2291 # class created by %edit? Try to find source
2291 # by looking for method definitions instead, the
2292 # by looking for method definitions instead, the
2292 # __module__ in those classes is FakeModule.
2293 # __module__ in those classes is FakeModule.
2293 attrs = [getattr(data, aname) for aname in dir(data)]
2294 attrs = [getattr(data, aname) for aname in dir(data)]
2294 for attr in attrs:
2295 for attr in attrs:
2295 if not inspect.ismethod(attr):
2296 if not inspect.ismethod(attr):
2296 continue
2297 continue
2297 filename = inspect.getabsfile(attr)
2298 filename = inspect.getabsfile(attr)
2298 if filename and 'fakemodule' not in filename.lower():
2299 if filename and 'fakemodule' not in filename.lower():
2299 # change the attribute to be the edit target instead
2300 # change the attribute to be the edit target instead
2300 data = attr
2301 data = attr
2301 break
2302 break
2302
2303
2303 datafile = 1
2304 datafile = 1
2304 except TypeError:
2305 except TypeError:
2305 filename = make_filename(args)
2306 filename = make_filename(args)
2306 datafile = 1
2307 datafile = 1
2307 warn('Could not find file where `%s` is defined.\n'
2308 warn('Could not find file where `%s` is defined.\n'
2308 'Opening a file named `%s`' % (args,filename))
2309 'Opening a file named `%s`' % (args,filename))
2309 # Now, make sure we can actually read the source (if it was in
2310 # Now, make sure we can actually read the source (if it was in
2310 # a temp file it's gone by now).
2311 # a temp file it's gone by now).
2311 if datafile:
2312 if datafile:
2312 try:
2313 try:
2313 if lineno is None:
2314 if lineno is None:
2314 lineno = inspect.getsourcelines(data)[1]
2315 lineno = inspect.getsourcelines(data)[1]
2315 except IOError:
2316 except IOError:
2316 filename = make_filename(args)
2317 filename = make_filename(args)
2317 if filename is None:
2318 if filename is None:
2318 warn('The file `%s` where `%s` was defined cannot '
2319 warn('The file `%s` where `%s` was defined cannot '
2319 'be read.' % (filename,data))
2320 'be read.' % (filename,data))
2320 return
2321 return
2321 use_temp = False
2322 use_temp = False
2322
2323
2323 if use_temp:
2324 if use_temp:
2324 filename = self.shell.mktempfile(data)
2325 filename = self.shell.mktempfile(data)
2325 print 'IPython will make a temporary file named:',filename
2326 print 'IPython will make a temporary file named:',filename
2326
2327
2327 return filename, lineno, use_temp
2328 return filename, lineno, use_temp
2328
2329
2329 def _edit_macro(self,mname,macro):
2330 def _edit_macro(self,mname,macro):
2330 """open an editor with the macro data in a file"""
2331 """open an editor with the macro data in a file"""
2331 filename = self.shell.mktempfile(macro.value)
2332 filename = self.shell.mktempfile(macro.value)
2332 self.shell.hooks.editor(filename)
2333 self.shell.hooks.editor(filename)
2333
2334
2334 # and make a new macro object, to replace the old one
2335 # and make a new macro object, to replace the old one
2335 mfile = open(filename)
2336 mfile = open(filename)
2336 mvalue = mfile.read()
2337 mvalue = mfile.read()
2337 mfile.close()
2338 mfile.close()
2338 self.shell.user_ns[mname] = Macro(mvalue)
2339 self.shell.user_ns[mname] = Macro(mvalue)
2339
2340
2340 def magic_ed(self,parameter_s=''):
2341 def magic_ed(self,parameter_s=''):
2341 """Alias to %edit."""
2342 """Alias to %edit."""
2342 return self.magic_edit(parameter_s)
2343 return self.magic_edit(parameter_s)
2343
2344
2344 @skip_doctest
2345 @skip_doctest
2345 def magic_edit(self,parameter_s='',last_call=['','']):
2346 def magic_edit(self,parameter_s='',last_call=['','']):
2346 """Bring up an editor and execute the resulting code.
2347 """Bring up an editor and execute the resulting code.
2347
2348
2348 Usage:
2349 Usage:
2349 %edit [options] [args]
2350 %edit [options] [args]
2350
2351
2351 %edit runs IPython's editor hook. The default version of this hook is
2352 %edit runs IPython's editor hook. The default version of this hook is
2352 set to call the editor specified by your $EDITOR environment variable.
2353 set to call the editor specified by your $EDITOR environment variable.
2353 If this isn't found, it will default to vi under Linux/Unix and to
2354 If this isn't found, it will default to vi under Linux/Unix and to
2354 notepad under Windows. See the end of this docstring for how to change
2355 notepad under Windows. See the end of this docstring for how to change
2355 the editor hook.
2356 the editor hook.
2356
2357
2357 You can also set the value of this editor via the
2358 You can also set the value of this editor via the
2358 ``TerminalInteractiveShell.editor`` option in your configuration file.
2359 ``TerminalInteractiveShell.editor`` option in your configuration file.
2359 This is useful if you wish to use a different editor from your typical
2360 This is useful if you wish to use a different editor from your typical
2360 default with IPython (and for Windows users who typically don't set
2361 default with IPython (and for Windows users who typically don't set
2361 environment variables).
2362 environment variables).
2362
2363
2363 This command allows you to conveniently edit multi-line code right in
2364 This command allows you to conveniently edit multi-line code right in
2364 your IPython session.
2365 your IPython session.
2365
2366
2366 If called without arguments, %edit opens up an empty editor with a
2367 If called without arguments, %edit opens up an empty editor with a
2367 temporary file and will execute the contents of this file when you
2368 temporary file and will execute the contents of this file when you
2368 close it (don't forget to save it!).
2369 close it (don't forget to save it!).
2369
2370
2370
2371
2371 Options:
2372 Options:
2372
2373
2373 -n <number>: open the editor at a specified line number. By default,
2374 -n <number>: open the editor at a specified line number. By default,
2374 the IPython editor hook uses the unix syntax 'editor +N filename', but
2375 the IPython editor hook uses the unix syntax 'editor +N filename', but
2375 you can configure this by providing your own modified hook if your
2376 you can configure this by providing your own modified hook if your
2376 favorite editor supports line-number specifications with a different
2377 favorite editor supports line-number specifications with a different
2377 syntax.
2378 syntax.
2378
2379
2379 -p: this will call the editor with the same data as the previous time
2380 -p: this will call the editor with the same data as the previous time
2380 it was used, regardless of how long ago (in your current session) it
2381 it was used, regardless of how long ago (in your current session) it
2381 was.
2382 was.
2382
2383
2383 -r: use 'raw' input. This option only applies to input taken from the
2384 -r: use 'raw' input. This option only applies to input taken from the
2384 user's history. By default, the 'processed' history is used, so that
2385 user's history. By default, the 'processed' history is used, so that
2385 magics are loaded in their transformed version to valid Python. If
2386 magics are loaded in their transformed version to valid Python. If
2386 this option is given, the raw input as typed as the command line is
2387 this option is given, the raw input as typed as the command line is
2387 used instead. When you exit the editor, it will be executed by
2388 used instead. When you exit the editor, it will be executed by
2388 IPython's own processor.
2389 IPython's own processor.
2389
2390
2390 -x: do not execute the edited code immediately upon exit. This is
2391 -x: do not execute the edited code immediately upon exit. This is
2391 mainly useful if you are editing programs which need to be called with
2392 mainly useful if you are editing programs which need to be called with
2392 command line arguments, which you can then do using %run.
2393 command line arguments, which you can then do using %run.
2393
2394
2394
2395
2395 Arguments:
2396 Arguments:
2396
2397
2397 If arguments are given, the following possibilities exist:
2398 If arguments are given, the following possibilities exist:
2398
2399
2399 - If the argument is a filename, IPython will load that into the
2400 - If the argument is a filename, IPython will load that into the
2400 editor. It will execute its contents with execfile() when you exit,
2401 editor. It will execute its contents with execfile() when you exit,
2401 loading any code in the file into your interactive namespace.
2402 loading any code in the file into your interactive namespace.
2402
2403
2403 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2404 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2404 The syntax is the same as in the %history magic.
2405 The syntax is the same as in the %history magic.
2405
2406
2406 - If the argument is a string variable, its contents are loaded
2407 - If the argument is a string variable, its contents are loaded
2407 into the editor. You can thus edit any string which contains
2408 into the editor. You can thus edit any string which contains
2408 python code (including the result of previous edits).
2409 python code (including the result of previous edits).
2409
2410
2410 - If the argument is the name of an object (other than a string),
2411 - If the argument is the name of an object (other than a string),
2411 IPython will try to locate the file where it was defined and open the
2412 IPython will try to locate the file where it was defined and open the
2412 editor at the point where it is defined. You can use `%edit function`
2413 editor at the point where it is defined. You can use `%edit function`
2413 to load an editor exactly at the point where 'function' is defined,
2414 to load an editor exactly at the point where 'function' is defined,
2414 edit it and have the file be executed automatically.
2415 edit it and have the file be executed automatically.
2415
2416
2416 - If the object is a macro (see %macro for details), this opens up your
2417 - If the object is a macro (see %macro for details), this opens up your
2417 specified editor with a temporary file containing the macro's data.
2418 specified editor with a temporary file containing the macro's data.
2418 Upon exit, the macro is reloaded with the contents of the file.
2419 Upon exit, the macro is reloaded with the contents of the file.
2419
2420
2420 Note: opening at an exact line is only supported under Unix, and some
2421 Note: opening at an exact line is only supported under Unix, and some
2421 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2422 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2422 '+NUMBER' parameter necessary for this feature. Good editors like
2423 '+NUMBER' parameter necessary for this feature. Good editors like
2423 (X)Emacs, vi, jed, pico and joe all do.
2424 (X)Emacs, vi, jed, pico and joe all do.
2424
2425
2425 After executing your code, %edit will return as output the code you
2426 After executing your code, %edit will return as output the code you
2426 typed in the editor (except when it was an existing file). This way
2427 typed in the editor (except when it was an existing file). This way
2427 you can reload the code in further invocations of %edit as a variable,
2428 you can reload the code in further invocations of %edit as a variable,
2428 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2429 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2429 the output.
2430 the output.
2430
2431
2431 Note that %edit is also available through the alias %ed.
2432 Note that %edit is also available through the alias %ed.
2432
2433
2433 This is an example of creating a simple function inside the editor and
2434 This is an example of creating a simple function inside the editor and
2434 then modifying it. First, start up the editor:
2435 then modifying it. First, start up the editor:
2435
2436
2436 In [1]: ed
2437 In [1]: ed
2437 Editing... done. Executing edited code...
2438 Editing... done. Executing edited code...
2438 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2439 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2439
2440
2440 We can then call the function foo():
2441 We can then call the function foo():
2441
2442
2442 In [2]: foo()
2443 In [2]: foo()
2443 foo() was defined in an editing session
2444 foo() was defined in an editing session
2444
2445
2445 Now we edit foo. IPython automatically loads the editor with the
2446 Now we edit foo. IPython automatically loads the editor with the
2446 (temporary) file where foo() was previously defined:
2447 (temporary) file where foo() was previously defined:
2447
2448
2448 In [3]: ed foo
2449 In [3]: ed foo
2449 Editing... done. Executing edited code...
2450 Editing... done. Executing edited code...
2450
2451
2451 And if we call foo() again we get the modified version:
2452 And if we call foo() again we get the modified version:
2452
2453
2453 In [4]: foo()
2454 In [4]: foo()
2454 foo() has now been changed!
2455 foo() has now been changed!
2455
2456
2456 Here is an example of how to edit a code snippet successive
2457 Here is an example of how to edit a code snippet successive
2457 times. First we call the editor:
2458 times. First we call the editor:
2458
2459
2459 In [5]: ed
2460 In [5]: ed
2460 Editing... done. Executing edited code...
2461 Editing... done. Executing edited code...
2461 hello
2462 hello
2462 Out[5]: "print 'hello'n"
2463 Out[5]: "print 'hello'n"
2463
2464
2464 Now we call it again with the previous output (stored in _):
2465 Now we call it again with the previous output (stored in _):
2465
2466
2466 In [6]: ed _
2467 In [6]: ed _
2467 Editing... done. Executing edited code...
2468 Editing... done. Executing edited code...
2468 hello world
2469 hello world
2469 Out[6]: "print 'hello world'n"
2470 Out[6]: "print 'hello world'n"
2470
2471
2471 Now we call it with the output #8 (stored in _8, also as Out[8]):
2472 Now we call it with the output #8 (stored in _8, also as Out[8]):
2472
2473
2473 In [7]: ed _8
2474 In [7]: ed _8
2474 Editing... done. Executing edited code...
2475 Editing... done. Executing edited code...
2475 hello again
2476 hello again
2476 Out[7]: "print 'hello again'n"
2477 Out[7]: "print 'hello again'n"
2477
2478
2478
2479
2479 Changing the default editor hook:
2480 Changing the default editor hook:
2480
2481
2481 If you wish to write your own editor hook, you can put it in a
2482 If you wish to write your own editor hook, you can put it in a
2482 configuration file which you load at startup time. The default hook
2483 configuration file which you load at startup time. The default hook
2483 is defined in the IPython.core.hooks module, and you can use that as a
2484 is defined in the IPython.core.hooks module, and you can use that as a
2484 starting example for further modifications. That file also has
2485 starting example for further modifications. That file also has
2485 general instructions on how to set a new hook for use once you've
2486 general instructions on how to set a new hook for use once you've
2486 defined it."""
2487 defined it."""
2487 opts,args = self.parse_options(parameter_s,'prxn:')
2488 opts,args = self.parse_options(parameter_s,'prxn:')
2488
2489
2489 try:
2490 try:
2490 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2491 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2491 except MacroToEdit as e:
2492 except MacroToEdit as e:
2492 self._edit_macro(args, e.args[0])
2493 self._edit_macro(args, e.args[0])
2493 return
2494 return
2494
2495
2495 # do actual editing here
2496 # do actual editing here
2496 print 'Editing...',
2497 print 'Editing...',
2497 sys.stdout.flush()
2498 sys.stdout.flush()
2498 try:
2499 try:
2499 # Quote filenames that may have spaces in them
2500 # Quote filenames that may have spaces in them
2500 if ' ' in filename:
2501 if ' ' in filename:
2501 filename = "'%s'" % filename
2502 filename = "'%s'" % filename
2502 self.shell.hooks.editor(filename,lineno)
2503 self.shell.hooks.editor(filename,lineno)
2503 except TryNext:
2504 except TryNext:
2504 warn('Could not open editor')
2505 warn('Could not open editor')
2505 return
2506 return
2506
2507
2507 # XXX TODO: should this be generalized for all string vars?
2508 # XXX TODO: should this be generalized for all string vars?
2508 # For now, this is special-cased to blocks created by cpaste
2509 # For now, this is special-cased to blocks created by cpaste
2509 if args.strip() == 'pasted_block':
2510 if args.strip() == 'pasted_block':
2510 self.shell.user_ns['pasted_block'] = file_read(filename)
2511 self.shell.user_ns['pasted_block'] = file_read(filename)
2511
2512
2512 if 'x' in opts: # -x prevents actual execution
2513 if 'x' in opts: # -x prevents actual execution
2513 print
2514 print
2514 else:
2515 else:
2515 print 'done. Executing edited code...'
2516 print 'done. Executing edited code...'
2516 if 'r' in opts: # Untranslated IPython code
2517 if 'r' in opts: # Untranslated IPython code
2517 self.shell.run_cell(file_read(filename),
2518 self.shell.run_cell(file_read(filename),
2518 store_history=False)
2519 store_history=False)
2519 else:
2520 else:
2520 self.shell.safe_execfile(filename,self.shell.user_ns,
2521 self.shell.safe_execfile(filename,self.shell.user_ns,
2521 self.shell.user_ns)
2522 self.shell.user_ns)
2522
2523
2523 if is_temp:
2524 if is_temp:
2524 try:
2525 try:
2525 return open(filename).read()
2526 return open(filename).read()
2526 except IOError,msg:
2527 except IOError,msg:
2527 if msg.filename == filename:
2528 if msg.filename == filename:
2528 warn('File not found. Did you forget to save?')
2529 warn('File not found. Did you forget to save?')
2529 return
2530 return
2530 else:
2531 else:
2531 self.shell.showtraceback()
2532 self.shell.showtraceback()
2532
2533
2533 def magic_xmode(self,parameter_s = ''):
2534 def magic_xmode(self,parameter_s = ''):
2534 """Switch modes for the exception handlers.
2535 """Switch modes for the exception handlers.
2535
2536
2536 Valid modes: Plain, Context and Verbose.
2537 Valid modes: Plain, Context and Verbose.
2537
2538
2538 If called without arguments, acts as a toggle."""
2539 If called without arguments, acts as a toggle."""
2539
2540
2540 def xmode_switch_err(name):
2541 def xmode_switch_err(name):
2541 warn('Error changing %s exception modes.\n%s' %
2542 warn('Error changing %s exception modes.\n%s' %
2542 (name,sys.exc_info()[1]))
2543 (name,sys.exc_info()[1]))
2543
2544
2544 shell = self.shell
2545 shell = self.shell
2545 new_mode = parameter_s.strip().capitalize()
2546 new_mode = parameter_s.strip().capitalize()
2546 try:
2547 try:
2547 shell.InteractiveTB.set_mode(mode=new_mode)
2548 shell.InteractiveTB.set_mode(mode=new_mode)
2548 print 'Exception reporting mode:',shell.InteractiveTB.mode
2549 print 'Exception reporting mode:',shell.InteractiveTB.mode
2549 except:
2550 except:
2550 xmode_switch_err('user')
2551 xmode_switch_err('user')
2551
2552
2552 def magic_colors(self,parameter_s = ''):
2553 def magic_colors(self,parameter_s = ''):
2553 """Switch color scheme for prompts, info system and exception handlers.
2554 """Switch color scheme for prompts, info system and exception handlers.
2554
2555
2555 Currently implemented schemes: NoColor, Linux, LightBG.
2556 Currently implemented schemes: NoColor, Linux, LightBG.
2556
2557
2557 Color scheme names are not case-sensitive.
2558 Color scheme names are not case-sensitive.
2558
2559
2559 Examples
2560 Examples
2560 --------
2561 --------
2561 To get a plain black and white terminal::
2562 To get a plain black and white terminal::
2562
2563
2563 %colors nocolor
2564 %colors nocolor
2564 """
2565 """
2565
2566
2566 def color_switch_err(name):
2567 def color_switch_err(name):
2567 warn('Error changing %s color schemes.\n%s' %
2568 warn('Error changing %s color schemes.\n%s' %
2568 (name,sys.exc_info()[1]))
2569 (name,sys.exc_info()[1]))
2569
2570
2570
2571
2571 new_scheme = parameter_s.strip()
2572 new_scheme = parameter_s.strip()
2572 if not new_scheme:
2573 if not new_scheme:
2573 raise UsageError(
2574 raise UsageError(
2574 "%colors: you must specify a color scheme. See '%colors?'")
2575 "%colors: you must specify a color scheme. See '%colors?'")
2575 return
2576 return
2576 # local shortcut
2577 # local shortcut
2577 shell = self.shell
2578 shell = self.shell
2578
2579
2579 import IPython.utils.rlineimpl as readline
2580 import IPython.utils.rlineimpl as readline
2580
2581
2581 if not shell.colors_force and \
2582 if not shell.colors_force and \
2582 not readline.have_readline and sys.platform == "win32":
2583 not readline.have_readline and sys.platform == "win32":
2583 msg = """\
2584 msg = """\
2584 Proper color support under MS Windows requires the pyreadline library.
2585 Proper color support under MS Windows requires the pyreadline library.
2585 You can find it at:
2586 You can find it at:
2586 http://ipython.org/pyreadline.html
2587 http://ipython.org/pyreadline.html
2587 Gary's readline needs the ctypes module, from:
2588 Gary's readline needs the ctypes module, from:
2588 http://starship.python.net/crew/theller/ctypes
2589 http://starship.python.net/crew/theller/ctypes
2589 (Note that ctypes is already part of Python versions 2.5 and newer).
2590 (Note that ctypes is already part of Python versions 2.5 and newer).
2590
2591
2591 Defaulting color scheme to 'NoColor'"""
2592 Defaulting color scheme to 'NoColor'"""
2592 new_scheme = 'NoColor'
2593 new_scheme = 'NoColor'
2593 warn(msg)
2594 warn(msg)
2594
2595
2595 # readline option is 0
2596 # readline option is 0
2596 if not shell.colors_force and not shell.has_readline:
2597 if not shell.colors_force and not shell.has_readline:
2597 new_scheme = 'NoColor'
2598 new_scheme = 'NoColor'
2598
2599
2599 # Set prompt colors
2600 # Set prompt colors
2600 try:
2601 try:
2601 shell.prompt_manager.color_scheme = new_scheme
2602 shell.prompt_manager.color_scheme = new_scheme
2602 except:
2603 except:
2603 color_switch_err('prompt')
2604 color_switch_err('prompt')
2604 else:
2605 else:
2605 shell.colors = \
2606 shell.colors = \
2606 shell.prompt_manager.color_scheme_table.active_scheme_name
2607 shell.prompt_manager.color_scheme_table.active_scheme_name
2607 # Set exception colors
2608 # Set exception colors
2608 try:
2609 try:
2609 shell.InteractiveTB.set_colors(scheme = new_scheme)
2610 shell.InteractiveTB.set_colors(scheme = new_scheme)
2610 shell.SyntaxTB.set_colors(scheme = new_scheme)
2611 shell.SyntaxTB.set_colors(scheme = new_scheme)
2611 except:
2612 except:
2612 color_switch_err('exception')
2613 color_switch_err('exception')
2613
2614
2614 # Set info (for 'object?') colors
2615 # Set info (for 'object?') colors
2615 if shell.color_info:
2616 if shell.color_info:
2616 try:
2617 try:
2617 shell.inspector.set_active_scheme(new_scheme)
2618 shell.inspector.set_active_scheme(new_scheme)
2618 except:
2619 except:
2619 color_switch_err('object inspector')
2620 color_switch_err('object inspector')
2620 else:
2621 else:
2621 shell.inspector.set_active_scheme('NoColor')
2622 shell.inspector.set_active_scheme('NoColor')
2622
2623
2623 def magic_pprint(self, parameter_s=''):
2624 def magic_pprint(self, parameter_s=''):
2624 """Toggle pretty printing on/off."""
2625 """Toggle pretty printing on/off."""
2625 ptformatter = self.shell.display_formatter.formatters['text/plain']
2626 ptformatter = self.shell.display_formatter.formatters['text/plain']
2626 ptformatter.pprint = bool(1 - ptformatter.pprint)
2627 ptformatter.pprint = bool(1 - ptformatter.pprint)
2627 print 'Pretty printing has been turned', \
2628 print 'Pretty printing has been turned', \
2628 ['OFF','ON'][ptformatter.pprint]
2629 ['OFF','ON'][ptformatter.pprint]
2629
2630
2630 #......................................................................
2631 #......................................................................
2631 # Functions to implement unix shell-type things
2632 # Functions to implement unix shell-type things
2632
2633
2633 @skip_doctest
2634 @skip_doctest
2634 def magic_alias(self, parameter_s = ''):
2635 def magic_alias(self, parameter_s = ''):
2635 """Define an alias for a system command.
2636 """Define an alias for a system command.
2636
2637
2637 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2638 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2638
2639
2639 Then, typing 'alias_name params' will execute the system command 'cmd
2640 Then, typing 'alias_name params' will execute the system command 'cmd
2640 params' (from your underlying operating system).
2641 params' (from your underlying operating system).
2641
2642
2642 Aliases have lower precedence than magic functions and Python normal
2643 Aliases have lower precedence than magic functions and Python normal
2643 variables, so if 'foo' is both a Python variable and an alias, the
2644 variables, so if 'foo' is both a Python variable and an alias, the
2644 alias can not be executed until 'del foo' removes the Python variable.
2645 alias can not be executed until 'del foo' removes the Python variable.
2645
2646
2646 You can use the %l specifier in an alias definition to represent the
2647 You can use the %l specifier in an alias definition to represent the
2647 whole line when the alias is called. For example:
2648 whole line when the alias is called. For example:
2648
2649
2649 In [2]: alias bracket echo "Input in brackets: <%l>"
2650 In [2]: alias bracket echo "Input in brackets: <%l>"
2650 In [3]: bracket hello world
2651 In [3]: bracket hello world
2651 Input in brackets: <hello world>
2652 Input in brackets: <hello world>
2652
2653
2653 You can also define aliases with parameters using %s specifiers (one
2654 You can also define aliases with parameters using %s specifiers (one
2654 per parameter):
2655 per parameter):
2655
2656
2656 In [1]: alias parts echo first %s second %s
2657 In [1]: alias parts echo first %s second %s
2657 In [2]: %parts A B
2658 In [2]: %parts A B
2658 first A second B
2659 first A second B
2659 In [3]: %parts A
2660 In [3]: %parts A
2660 Incorrect number of arguments: 2 expected.
2661 Incorrect number of arguments: 2 expected.
2661 parts is an alias to: 'echo first %s second %s'
2662 parts is an alias to: 'echo first %s second %s'
2662
2663
2663 Note that %l and %s are mutually exclusive. You can only use one or
2664 Note that %l and %s are mutually exclusive. You can only use one or
2664 the other in your aliases.
2665 the other in your aliases.
2665
2666
2666 Aliases expand Python variables just like system calls using ! or !!
2667 Aliases expand Python variables just like system calls using ! or !!
2667 do: all expressions prefixed with '$' get expanded. For details of
2668 do: all expressions prefixed with '$' get expanded. For details of
2668 the semantic rules, see PEP-215:
2669 the semantic rules, see PEP-215:
2669 http://www.python.org/peps/pep-0215.html. This is the library used by
2670 http://www.python.org/peps/pep-0215.html. This is the library used by
2670 IPython for variable expansion. If you want to access a true shell
2671 IPython for variable expansion. If you want to access a true shell
2671 variable, an extra $ is necessary to prevent its expansion by IPython:
2672 variable, an extra $ is necessary to prevent its expansion by IPython:
2672
2673
2673 In [6]: alias show echo
2674 In [6]: alias show echo
2674 In [7]: PATH='A Python string'
2675 In [7]: PATH='A Python string'
2675 In [8]: show $PATH
2676 In [8]: show $PATH
2676 A Python string
2677 A Python string
2677 In [9]: show $$PATH
2678 In [9]: show $$PATH
2678 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2679 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2679
2680
2680 You can use the alias facility to acess all of $PATH. See the %rehash
2681 You can use the alias facility to acess all of $PATH. See the %rehash
2681 and %rehashx functions, which automatically create aliases for the
2682 and %rehashx functions, which automatically create aliases for the
2682 contents of your $PATH.
2683 contents of your $PATH.
2683
2684
2684 If called with no parameters, %alias prints the current alias table."""
2685 If called with no parameters, %alias prints the current alias table."""
2685
2686
2686 par = parameter_s.strip()
2687 par = parameter_s.strip()
2687 if not par:
2688 if not par:
2688 stored = self.db.get('stored_aliases', {} )
2689 stored = self.db.get('stored_aliases', {} )
2689 aliases = sorted(self.shell.alias_manager.aliases)
2690 aliases = sorted(self.shell.alias_manager.aliases)
2690 # for k, v in stored:
2691 # for k, v in stored:
2691 # atab.append(k, v[0])
2692 # atab.append(k, v[0])
2692
2693
2693 print "Total number of aliases:", len(aliases)
2694 print "Total number of aliases:", len(aliases)
2694 sys.stdout.flush()
2695 sys.stdout.flush()
2695 return aliases
2696 return aliases
2696
2697
2697 # Now try to define a new one
2698 # Now try to define a new one
2698 try:
2699 try:
2699 alias,cmd = par.split(None, 1)
2700 alias,cmd = par.split(None, 1)
2700 except:
2701 except:
2701 print oinspect.getdoc(self.magic_alias)
2702 print oinspect.getdoc(self.magic_alias)
2702 else:
2703 else:
2703 self.shell.alias_manager.soft_define_alias(alias, cmd)
2704 self.shell.alias_manager.soft_define_alias(alias, cmd)
2704 # end magic_alias
2705 # end magic_alias
2705
2706
2706 def magic_unalias(self, parameter_s = ''):
2707 def magic_unalias(self, parameter_s = ''):
2707 """Remove an alias"""
2708 """Remove an alias"""
2708
2709
2709 aname = parameter_s.strip()
2710 aname = parameter_s.strip()
2710 self.shell.alias_manager.undefine_alias(aname)
2711 self.shell.alias_manager.undefine_alias(aname)
2711 stored = self.db.get('stored_aliases', {} )
2712 stored = self.db.get('stored_aliases', {} )
2712 if aname in stored:
2713 if aname in stored:
2713 print "Removing %stored alias",aname
2714 print "Removing %stored alias",aname
2714 del stored[aname]
2715 del stored[aname]
2715 self.db['stored_aliases'] = stored
2716 self.db['stored_aliases'] = stored
2716
2717
2717 def magic_rehashx(self, parameter_s = ''):
2718 def magic_rehashx(self, parameter_s = ''):
2718 """Update the alias table with all executable files in $PATH.
2719 """Update the alias table with all executable files in $PATH.
2719
2720
2720 This version explicitly checks that every entry in $PATH is a file
2721 This version explicitly checks that every entry in $PATH is a file
2721 with execute access (os.X_OK), so it is much slower than %rehash.
2722 with execute access (os.X_OK), so it is much slower than %rehash.
2722
2723
2723 Under Windows, it checks executability as a match against a
2724 Under Windows, it checks executability as a match against a
2724 '|'-separated string of extensions, stored in the IPython config
2725 '|'-separated string of extensions, stored in the IPython config
2725 variable win_exec_ext. This defaults to 'exe|com|bat'.
2726 variable win_exec_ext. This defaults to 'exe|com|bat'.
2726
2727
2727 This function also resets the root module cache of module completer,
2728 This function also resets the root module cache of module completer,
2728 used on slow filesystems.
2729 used on slow filesystems.
2729 """
2730 """
2730 from IPython.core.alias import InvalidAliasError
2731 from IPython.core.alias import InvalidAliasError
2731
2732
2732 # for the benefit of module completer in ipy_completers.py
2733 # for the benefit of module completer in ipy_completers.py
2733 del self.shell.db['rootmodules']
2734 del self.shell.db['rootmodules']
2734
2735
2735 path = [os.path.abspath(os.path.expanduser(p)) for p in
2736 path = [os.path.abspath(os.path.expanduser(p)) for p in
2736 os.environ.get('PATH','').split(os.pathsep)]
2737 os.environ.get('PATH','').split(os.pathsep)]
2737 path = filter(os.path.isdir,path)
2738 path = filter(os.path.isdir,path)
2738
2739
2739 syscmdlist = []
2740 syscmdlist = []
2740 # Now define isexec in a cross platform manner.
2741 # Now define isexec in a cross platform manner.
2741 if os.name == 'posix':
2742 if os.name == 'posix':
2742 isexec = lambda fname:os.path.isfile(fname) and \
2743 isexec = lambda fname:os.path.isfile(fname) and \
2743 os.access(fname,os.X_OK)
2744 os.access(fname,os.X_OK)
2744 else:
2745 else:
2745 try:
2746 try:
2746 winext = os.environ['pathext'].replace(';','|').replace('.','')
2747 winext = os.environ['pathext'].replace(';','|').replace('.','')
2747 except KeyError:
2748 except KeyError:
2748 winext = 'exe|com|bat|py'
2749 winext = 'exe|com|bat|py'
2749 if 'py' not in winext:
2750 if 'py' not in winext:
2750 winext += '|py'
2751 winext += '|py'
2751 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2752 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2752 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2753 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2753 savedir = os.getcwdu()
2754 savedir = os.getcwdu()
2754
2755
2755 # Now walk the paths looking for executables to alias.
2756 # Now walk the paths looking for executables to alias.
2756 try:
2757 try:
2757 # write the whole loop for posix/Windows so we don't have an if in
2758 # write the whole loop for posix/Windows so we don't have an if in
2758 # the innermost part
2759 # the innermost part
2759 if os.name == 'posix':
2760 if os.name == 'posix':
2760 for pdir in path:
2761 for pdir in path:
2761 os.chdir(pdir)
2762 os.chdir(pdir)
2762 for ff in os.listdir(pdir):
2763 for ff in os.listdir(pdir):
2763 if isexec(ff):
2764 if isexec(ff):
2764 try:
2765 try:
2765 # Removes dots from the name since ipython
2766 # Removes dots from the name since ipython
2766 # will assume names with dots to be python.
2767 # will assume names with dots to be python.
2767 self.shell.alias_manager.define_alias(
2768 self.shell.alias_manager.define_alias(
2768 ff.replace('.',''), ff)
2769 ff.replace('.',''), ff)
2769 except InvalidAliasError:
2770 except InvalidAliasError:
2770 pass
2771 pass
2771 else:
2772 else:
2772 syscmdlist.append(ff)
2773 syscmdlist.append(ff)
2773 else:
2774 else:
2774 no_alias = self.shell.alias_manager.no_alias
2775 no_alias = self.shell.alias_manager.no_alias
2775 for pdir in path:
2776 for pdir in path:
2776 os.chdir(pdir)
2777 os.chdir(pdir)
2777 for ff in os.listdir(pdir):
2778 for ff in os.listdir(pdir):
2778 base, ext = os.path.splitext(ff)
2779 base, ext = os.path.splitext(ff)
2779 if isexec(ff) and base.lower() not in no_alias:
2780 if isexec(ff) and base.lower() not in no_alias:
2780 if ext.lower() == '.exe':
2781 if ext.lower() == '.exe':
2781 ff = base
2782 ff = base
2782 try:
2783 try:
2783 # Removes dots from the name since ipython
2784 # Removes dots from the name since ipython
2784 # will assume names with dots to be python.
2785 # will assume names with dots to be python.
2785 self.shell.alias_manager.define_alias(
2786 self.shell.alias_manager.define_alias(
2786 base.lower().replace('.',''), ff)
2787 base.lower().replace('.',''), ff)
2787 except InvalidAliasError:
2788 except InvalidAliasError:
2788 pass
2789 pass
2789 syscmdlist.append(ff)
2790 syscmdlist.append(ff)
2790 self.shell.db['syscmdlist'] = syscmdlist
2791 self.shell.db['syscmdlist'] = syscmdlist
2791 finally:
2792 finally:
2792 os.chdir(savedir)
2793 os.chdir(savedir)
2793
2794
2794 @skip_doctest
2795 @skip_doctest
2795 def magic_pwd(self, parameter_s = ''):
2796 def magic_pwd(self, parameter_s = ''):
2796 """Return the current working directory path.
2797 """Return the current working directory path.
2797
2798
2798 Examples
2799 Examples
2799 --------
2800 --------
2800 ::
2801 ::
2801
2802
2802 In [9]: pwd
2803 In [9]: pwd
2803 Out[9]: '/home/tsuser/sprint/ipython'
2804 Out[9]: '/home/tsuser/sprint/ipython'
2804 """
2805 """
2805 return os.getcwdu()
2806 return os.getcwdu()
2806
2807
2807 @skip_doctest
2808 @skip_doctest
2808 def magic_cd(self, parameter_s=''):
2809 def magic_cd(self, parameter_s=''):
2809 """Change the current working directory.
2810 """Change the current working directory.
2810
2811
2811 This command automatically maintains an internal list of directories
2812 This command automatically maintains an internal list of directories
2812 you visit during your IPython session, in the variable _dh. The
2813 you visit during your IPython session, in the variable _dh. The
2813 command %dhist shows this history nicely formatted. You can also
2814 command %dhist shows this history nicely formatted. You can also
2814 do 'cd -<tab>' to see directory history conveniently.
2815 do 'cd -<tab>' to see directory history conveniently.
2815
2816
2816 Usage:
2817 Usage:
2817
2818
2818 cd 'dir': changes to directory 'dir'.
2819 cd 'dir': changes to directory 'dir'.
2819
2820
2820 cd -: changes to the last visited directory.
2821 cd -: changes to the last visited directory.
2821
2822
2822 cd -<n>: changes to the n-th directory in the directory history.
2823 cd -<n>: changes to the n-th directory in the directory history.
2823
2824
2824 cd --foo: change to directory that matches 'foo' in history
2825 cd --foo: change to directory that matches 'foo' in history
2825
2826
2826 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2827 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2827 (note: cd <bookmark_name> is enough if there is no
2828 (note: cd <bookmark_name> is enough if there is no
2828 directory <bookmark_name>, but a bookmark with the name exists.)
2829 directory <bookmark_name>, but a bookmark with the name exists.)
2829 'cd -b <tab>' allows you to tab-complete bookmark names.
2830 'cd -b <tab>' allows you to tab-complete bookmark names.
2830
2831
2831 Options:
2832 Options:
2832
2833
2833 -q: quiet. Do not print the working directory after the cd command is
2834 -q: quiet. Do not print the working directory after the cd command is
2834 executed. By default IPython's cd command does print this directory,
2835 executed. By default IPython's cd command does print this directory,
2835 since the default prompts do not display path information.
2836 since the default prompts do not display path information.
2836
2837
2837 Note that !cd doesn't work for this purpose because the shell where
2838 Note that !cd doesn't work for this purpose because the shell where
2838 !command runs is immediately discarded after executing 'command'.
2839 !command runs is immediately discarded after executing 'command'.
2839
2840
2840 Examples
2841 Examples
2841 --------
2842 --------
2842 ::
2843 ::
2843
2844
2844 In [10]: cd parent/child
2845 In [10]: cd parent/child
2845 /home/tsuser/parent/child
2846 /home/tsuser/parent/child
2846 """
2847 """
2847
2848
2848 parameter_s = parameter_s.strip()
2849 parameter_s = parameter_s.strip()
2849 #bkms = self.shell.persist.get("bookmarks",{})
2850 #bkms = self.shell.persist.get("bookmarks",{})
2850
2851
2851 oldcwd = os.getcwdu()
2852 oldcwd = os.getcwdu()
2852 numcd = re.match(r'(-)(\d+)$',parameter_s)
2853 numcd = re.match(r'(-)(\d+)$',parameter_s)
2853 # jump in directory history by number
2854 # jump in directory history by number
2854 if numcd:
2855 if numcd:
2855 nn = int(numcd.group(2))
2856 nn = int(numcd.group(2))
2856 try:
2857 try:
2857 ps = self.shell.user_ns['_dh'][nn]
2858 ps = self.shell.user_ns['_dh'][nn]
2858 except IndexError:
2859 except IndexError:
2859 print 'The requested directory does not exist in history.'
2860 print 'The requested directory does not exist in history.'
2860 return
2861 return
2861 else:
2862 else:
2862 opts = {}
2863 opts = {}
2863 elif parameter_s.startswith('--'):
2864 elif parameter_s.startswith('--'):
2864 ps = None
2865 ps = None
2865 fallback = None
2866 fallback = None
2866 pat = parameter_s[2:]
2867 pat = parameter_s[2:]
2867 dh = self.shell.user_ns['_dh']
2868 dh = self.shell.user_ns['_dh']
2868 # first search only by basename (last component)
2869 # first search only by basename (last component)
2869 for ent in reversed(dh):
2870 for ent in reversed(dh):
2870 if pat in os.path.basename(ent) and os.path.isdir(ent):
2871 if pat in os.path.basename(ent) and os.path.isdir(ent):
2871 ps = ent
2872 ps = ent
2872 break
2873 break
2873
2874
2874 if fallback is None and pat in ent and os.path.isdir(ent):
2875 if fallback is None and pat in ent and os.path.isdir(ent):
2875 fallback = ent
2876 fallback = ent
2876
2877
2877 # if we have no last part match, pick the first full path match
2878 # if we have no last part match, pick the first full path match
2878 if ps is None:
2879 if ps is None:
2879 ps = fallback
2880 ps = fallback
2880
2881
2881 if ps is None:
2882 if ps is None:
2882 print "No matching entry in directory history"
2883 print "No matching entry in directory history"
2883 return
2884 return
2884 else:
2885 else:
2885 opts = {}
2886 opts = {}
2886
2887
2887
2888
2888 else:
2889 else:
2889 #turn all non-space-escaping backslashes to slashes,
2890 #turn all non-space-escaping backslashes to slashes,
2890 # for c:\windows\directory\names\
2891 # for c:\windows\directory\names\
2891 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2892 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2892 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2893 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2893 # jump to previous
2894 # jump to previous
2894 if ps == '-':
2895 if ps == '-':
2895 try:
2896 try:
2896 ps = self.shell.user_ns['_dh'][-2]
2897 ps = self.shell.user_ns['_dh'][-2]
2897 except IndexError:
2898 except IndexError:
2898 raise UsageError('%cd -: No previous directory to change to.')
2899 raise UsageError('%cd -: No previous directory to change to.')
2899 # jump to bookmark if needed
2900 # jump to bookmark if needed
2900 else:
2901 else:
2901 if not os.path.isdir(ps) or opts.has_key('b'):
2902 if not os.path.isdir(ps) or opts.has_key('b'):
2902 bkms = self.db.get('bookmarks', {})
2903 bkms = self.db.get('bookmarks', {})
2903
2904
2904 if bkms.has_key(ps):
2905 if bkms.has_key(ps):
2905 target = bkms[ps]
2906 target = bkms[ps]
2906 print '(bookmark:%s) -> %s' % (ps,target)
2907 print '(bookmark:%s) -> %s' % (ps,target)
2907 ps = target
2908 ps = target
2908 else:
2909 else:
2909 if opts.has_key('b'):
2910 if opts.has_key('b'):
2910 raise UsageError("Bookmark '%s' not found. "
2911 raise UsageError("Bookmark '%s' not found. "
2911 "Use '%%bookmark -l' to see your bookmarks." % ps)
2912 "Use '%%bookmark -l' to see your bookmarks." % ps)
2912
2913
2913 # strip extra quotes on Windows, because os.chdir doesn't like them
2914 # strip extra quotes on Windows, because os.chdir doesn't like them
2914 ps = unquote_filename(ps)
2915 ps = unquote_filename(ps)
2915 # at this point ps should point to the target dir
2916 # at this point ps should point to the target dir
2916 if ps:
2917 if ps:
2917 try:
2918 try:
2918 os.chdir(os.path.expanduser(ps))
2919 os.chdir(os.path.expanduser(ps))
2919 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2920 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2920 set_term_title('IPython: ' + abbrev_cwd())
2921 set_term_title('IPython: ' + abbrev_cwd())
2921 except OSError:
2922 except OSError:
2922 print sys.exc_info()[1]
2923 print sys.exc_info()[1]
2923 else:
2924 else:
2924 cwd = os.getcwdu()
2925 cwd = os.getcwdu()
2925 dhist = self.shell.user_ns['_dh']
2926 dhist = self.shell.user_ns['_dh']
2926 if oldcwd != cwd:
2927 if oldcwd != cwd:
2927 dhist.append(cwd)
2928 dhist.append(cwd)
2928 self.db['dhist'] = compress_dhist(dhist)[-100:]
2929 self.db['dhist'] = compress_dhist(dhist)[-100:]
2929
2930
2930 else:
2931 else:
2931 os.chdir(self.shell.home_dir)
2932 os.chdir(self.shell.home_dir)
2932 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2933 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2933 set_term_title('IPython: ' + '~')
2934 set_term_title('IPython: ' + '~')
2934 cwd = os.getcwdu()
2935 cwd = os.getcwdu()
2935 dhist = self.shell.user_ns['_dh']
2936 dhist = self.shell.user_ns['_dh']
2936
2937
2937 if oldcwd != cwd:
2938 if oldcwd != cwd:
2938 dhist.append(cwd)
2939 dhist.append(cwd)
2939 self.db['dhist'] = compress_dhist(dhist)[-100:]
2940 self.db['dhist'] = compress_dhist(dhist)[-100:]
2940 if not 'q' in opts and self.shell.user_ns['_dh']:
2941 if not 'q' in opts and self.shell.user_ns['_dh']:
2941 print self.shell.user_ns['_dh'][-1]
2942 print self.shell.user_ns['_dh'][-1]
2942
2943
2943
2944
2944 def magic_env(self, parameter_s=''):
2945 def magic_env(self, parameter_s=''):
2945 """List environment variables."""
2946 """List environment variables."""
2946
2947
2947 return os.environ.data
2948 return os.environ.data
2948
2949
2949 def magic_pushd(self, parameter_s=''):
2950 def magic_pushd(self, parameter_s=''):
2950 """Place the current dir on stack and change directory.
2951 """Place the current dir on stack and change directory.
2951
2952
2952 Usage:\\
2953 Usage:\\
2953 %pushd ['dirname']
2954 %pushd ['dirname']
2954 """
2955 """
2955
2956
2956 dir_s = self.shell.dir_stack
2957 dir_s = self.shell.dir_stack
2957 tgt = os.path.expanduser(unquote_filename(parameter_s))
2958 tgt = os.path.expanduser(unquote_filename(parameter_s))
2958 cwd = os.getcwdu().replace(self.home_dir,'~')
2959 cwd = os.getcwdu().replace(self.home_dir,'~')
2959 if tgt:
2960 if tgt:
2960 self.magic_cd(parameter_s)
2961 self.magic_cd(parameter_s)
2961 dir_s.insert(0,cwd)
2962 dir_s.insert(0,cwd)
2962 return self.magic_dirs()
2963 return self.magic_dirs()
2963
2964
2964 def magic_popd(self, parameter_s=''):
2965 def magic_popd(self, parameter_s=''):
2965 """Change to directory popped off the top of the stack.
2966 """Change to directory popped off the top of the stack.
2966 """
2967 """
2967 if not self.shell.dir_stack:
2968 if not self.shell.dir_stack:
2968 raise UsageError("%popd on empty stack")
2969 raise UsageError("%popd on empty stack")
2969 top = self.shell.dir_stack.pop(0)
2970 top = self.shell.dir_stack.pop(0)
2970 self.magic_cd(top)
2971 self.magic_cd(top)
2971 print "popd ->",top
2972 print "popd ->",top
2972
2973
2973 def magic_dirs(self, parameter_s=''):
2974 def magic_dirs(self, parameter_s=''):
2974 """Return the current directory stack."""
2975 """Return the current directory stack."""
2975
2976
2976 return self.shell.dir_stack
2977 return self.shell.dir_stack
2977
2978
2978 def magic_dhist(self, parameter_s=''):
2979 def magic_dhist(self, parameter_s=''):
2979 """Print your history of visited directories.
2980 """Print your history of visited directories.
2980
2981
2981 %dhist -> print full history\\
2982 %dhist -> print full history\\
2982 %dhist n -> print last n entries only\\
2983 %dhist n -> print last n entries only\\
2983 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2984 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2984
2985
2985 This history is automatically maintained by the %cd command, and
2986 This history is automatically maintained by the %cd command, and
2986 always available as the global list variable _dh. You can use %cd -<n>
2987 always available as the global list variable _dh. You can use %cd -<n>
2987 to go to directory number <n>.
2988 to go to directory number <n>.
2988
2989
2989 Note that most of time, you should view directory history by entering
2990 Note that most of time, you should view directory history by entering
2990 cd -<TAB>.
2991 cd -<TAB>.
2991
2992
2992 """
2993 """
2993
2994
2994 dh = self.shell.user_ns['_dh']
2995 dh = self.shell.user_ns['_dh']
2995 if parameter_s:
2996 if parameter_s:
2996 try:
2997 try:
2997 args = map(int,parameter_s.split())
2998 args = map(int,parameter_s.split())
2998 except:
2999 except:
2999 self.arg_err(Magic.magic_dhist)
3000 self.arg_err(Magic.magic_dhist)
3000 return
3001 return
3001 if len(args) == 1:
3002 if len(args) == 1:
3002 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3003 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3003 elif len(args) == 2:
3004 elif len(args) == 2:
3004 ini,fin = args
3005 ini,fin = args
3005 else:
3006 else:
3006 self.arg_err(Magic.magic_dhist)
3007 self.arg_err(Magic.magic_dhist)
3007 return
3008 return
3008 else:
3009 else:
3009 ini,fin = 0,len(dh)
3010 ini,fin = 0,len(dh)
3010 nlprint(dh,
3011 nlprint(dh,
3011 header = 'Directory history (kept in _dh)',
3012 header = 'Directory history (kept in _dh)',
3012 start=ini,stop=fin)
3013 start=ini,stop=fin)
3013
3014
3014 @skip_doctest
3015 @skip_doctest
3015 def magic_sc(self, parameter_s=''):
3016 def magic_sc(self, parameter_s=''):
3016 """Shell capture - execute a shell command and capture its output.
3017 """Shell capture - execute a shell command and capture its output.
3017
3018
3018 DEPRECATED. Suboptimal, retained for backwards compatibility.
3019 DEPRECATED. Suboptimal, retained for backwards compatibility.
3019
3020
3020 You should use the form 'var = !command' instead. Example:
3021 You should use the form 'var = !command' instead. Example:
3021
3022
3022 "%sc -l myfiles = ls ~" should now be written as
3023 "%sc -l myfiles = ls ~" should now be written as
3023
3024
3024 "myfiles = !ls ~"
3025 "myfiles = !ls ~"
3025
3026
3026 myfiles.s, myfiles.l and myfiles.n still apply as documented
3027 myfiles.s, myfiles.l and myfiles.n still apply as documented
3027 below.
3028 below.
3028
3029
3029 --
3030 --
3030 %sc [options] varname=command
3031 %sc [options] varname=command
3031
3032
3032 IPython will run the given command using commands.getoutput(), and
3033 IPython will run the given command using commands.getoutput(), and
3033 will then update the user's interactive namespace with a variable
3034 will then update the user's interactive namespace with a variable
3034 called varname, containing the value of the call. Your command can
3035 called varname, containing the value of the call. Your command can
3035 contain shell wildcards, pipes, etc.
3036 contain shell wildcards, pipes, etc.
3036
3037
3037 The '=' sign in the syntax is mandatory, and the variable name you
3038 The '=' sign in the syntax is mandatory, and the variable name you
3038 supply must follow Python's standard conventions for valid names.
3039 supply must follow Python's standard conventions for valid names.
3039
3040
3040 (A special format without variable name exists for internal use)
3041 (A special format without variable name exists for internal use)
3041
3042
3042 Options:
3043 Options:
3043
3044
3044 -l: list output. Split the output on newlines into a list before
3045 -l: list output. Split the output on newlines into a list before
3045 assigning it to the given variable. By default the output is stored
3046 assigning it to the given variable. By default the output is stored
3046 as a single string.
3047 as a single string.
3047
3048
3048 -v: verbose. Print the contents of the variable.
3049 -v: verbose. Print the contents of the variable.
3049
3050
3050 In most cases you should not need to split as a list, because the
3051 In most cases you should not need to split as a list, because the
3051 returned value is a special type of string which can automatically
3052 returned value is a special type of string which can automatically
3052 provide its contents either as a list (split on newlines) or as a
3053 provide its contents either as a list (split on newlines) or as a
3053 space-separated string. These are convenient, respectively, either
3054 space-separated string. These are convenient, respectively, either
3054 for sequential processing or to be passed to a shell command.
3055 for sequential processing or to be passed to a shell command.
3055
3056
3056 For example:
3057 For example:
3057
3058
3058 # all-random
3059 # all-random
3059
3060
3060 # Capture into variable a
3061 # Capture into variable a
3061 In [1]: sc a=ls *py
3062 In [1]: sc a=ls *py
3062
3063
3063 # a is a string with embedded newlines
3064 # a is a string with embedded newlines
3064 In [2]: a
3065 In [2]: a
3065 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3066 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3066
3067
3067 # which can be seen as a list:
3068 # which can be seen as a list:
3068 In [3]: a.l
3069 In [3]: a.l
3069 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3070 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3070
3071
3071 # or as a whitespace-separated string:
3072 # or as a whitespace-separated string:
3072 In [4]: a.s
3073 In [4]: a.s
3073 Out[4]: 'setup.py win32_manual_post_install.py'
3074 Out[4]: 'setup.py win32_manual_post_install.py'
3074
3075
3075 # a.s is useful to pass as a single command line:
3076 # a.s is useful to pass as a single command line:
3076 In [5]: !wc -l $a.s
3077 In [5]: !wc -l $a.s
3077 146 setup.py
3078 146 setup.py
3078 130 win32_manual_post_install.py
3079 130 win32_manual_post_install.py
3079 276 total
3080 276 total
3080
3081
3081 # while the list form is useful to loop over:
3082 # while the list form is useful to loop over:
3082 In [6]: for f in a.l:
3083 In [6]: for f in a.l:
3083 ...: !wc -l $f
3084 ...: !wc -l $f
3084 ...:
3085 ...:
3085 146 setup.py
3086 146 setup.py
3086 130 win32_manual_post_install.py
3087 130 win32_manual_post_install.py
3087
3088
3088 Similarly, the lists returned by the -l option are also special, in
3089 Similarly, the lists returned by the -l option are also special, in
3089 the sense that you can equally invoke the .s attribute on them to
3090 the sense that you can equally invoke the .s attribute on them to
3090 automatically get a whitespace-separated string from their contents:
3091 automatically get a whitespace-separated string from their contents:
3091
3092
3092 In [7]: sc -l b=ls *py
3093 In [7]: sc -l b=ls *py
3093
3094
3094 In [8]: b
3095 In [8]: b
3095 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3096 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3096
3097
3097 In [9]: b.s
3098 In [9]: b.s
3098 Out[9]: 'setup.py win32_manual_post_install.py'
3099 Out[9]: 'setup.py win32_manual_post_install.py'
3099
3100
3100 In summary, both the lists and strings used for output capture have
3101 In summary, both the lists and strings used for output capture have
3101 the following special attributes:
3102 the following special attributes:
3102
3103
3103 .l (or .list) : value as list.
3104 .l (or .list) : value as list.
3104 .n (or .nlstr): value as newline-separated string.
3105 .n (or .nlstr): value as newline-separated string.
3105 .s (or .spstr): value as space-separated string.
3106 .s (or .spstr): value as space-separated string.
3106 """
3107 """
3107
3108
3108 opts,args = self.parse_options(parameter_s,'lv')
3109 opts,args = self.parse_options(parameter_s,'lv')
3109 # Try to get a variable name and command to run
3110 # Try to get a variable name and command to run
3110 try:
3111 try:
3111 # the variable name must be obtained from the parse_options
3112 # the variable name must be obtained from the parse_options
3112 # output, which uses shlex.split to strip options out.
3113 # output, which uses shlex.split to strip options out.
3113 var,_ = args.split('=',1)
3114 var,_ = args.split('=',1)
3114 var = var.strip()
3115 var = var.strip()
3115 # But the command has to be extracted from the original input
3116 # But the command has to be extracted from the original input
3116 # parameter_s, not on what parse_options returns, to avoid the
3117 # parameter_s, not on what parse_options returns, to avoid the
3117 # quote stripping which shlex.split performs on it.
3118 # quote stripping which shlex.split performs on it.
3118 _,cmd = parameter_s.split('=',1)
3119 _,cmd = parameter_s.split('=',1)
3119 except ValueError:
3120 except ValueError:
3120 var,cmd = '',''
3121 var,cmd = '',''
3121 # If all looks ok, proceed
3122 # If all looks ok, proceed
3122 split = 'l' in opts
3123 split = 'l' in opts
3123 out = self.shell.getoutput(cmd, split=split)
3124 out = self.shell.getoutput(cmd, split=split)
3124 if opts.has_key('v'):
3125 if opts.has_key('v'):
3125 print '%s ==\n%s' % (var,pformat(out))
3126 print '%s ==\n%s' % (var,pformat(out))
3126 if var:
3127 if var:
3127 self.shell.user_ns.update({var:out})
3128 self.shell.user_ns.update({var:out})
3128 else:
3129 else:
3129 return out
3130 return out
3130
3131
3131 def magic_sx(self, parameter_s=''):
3132 def magic_sx(self, parameter_s=''):
3132 """Shell execute - run a shell command and capture its output.
3133 """Shell execute - run a shell command and capture its output.
3133
3134
3134 %sx command
3135 %sx command
3135
3136
3136 IPython will run the given command using commands.getoutput(), and
3137 IPython will run the given command using commands.getoutput(), and
3137 return the result formatted as a list (split on '\\n'). Since the
3138 return the result formatted as a list (split on '\\n'). Since the
3138 output is _returned_, it will be stored in ipython's regular output
3139 output is _returned_, it will be stored in ipython's regular output
3139 cache Out[N] and in the '_N' automatic variables.
3140 cache Out[N] and in the '_N' automatic variables.
3140
3141
3141 Notes:
3142 Notes:
3142
3143
3143 1) If an input line begins with '!!', then %sx is automatically
3144 1) If an input line begins with '!!', then %sx is automatically
3144 invoked. That is, while:
3145 invoked. That is, while:
3145 !ls
3146 !ls
3146 causes ipython to simply issue system('ls'), typing
3147 causes ipython to simply issue system('ls'), typing
3147 !!ls
3148 !!ls
3148 is a shorthand equivalent to:
3149 is a shorthand equivalent to:
3149 %sx ls
3150 %sx ls
3150
3151
3151 2) %sx differs from %sc in that %sx automatically splits into a list,
3152 2) %sx differs from %sc in that %sx automatically splits into a list,
3152 like '%sc -l'. The reason for this is to make it as easy as possible
3153 like '%sc -l'. The reason for this is to make it as easy as possible
3153 to process line-oriented shell output via further python commands.
3154 to process line-oriented shell output via further python commands.
3154 %sc is meant to provide much finer control, but requires more
3155 %sc is meant to provide much finer control, but requires more
3155 typing.
3156 typing.
3156
3157
3157 3) Just like %sc -l, this is a list with special attributes:
3158 3) Just like %sc -l, this is a list with special attributes:
3158
3159
3159 .l (or .list) : value as list.
3160 .l (or .list) : value as list.
3160 .n (or .nlstr): value as newline-separated string.
3161 .n (or .nlstr): value as newline-separated string.
3161 .s (or .spstr): value as whitespace-separated string.
3162 .s (or .spstr): value as whitespace-separated string.
3162
3163
3163 This is very useful when trying to use such lists as arguments to
3164 This is very useful when trying to use such lists as arguments to
3164 system commands."""
3165 system commands."""
3165
3166
3166 if parameter_s:
3167 if parameter_s:
3167 return self.shell.getoutput(parameter_s)
3168 return self.shell.getoutput(parameter_s)
3168
3169
3169
3170
3170 def magic_bookmark(self, parameter_s=''):
3171 def magic_bookmark(self, parameter_s=''):
3171 """Manage IPython's bookmark system.
3172 """Manage IPython's bookmark system.
3172
3173
3173 %bookmark <name> - set bookmark to current dir
3174 %bookmark <name> - set bookmark to current dir
3174 %bookmark <name> <dir> - set bookmark to <dir>
3175 %bookmark <name> <dir> - set bookmark to <dir>
3175 %bookmark -l - list all bookmarks
3176 %bookmark -l - list all bookmarks
3176 %bookmark -d <name> - remove bookmark
3177 %bookmark -d <name> - remove bookmark
3177 %bookmark -r - remove all bookmarks
3178 %bookmark -r - remove all bookmarks
3178
3179
3179 You can later on access a bookmarked folder with:
3180 You can later on access a bookmarked folder with:
3180 %cd -b <name>
3181 %cd -b <name>
3181 or simply '%cd <name>' if there is no directory called <name> AND
3182 or simply '%cd <name>' if there is no directory called <name> AND
3182 there is such a bookmark defined.
3183 there is such a bookmark defined.
3183
3184
3184 Your bookmarks persist through IPython sessions, but they are
3185 Your bookmarks persist through IPython sessions, but they are
3185 associated with each profile."""
3186 associated with each profile."""
3186
3187
3187 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3188 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3188 if len(args) > 2:
3189 if len(args) > 2:
3189 raise UsageError("%bookmark: too many arguments")
3190 raise UsageError("%bookmark: too many arguments")
3190
3191
3191 bkms = self.db.get('bookmarks',{})
3192 bkms = self.db.get('bookmarks',{})
3192
3193
3193 if opts.has_key('d'):
3194 if opts.has_key('d'):
3194 try:
3195 try:
3195 todel = args[0]
3196 todel = args[0]
3196 except IndexError:
3197 except IndexError:
3197 raise UsageError(
3198 raise UsageError(
3198 "%bookmark -d: must provide a bookmark to delete")
3199 "%bookmark -d: must provide a bookmark to delete")
3199 else:
3200 else:
3200 try:
3201 try:
3201 del bkms[todel]
3202 del bkms[todel]
3202 except KeyError:
3203 except KeyError:
3203 raise UsageError(
3204 raise UsageError(
3204 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3205 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3205
3206
3206 elif opts.has_key('r'):
3207 elif opts.has_key('r'):
3207 bkms = {}
3208 bkms = {}
3208 elif opts.has_key('l'):
3209 elif opts.has_key('l'):
3209 bks = bkms.keys()
3210 bks = bkms.keys()
3210 bks.sort()
3211 bks.sort()
3211 if bks:
3212 if bks:
3212 size = max(map(len,bks))
3213 size = max(map(len,bks))
3213 else:
3214 else:
3214 size = 0
3215 size = 0
3215 fmt = '%-'+str(size)+'s -> %s'
3216 fmt = '%-'+str(size)+'s -> %s'
3216 print 'Current bookmarks:'
3217 print 'Current bookmarks:'
3217 for bk in bks:
3218 for bk in bks:
3218 print fmt % (bk,bkms[bk])
3219 print fmt % (bk,bkms[bk])
3219 else:
3220 else:
3220 if not args:
3221 if not args:
3221 raise UsageError("%bookmark: You must specify the bookmark name")
3222 raise UsageError("%bookmark: You must specify the bookmark name")
3222 elif len(args)==1:
3223 elif len(args)==1:
3223 bkms[args[0]] = os.getcwdu()
3224 bkms[args[0]] = os.getcwdu()
3224 elif len(args)==2:
3225 elif len(args)==2:
3225 bkms[args[0]] = args[1]
3226 bkms[args[0]] = args[1]
3226 self.db['bookmarks'] = bkms
3227 self.db['bookmarks'] = bkms
3227
3228
3228 def magic_pycat(self, parameter_s=''):
3229 def magic_pycat(self, parameter_s=''):
3229 """Show a syntax-highlighted file through a pager.
3230 """Show a syntax-highlighted file through a pager.
3230
3231
3231 This magic is similar to the cat utility, but it will assume the file
3232 This magic is similar to the cat utility, but it will assume the file
3232 to be Python source and will show it with syntax highlighting. """
3233 to be Python source and will show it with syntax highlighting. """
3233
3234
3234 try:
3235 try:
3235 filename = get_py_filename(parameter_s)
3236 filename = get_py_filename(parameter_s)
3236 cont = file_read(filename)
3237 cont = file_read(filename)
3237 except IOError:
3238 except IOError:
3238 try:
3239 try:
3239 cont = eval(parameter_s,self.user_ns)
3240 cont = eval(parameter_s,self.user_ns)
3240 except NameError:
3241 except NameError:
3241 cont = None
3242 cont = None
3242 if cont is None:
3243 if cont is None:
3243 print "Error: no such file or variable"
3244 print "Error: no such file or variable"
3244 return
3245 return
3245
3246
3246 page.page(self.shell.pycolorize(cont))
3247 page.page(self.shell.pycolorize(cont))
3247
3248
3248 def magic_quickref(self,arg):
3249 def magic_quickref(self,arg):
3249 """ Show a quick reference sheet """
3250 """ Show a quick reference sheet """
3250 import IPython.core.usage
3251 import IPython.core.usage
3251 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3252 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3252
3253
3253 page.page(qr)
3254 page.page(qr)
3254
3255
3255 def magic_doctest_mode(self,parameter_s=''):
3256 def magic_doctest_mode(self,parameter_s=''):
3256 """Toggle doctest mode on and off.
3257 """Toggle doctest mode on and off.
3257
3258
3258 This mode is intended to make IPython behave as much as possible like a
3259 This mode is intended to make IPython behave as much as possible like a
3259 plain Python shell, from the perspective of how its prompts, exceptions
3260 plain Python shell, from the perspective of how its prompts, exceptions
3260 and output look. This makes it easy to copy and paste parts of a
3261 and output look. This makes it easy to copy and paste parts of a
3261 session into doctests. It does so by:
3262 session into doctests. It does so by:
3262
3263
3263 - Changing the prompts to the classic ``>>>`` ones.
3264 - Changing the prompts to the classic ``>>>`` ones.
3264 - Changing the exception reporting mode to 'Plain'.
3265 - Changing the exception reporting mode to 'Plain'.
3265 - Disabling pretty-printing of output.
3266 - Disabling pretty-printing of output.
3266
3267
3267 Note that IPython also supports the pasting of code snippets that have
3268 Note that IPython also supports the pasting of code snippets that have
3268 leading '>>>' and '...' prompts in them. This means that you can paste
3269 leading '>>>' and '...' prompts in them. This means that you can paste
3269 doctests from files or docstrings (even if they have leading
3270 doctests from files or docstrings (even if they have leading
3270 whitespace), and the code will execute correctly. You can then use
3271 whitespace), and the code will execute correctly. You can then use
3271 '%history -t' to see the translated history; this will give you the
3272 '%history -t' to see the translated history; this will give you the
3272 input after removal of all the leading prompts and whitespace, which
3273 input after removal of all the leading prompts and whitespace, which
3273 can be pasted back into an editor.
3274 can be pasted back into an editor.
3274
3275
3275 With these features, you can switch into this mode easily whenever you
3276 With these features, you can switch into this mode easily whenever you
3276 need to do testing and changes to doctests, without having to leave
3277 need to do testing and changes to doctests, without having to leave
3277 your existing IPython session.
3278 your existing IPython session.
3278 """
3279 """
3279
3280
3280 from IPython.utils.ipstruct import Struct
3281 from IPython.utils.ipstruct import Struct
3281
3282
3282 # Shorthands
3283 # Shorthands
3283 shell = self.shell
3284 shell = self.shell
3284 pm = shell.prompt_manager
3285 pm = shell.prompt_manager
3285 meta = shell.meta
3286 meta = shell.meta
3286 disp_formatter = self.shell.display_formatter
3287 disp_formatter = self.shell.display_formatter
3287 ptformatter = disp_formatter.formatters['text/plain']
3288 ptformatter = disp_formatter.formatters['text/plain']
3288 # dstore is a data store kept in the instance metadata bag to track any
3289 # dstore is a data store kept in the instance metadata bag to track any
3289 # changes we make, so we can undo them later.
3290 # changes we make, so we can undo them later.
3290 dstore = meta.setdefault('doctest_mode',Struct())
3291 dstore = meta.setdefault('doctest_mode',Struct())
3291 save_dstore = dstore.setdefault
3292 save_dstore = dstore.setdefault
3292
3293
3293 # save a few values we'll need to recover later
3294 # save a few values we'll need to recover later
3294 mode = save_dstore('mode',False)
3295 mode = save_dstore('mode',False)
3295 save_dstore('rc_pprint',ptformatter.pprint)
3296 save_dstore('rc_pprint',ptformatter.pprint)
3296 save_dstore('xmode',shell.InteractiveTB.mode)
3297 save_dstore('xmode',shell.InteractiveTB.mode)
3297 save_dstore('rc_separate_out',shell.separate_out)
3298 save_dstore('rc_separate_out',shell.separate_out)
3298 save_dstore('rc_separate_out2',shell.separate_out2)
3299 save_dstore('rc_separate_out2',shell.separate_out2)
3299 save_dstore('rc_prompts_pad_left',pm.justify)
3300 save_dstore('rc_prompts_pad_left',pm.justify)
3300 save_dstore('rc_separate_in',shell.separate_in)
3301 save_dstore('rc_separate_in',shell.separate_in)
3301 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3302 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3302 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3303 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3303
3304
3304 if mode == False:
3305 if mode == False:
3305 # turn on
3306 # turn on
3306 pm.in_template = '>>> '
3307 pm.in_template = '>>> '
3307 pm.in2_template = '... '
3308 pm.in2_template = '... '
3308 pm.out_template = ''
3309 pm.out_template = ''
3309
3310
3310 # Prompt separators like plain python
3311 # Prompt separators like plain python
3311 shell.separate_in = ''
3312 shell.separate_in = ''
3312 shell.separate_out = ''
3313 shell.separate_out = ''
3313 shell.separate_out2 = ''
3314 shell.separate_out2 = ''
3314
3315
3315 pm.justify = False
3316 pm.justify = False
3316
3317
3317 ptformatter.pprint = False
3318 ptformatter.pprint = False
3318 disp_formatter.plain_text_only = True
3319 disp_formatter.plain_text_only = True
3319
3320
3320 shell.magic_xmode('Plain')
3321 shell.magic_xmode('Plain')
3321 else:
3322 else:
3322 # turn off
3323 # turn off
3323 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3324 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3324
3325
3325 shell.separate_in = dstore.rc_separate_in
3326 shell.separate_in = dstore.rc_separate_in
3326
3327
3327 shell.separate_out = dstore.rc_separate_out
3328 shell.separate_out = dstore.rc_separate_out
3328 shell.separate_out2 = dstore.rc_separate_out2
3329 shell.separate_out2 = dstore.rc_separate_out2
3329
3330
3330 pm.justify = dstore.rc_prompts_pad_left
3331 pm.justify = dstore.rc_prompts_pad_left
3331
3332
3332 ptformatter.pprint = dstore.rc_pprint
3333 ptformatter.pprint = dstore.rc_pprint
3333 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3334 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3334
3335
3335 shell.magic_xmode(dstore.xmode)
3336 shell.magic_xmode(dstore.xmode)
3336
3337
3337 # Store new mode and inform
3338 # Store new mode and inform
3338 dstore.mode = bool(1-int(mode))
3339 dstore.mode = bool(1-int(mode))
3339 mode_label = ['OFF','ON'][dstore.mode]
3340 mode_label = ['OFF','ON'][dstore.mode]
3340 print 'Doctest mode is:', mode_label
3341 print 'Doctest mode is:', mode_label
3341
3342
3342 def magic_gui(self, parameter_s=''):
3343 def magic_gui(self, parameter_s=''):
3343 """Enable or disable IPython GUI event loop integration.
3344 """Enable or disable IPython GUI event loop integration.
3344
3345
3345 %gui [GUINAME]
3346 %gui [GUINAME]
3346
3347
3347 This magic replaces IPython's threaded shells that were activated
3348 This magic replaces IPython's threaded shells that were activated
3348 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3349 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3349 can now be enabled at runtime and keyboard
3350 can now be enabled at runtime and keyboard
3350 interrupts should work without any problems. The following toolkits
3351 interrupts should work without any problems. The following toolkits
3351 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3352 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3352
3353
3353 %gui wx # enable wxPython event loop integration
3354 %gui wx # enable wxPython event loop integration
3354 %gui qt4|qt # enable PyQt4 event loop integration
3355 %gui qt4|qt # enable PyQt4 event loop integration
3355 %gui gtk # enable PyGTK event loop integration
3356 %gui gtk # enable PyGTK event loop integration
3356 %gui tk # enable Tk event loop integration
3357 %gui tk # enable Tk event loop integration
3357 %gui OSX # enable Cocoa event loop integration
3358 %gui OSX # enable Cocoa event loop integration
3358 # (requires %matplotlib 1.1)
3359 # (requires %matplotlib 1.1)
3359 %gui # disable all event loop integration
3360 %gui # disable all event loop integration
3360
3361
3361 WARNING: after any of these has been called you can simply create
3362 WARNING: after any of these has been called you can simply create
3362 an application object, but DO NOT start the event loop yourself, as
3363 an application object, but DO NOT start the event loop yourself, as
3363 we have already handled that.
3364 we have already handled that.
3364 """
3365 """
3365 opts, arg = self.parse_options(parameter_s, '')
3366 opts, arg = self.parse_options(parameter_s, '')
3366 if arg=='': arg = None
3367 if arg=='': arg = None
3367 try:
3368 try:
3368 return self.enable_gui(arg)
3369 return self.enable_gui(arg)
3369 except Exception as e:
3370 except Exception as e:
3370 # print simple error message, rather than traceback if we can't
3371 # print simple error message, rather than traceback if we can't
3371 # hook up the GUI
3372 # hook up the GUI
3372 error(str(e))
3373 error(str(e))
3373
3374
3374 def magic_load_ext(self, module_str):
3375 def magic_load_ext(self, module_str):
3375 """Load an IPython extension by its module name."""
3376 """Load an IPython extension by its module name."""
3376 return self.extension_manager.load_extension(module_str)
3377 return self.extension_manager.load_extension(module_str)
3377
3378
3378 def magic_unload_ext(self, module_str):
3379 def magic_unload_ext(self, module_str):
3379 """Unload an IPython extension by its module name."""
3380 """Unload an IPython extension by its module name."""
3380 self.extension_manager.unload_extension(module_str)
3381 self.extension_manager.unload_extension(module_str)
3381
3382
3382 def magic_reload_ext(self, module_str):
3383 def magic_reload_ext(self, module_str):
3383 """Reload an IPython extension by its module name."""
3384 """Reload an IPython extension by its module name."""
3384 self.extension_manager.reload_extension(module_str)
3385 self.extension_manager.reload_extension(module_str)
3385
3386
3386 def magic_install_profiles(self, s):
3387 def magic_install_profiles(self, s):
3387 """%install_profiles has been deprecated."""
3388 """%install_profiles has been deprecated."""
3388 print '\n'.join([
3389 print '\n'.join([
3389 "%install_profiles has been deprecated.",
3390 "%install_profiles has been deprecated.",
3390 "Use `ipython profile list` to view available profiles.",
3391 "Use `ipython profile list` to view available profiles.",
3391 "Requesting a profile with `ipython profile create <name>`",
3392 "Requesting a profile with `ipython profile create <name>`",
3392 "or `ipython --profile=<name>` will start with the bundled",
3393 "or `ipython --profile=<name>` will start with the bundled",
3393 "profile of that name if it exists."
3394 "profile of that name if it exists."
3394 ])
3395 ])
3395
3396
3396 def magic_install_default_config(self, s):
3397 def magic_install_default_config(self, s):
3397 """%install_default_config has been deprecated."""
3398 """%install_default_config has been deprecated."""
3398 print '\n'.join([
3399 print '\n'.join([
3399 "%install_default_config has been deprecated.",
3400 "%install_default_config has been deprecated.",
3400 "Use `ipython profile create <name>` to initialize a profile",
3401 "Use `ipython profile create <name>` to initialize a profile",
3401 "with the default config files.",
3402 "with the default config files.",
3402 "Add `--reset` to overwrite already existing config files with defaults."
3403 "Add `--reset` to overwrite already existing config files with defaults."
3403 ])
3404 ])
3404
3405
3405 # Pylab support: simple wrappers that activate pylab, load gui input
3406 # Pylab support: simple wrappers that activate pylab, load gui input
3406 # handling and modify slightly %run
3407 # handling and modify slightly %run
3407
3408
3408 @skip_doctest
3409 @skip_doctest
3409 def _pylab_magic_run(self, parameter_s=''):
3410 def _pylab_magic_run(self, parameter_s=''):
3410 Magic.magic_run(self, parameter_s,
3411 Magic.magic_run(self, parameter_s,
3411 runner=mpl_runner(self.shell.safe_execfile))
3412 runner=mpl_runner(self.shell.safe_execfile))
3412
3413
3413 _pylab_magic_run.__doc__ = magic_run.__doc__
3414 _pylab_magic_run.__doc__ = magic_run.__doc__
3414
3415
3415 @skip_doctest
3416 @skip_doctest
3416 def magic_pylab(self, s):
3417 def magic_pylab(self, s):
3417 """Load numpy and matplotlib to work interactively.
3418 """Load numpy and matplotlib to work interactively.
3418
3419
3419 %pylab [GUINAME]
3420 %pylab [GUINAME]
3420
3421
3421 This function lets you activate pylab (matplotlib, numpy and
3422 This function lets you activate pylab (matplotlib, numpy and
3422 interactive support) at any point during an IPython session.
3423 interactive support) at any point during an IPython session.
3423
3424
3424 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3425 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3425 pylab and mlab, as well as all names from numpy and pylab.
3426 pylab and mlab, as well as all names from numpy and pylab.
3426
3427
3427 If you are using the inline matplotlib backend for embedded figures,
3428 If you are using the inline matplotlib backend for embedded figures,
3428 you can adjust its behavior via the %config magic::
3429 you can adjust its behavior via the %config magic::
3429
3430
3430 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3431 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3431 In [1]: %config InlineBackend.figure_format = 'svg'
3432 In [1]: %config InlineBackend.figure_format = 'svg'
3432
3433
3433 # change the behavior of closing all figures at the end of each
3434 # change the behavior of closing all figures at the end of each
3434 # execution (cell), or allowing reuse of active figures across
3435 # execution (cell), or allowing reuse of active figures across
3435 # cells:
3436 # cells:
3436 In [2]: %config InlineBackend.close_figures = False
3437 In [2]: %config InlineBackend.close_figures = False
3437
3438
3438 Parameters
3439 Parameters
3439 ----------
3440 ----------
3440 guiname : optional
3441 guiname : optional
3441 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3442 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3442 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3443 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3443 used, otherwise matplotlib's default (which you can override in your
3444 used, otherwise matplotlib's default (which you can override in your
3444 matplotlib config file) is used.
3445 matplotlib config file) is used.
3445
3446
3446 Examples
3447 Examples
3447 --------
3448 --------
3448 In this case, where the MPL default is TkAgg::
3449 In this case, where the MPL default is TkAgg::
3449
3450
3450 In [2]: %pylab
3451 In [2]: %pylab
3451
3452
3452 Welcome to pylab, a matplotlib-based Python environment.
3453 Welcome to pylab, a matplotlib-based Python environment.
3453 Backend in use: TkAgg
3454 Backend in use: TkAgg
3454 For more information, type 'help(pylab)'.
3455 For more information, type 'help(pylab)'.
3455
3456
3456 But you can explicitly request a different backend::
3457 But you can explicitly request a different backend::
3457
3458
3458 In [3]: %pylab qt
3459 In [3]: %pylab qt
3459
3460
3460 Welcome to pylab, a matplotlib-based Python environment.
3461 Welcome to pylab, a matplotlib-based Python environment.
3461 Backend in use: Qt4Agg
3462 Backend in use: Qt4Agg
3462 For more information, type 'help(pylab)'.
3463 For more information, type 'help(pylab)'.
3463 """
3464 """
3464
3465
3465 if Application.initialized():
3466 if Application.initialized():
3466 app = Application.instance()
3467 app = Application.instance()
3467 try:
3468 try:
3468 import_all_status = app.pylab_import_all
3469 import_all_status = app.pylab_import_all
3469 except AttributeError:
3470 except AttributeError:
3470 import_all_status = True
3471 import_all_status = True
3471 else:
3472 else:
3472 import_all_status = True
3473 import_all_status = True
3473
3474
3474 self.shell.enable_pylab(s, import_all=import_all_status)
3475 self.shell.enable_pylab(s, import_all=import_all_status)
3475
3476
3476 def magic_tb(self, s):
3477 def magic_tb(self, s):
3477 """Print the last traceback with the currently active exception mode.
3478 """Print the last traceback with the currently active exception mode.
3478
3479
3479 See %xmode for changing exception reporting modes."""
3480 See %xmode for changing exception reporting modes."""
3480 self.shell.showtraceback()
3481 self.shell.showtraceback()
3481
3482
3482 @skip_doctest
3483 @skip_doctest
3483 def magic_precision(self, s=''):
3484 def magic_precision(self, s=''):
3484 """Set floating point precision for pretty printing.
3485 """Set floating point precision for pretty printing.
3485
3486
3486 Can set either integer precision or a format string.
3487 Can set either integer precision or a format string.
3487
3488
3488 If numpy has been imported and precision is an int,
3489 If numpy has been imported and precision is an int,
3489 numpy display precision will also be set, via ``numpy.set_printoptions``.
3490 numpy display precision will also be set, via ``numpy.set_printoptions``.
3490
3491
3491 If no argument is given, defaults will be restored.
3492 If no argument is given, defaults will be restored.
3492
3493
3493 Examples
3494 Examples
3494 --------
3495 --------
3495 ::
3496 ::
3496
3497
3497 In [1]: from math import pi
3498 In [1]: from math import pi
3498
3499
3499 In [2]: %precision 3
3500 In [2]: %precision 3
3500 Out[2]: u'%.3f'
3501 Out[2]: u'%.3f'
3501
3502
3502 In [3]: pi
3503 In [3]: pi
3503 Out[3]: 3.142
3504 Out[3]: 3.142
3504
3505
3505 In [4]: %precision %i
3506 In [4]: %precision %i
3506 Out[4]: u'%i'
3507 Out[4]: u'%i'
3507
3508
3508 In [5]: pi
3509 In [5]: pi
3509 Out[5]: 3
3510 Out[5]: 3
3510
3511
3511 In [6]: %precision %e
3512 In [6]: %precision %e
3512 Out[6]: u'%e'
3513 Out[6]: u'%e'
3513
3514
3514 In [7]: pi**10
3515 In [7]: pi**10
3515 Out[7]: 9.364805e+04
3516 Out[7]: 9.364805e+04
3516
3517
3517 In [8]: %precision
3518 In [8]: %precision
3518 Out[8]: u'%r'
3519 Out[8]: u'%r'
3519
3520
3520 In [9]: pi**10
3521 In [9]: pi**10
3521 Out[9]: 93648.047476082982
3522 Out[9]: 93648.047476082982
3522
3523
3523 """
3524 """
3524
3525
3525 ptformatter = self.shell.display_formatter.formatters['text/plain']
3526 ptformatter = self.shell.display_formatter.formatters['text/plain']
3526 ptformatter.float_precision = s
3527 ptformatter.float_precision = s
3527 return ptformatter.float_format
3528 return ptformatter.float_format
3528
3529
3529
3530
3530 @magic_arguments.magic_arguments()
3531 @magic_arguments.magic_arguments()
3531 @magic_arguments.argument(
3532 @magic_arguments.argument(
3532 '-e', '--export', action='store_true', default=False,
3533 '-e', '--export', action='store_true', default=False,
3533 help='Export IPython history as a notebook. The filename argument '
3534 help='Export IPython history as a notebook. The filename argument '
3534 'is used to specify the notebook name and format. For example '
3535 'is used to specify the notebook name and format. For example '
3535 'a filename of notebook.ipynb will result in a notebook name '
3536 'a filename of notebook.ipynb will result in a notebook name '
3536 'of "notebook" and a format of "xml". Likewise using a ".json" '
3537 'of "notebook" and a format of "xml". Likewise using a ".json" '
3537 'or ".py" file extension will write the notebook in the json '
3538 'or ".py" file extension will write the notebook in the json '
3538 'or py formats.'
3539 'or py formats.'
3539 )
3540 )
3540 @magic_arguments.argument(
3541 @magic_arguments.argument(
3541 '-f', '--format',
3542 '-f', '--format',
3542 help='Convert an existing IPython notebook to a new format. This option '
3543 help='Convert an existing IPython notebook to a new format. This option '
3543 'specifies the new format and can have the values: xml, json, py. '
3544 'specifies the new format and can have the values: xml, json, py. '
3544 'The target filename is chosen automatically based on the new '
3545 'The target filename is chosen automatically based on the new '
3545 'format. The filename argument gives the name of the source file.'
3546 'format. The filename argument gives the name of the source file.'
3546 )
3547 )
3547 @magic_arguments.argument(
3548 @magic_arguments.argument(
3548 'filename', type=unicode,
3549 'filename', type=unicode,
3549 help='Notebook name or filename'
3550 help='Notebook name or filename'
3550 )
3551 )
3551 def magic_notebook(self, s):
3552 def magic_notebook(self, s):
3552 """Export and convert IPython notebooks.
3553 """Export and convert IPython notebooks.
3553
3554
3554 This function can export the current IPython history to a notebook file
3555 This function can export the current IPython history to a notebook file
3555 or can convert an existing notebook file into a different format. For
3556 or can convert an existing notebook file into a different format. For
3556 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3557 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3557 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3558 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3558 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3559 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3559 formats include (json/ipynb, py).
3560 formats include (json/ipynb, py).
3560 """
3561 """
3561 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3562 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3562
3563
3563 from IPython.nbformat import current
3564 from IPython.nbformat import current
3564 args.filename = unquote_filename(args.filename)
3565 args.filename = unquote_filename(args.filename)
3565 if args.export:
3566 if args.export:
3566 fname, name, format = current.parse_filename(args.filename)
3567 fname, name, format = current.parse_filename(args.filename)
3567 cells = []
3568 cells = []
3568 hist = list(self.history_manager.get_range())
3569 hist = list(self.history_manager.get_range())
3569 for session, prompt_number, input in hist[:-1]:
3570 for session, prompt_number, input in hist[:-1]:
3570 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3571 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3571 worksheet = current.new_worksheet(cells=cells)
3572 worksheet = current.new_worksheet(cells=cells)
3572 nb = current.new_notebook(name=name,worksheets=[worksheet])
3573 nb = current.new_notebook(name=name,worksheets=[worksheet])
3573 with open(fname, 'w') as f:
3574 with open(fname, 'w') as f:
3574 current.write(nb, f, format);
3575 current.write(nb, f, format);
3575 elif args.format is not None:
3576 elif args.format is not None:
3576 old_fname, old_name, old_format = current.parse_filename(args.filename)
3577 old_fname, old_name, old_format = current.parse_filename(args.filename)
3577 new_format = args.format
3578 new_format = args.format
3578 if new_format == u'xml':
3579 if new_format == u'xml':
3579 raise ValueError('Notebooks cannot be written as xml.')
3580 raise ValueError('Notebooks cannot be written as xml.')
3580 elif new_format == u'ipynb' or new_format == u'json':
3581 elif new_format == u'ipynb' or new_format == u'json':
3581 new_fname = old_name + u'.ipynb'
3582 new_fname = old_name + u'.ipynb'
3582 new_format = u'json'
3583 new_format = u'json'
3583 elif new_format == u'py':
3584 elif new_format == u'py':
3584 new_fname = old_name + u'.py'
3585 new_fname = old_name + u'.py'
3585 else:
3586 else:
3586 raise ValueError('Invalid notebook format: %s' % new_format)
3587 raise ValueError('Invalid notebook format: %s' % new_format)
3587 with open(old_fname, 'r') as f:
3588 with open(old_fname, 'r') as f:
3588 s = f.read()
3589 s = f.read()
3589 try:
3590 try:
3590 nb = current.reads(s, old_format)
3591 nb = current.reads(s, old_format)
3591 except:
3592 except:
3592 nb = current.reads(s, u'xml')
3593 nb = current.reads(s, u'xml')
3593 with open(new_fname, 'w') as f:
3594 with open(new_fname, 'w') as f:
3594 current.write(nb, f, new_format)
3595 current.write(nb, f, new_format)
3595
3596
3596 def magic_config(self, s):
3597 def magic_config(self, s):
3597 """configure IPython
3598 """configure IPython
3598
3599
3599 %config Class[.trait=value]
3600 %config Class[.trait=value]
3600
3601
3601 This magic exposes most of the IPython config system. Any
3602 This magic exposes most of the IPython config system. Any
3602 Configurable class should be able to be configured with the simple
3603 Configurable class should be able to be configured with the simple
3603 line::
3604 line::
3604
3605
3605 %config Class.trait=value
3606 %config Class.trait=value
3606
3607
3607 Where `value` will be resolved in the user's namespace, if it is an
3608 Where `value` will be resolved in the user's namespace, if it is an
3608 expression or variable name.
3609 expression or variable name.
3609
3610
3610 Examples
3611 Examples
3611 --------
3612 --------
3612
3613
3613 To see what classes are available for config, pass no arguments::
3614 To see what classes are available for config, pass no arguments::
3614
3615
3615 In [1]: %config
3616 In [1]: %config
3616 Available objects for config:
3617 Available objects for config:
3617 TerminalInteractiveShell
3618 TerminalInteractiveShell
3618 HistoryManager
3619 HistoryManager
3619 PrefilterManager
3620 PrefilterManager
3620 AliasManager
3621 AliasManager
3621 IPCompleter
3622 IPCompleter
3622 PromptManager
3623 PromptManager
3623 DisplayFormatter
3624 DisplayFormatter
3624
3625
3625 To view what is configurable on a given class, just pass the class name::
3626 To view what is configurable on a given class, just pass the class name::
3626
3627
3627 In [2]: %config IPCompleter
3628 In [2]: %config IPCompleter
3628 IPCompleter options
3629 IPCompleter options
3629 -----------------
3630 -----------------
3630 IPCompleter.omit__names=<Enum>
3631 IPCompleter.omit__names=<Enum>
3631 Current: 2
3632 Current: 2
3632 Choices: (0, 1, 2)
3633 Choices: (0, 1, 2)
3633 Instruct the completer to omit private method names
3634 Instruct the completer to omit private method names
3634 Specifically, when completing on ``object.<tab>``.
3635 Specifically, when completing on ``object.<tab>``.
3635 When 2 [default]: all names that start with '_' will be excluded.
3636 When 2 [default]: all names that start with '_' will be excluded.
3636 When 1: all 'magic' names (``__foo__``) will be excluded.
3637 When 1: all 'magic' names (``__foo__``) will be excluded.
3637 When 0: nothing will be excluded.
3638 When 0: nothing will be excluded.
3638 IPCompleter.merge_completions=<CBool>
3639 IPCompleter.merge_completions=<CBool>
3639 Current: True
3640 Current: True
3640 Whether to merge completion results into a single list
3641 Whether to merge completion results into a single list
3641 If False, only the completion results from the first non-empty completer
3642 If False, only the completion results from the first non-empty completer
3642 will be returned.
3643 will be returned.
3643 IPCompleter.greedy=<CBool>
3644 IPCompleter.greedy=<CBool>
3644 Current: False
3645 Current: False
3645 Activate greedy completion
3646 Activate greedy completion
3646 This will enable completion on elements of lists, results of function calls,
3647 This will enable completion on elements of lists, results of function calls,
3647 etc., but can be unsafe because the code is actually evaluated on TAB.
3648 etc., but can be unsafe because the code is actually evaluated on TAB.
3648
3649
3649 but the real use is in setting values::
3650 but the real use is in setting values::
3650
3651
3651 In [3]: %config IPCompleter.greedy = True
3652 In [3]: %config IPCompleter.greedy = True
3652
3653
3653 and these values are read from the user_ns if they are variables::
3654 and these values are read from the user_ns if they are variables::
3654
3655
3655 In [4]: feeling_greedy=False
3656 In [4]: feeling_greedy=False
3656
3657
3657 In [5]: %config IPCompleter.greedy = feeling_greedy
3658 In [5]: %config IPCompleter.greedy = feeling_greedy
3658
3659
3659 """
3660 """
3660 from IPython.config.loader import Config
3661 from IPython.config.loader import Config
3661 # some IPython objects are Configurable, but do not yet have
3662 # some IPython objects are Configurable, but do not yet have
3662 # any configurable traits. Exclude them from the effects of
3663 # any configurable traits. Exclude them from the effects of
3663 # this magic, as their presence is just noise:
3664 # this magic, as their presence is just noise:
3664 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3665 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3665 classnames = [ c.__class__.__name__ for c in configurables ]
3666 classnames = [ c.__class__.__name__ for c in configurables ]
3666
3667
3667 line = s.strip()
3668 line = s.strip()
3668 if not line:
3669 if not line:
3669 # print available configurable names
3670 # print available configurable names
3670 print "Available objects for config:"
3671 print "Available objects for config:"
3671 for name in classnames:
3672 for name in classnames:
3672 print " ", name
3673 print " ", name
3673 return
3674 return
3674 elif line in classnames:
3675 elif line in classnames:
3675 # `%config TerminalInteractiveShell` will print trait info for
3676 # `%config TerminalInteractiveShell` will print trait info for
3676 # TerminalInteractiveShell
3677 # TerminalInteractiveShell
3677 c = configurables[classnames.index(line)]
3678 c = configurables[classnames.index(line)]
3678 cls = c.__class__
3679 cls = c.__class__
3679 help = cls.class_get_help(c)
3680 help = cls.class_get_help(c)
3680 # strip leading '--' from cl-args:
3681 # strip leading '--' from cl-args:
3681 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3682 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3682 print help
3683 print help
3683 return
3684 return
3684 elif '=' not in line:
3685 elif '=' not in line:
3685 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3686 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3686
3687
3687
3688
3688 # otherwise, assume we are setting configurables.
3689 # otherwise, assume we are setting configurables.
3689 # leave quotes on args when splitting, because we want
3690 # leave quotes on args when splitting, because we want
3690 # unquoted args to eval in user_ns
3691 # unquoted args to eval in user_ns
3691 cfg = Config()
3692 cfg = Config()
3692 exec "cfg."+line in locals(), self.user_ns
3693 exec "cfg."+line in locals(), self.user_ns
3693
3694
3694 for configurable in configurables:
3695 for configurable in configurables:
3695 try:
3696 try:
3696 configurable.update_config(cfg)
3697 configurable.update_config(cfg)
3697 except Exception as e:
3698 except Exception as e:
3698 error(e)
3699 error(e)
3699
3700
3701 def magic_clear(self, s):
3702 """Clear various data (e.g. stored history data)
3703
3704 %clear in - clear input history
3705 %clear out - clear output history
3706 %clear dhist - clear dir history
3707 %clear array - clear only variables that are NumPy arrays
3708
3709 Examples
3710 --------
3711 ::
3712
3713 In [1]: clear in
3714 Flushing input history
3715
3716 In [2]: clear dhist
3717 Clearing directory history
3718 """
3719 ip = self.shell
3720 user_ns = self.user_ns # local lookup, heavily used
3721
3722 for target in s.split():
3723 if target == 'out':
3724 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
3725 self.displayhook.flush()
3726
3727 elif target == 'in':
3728 print "Flushing input history"
3729 pc = self.displayhook.prompt_count + 1
3730 for n in range(1, pc):
3731 key = '_i'+repr(n)
3732 user_ns.pop(key,None)
3733 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
3734 # don't delete these, as %save and %macro depending on the length
3735 # of these lists to be preserved
3736 self.history_manager.input_hist_parsed[:] = [''] * pc
3737 self.history_manager.input_hist_raw[:] = [''] * pc
3738
3739 elif target == 'array':
3740 # Support cleaning up numpy arrays
3741 try:
3742 from numpy import ndarray
3743 # This must be done with items and not iteritems because we're
3744 # going to modify the dict in-place.
3745 for x,val in user_ns.items():
3746 if isinstance(val,ndarray):
3747 del user_ns[x]
3748 except ImportError:
3749 print "Clear array only works if Numpy is available."
3750
3751 elif target == 'dhist':
3752 print "Clearing directory history"
3753 del user_ns['_dh'][:]
3754
3755 gc.collect()
3756
3700 # end Magic
3757 # end Magic
@@ -1,389 +1,387 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12
12
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 from IPython.testing import decorators as dec
15 from IPython.testing import decorators as dec
16 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils import py3compat
17 from IPython.utils import py3compat
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Test functions begin
20 # Test functions begin
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 def test_rehashx():
23 def test_rehashx():
24 # clear up everything
24 # clear up everything
25 _ip = get_ipython()
25 _ip = get_ipython()
26 _ip.alias_manager.alias_table.clear()
26 _ip.alias_manager.alias_table.clear()
27 del _ip.db['syscmdlist']
27 del _ip.db['syscmdlist']
28
28
29 _ip.magic('rehashx')
29 _ip.magic('rehashx')
30 # Practically ALL ipython development systems will have more than 10 aliases
30 # Practically ALL ipython development systems will have more than 10 aliases
31
31
32 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
32 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
33 for key, val in _ip.alias_manager.alias_table.iteritems():
33 for key, val in _ip.alias_manager.alias_table.iteritems():
34 # we must strip dots from alias names
34 # we must strip dots from alias names
35 nt.assert_true('.' not in key)
35 nt.assert_true('.' not in key)
36
36
37 # rehashx must fill up syscmdlist
37 # rehashx must fill up syscmdlist
38 scoms = _ip.db['syscmdlist']
38 scoms = _ip.db['syscmdlist']
39 yield (nt.assert_true, len(scoms) > 10)
39 yield (nt.assert_true, len(scoms) > 10)
40
40
41
41
42 def test_magic_parse_options():
42 def test_magic_parse_options():
43 """Test that we don't mangle paths when parsing magic options."""
43 """Test that we don't mangle paths when parsing magic options."""
44 ip = get_ipython()
44 ip = get_ipython()
45 path = 'c:\\x'
45 path = 'c:\\x'
46 opts = ip.parse_options('-f %s' % path,'f:')[0]
46 opts = ip.parse_options('-f %s' % path,'f:')[0]
47 # argv splitting is os-dependent
47 # argv splitting is os-dependent
48 if os.name == 'posix':
48 if os.name == 'posix':
49 expected = 'c:x'
49 expected = 'c:x'
50 else:
50 else:
51 expected = path
51 expected = path
52 nt.assert_equals(opts['f'], expected)
52 nt.assert_equals(opts['f'], expected)
53
53
54
54
55 @dec.skip_without('sqlite3')
55 @dec.skip_without('sqlite3')
56 def doctest_hist_f():
56 def doctest_hist_f():
57 """Test %hist -f with temporary filename.
57 """Test %hist -f with temporary filename.
58
58
59 In [9]: import tempfile
59 In [9]: import tempfile
60
60
61 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
61 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
62
62
63 In [11]: %hist -nl -f $tfile 3
63 In [11]: %hist -nl -f $tfile 3
64
64
65 In [13]: import os; os.unlink(tfile)
65 In [13]: import os; os.unlink(tfile)
66 """
66 """
67
67
68
68
69 @dec.skip_without('sqlite3')
69 @dec.skip_without('sqlite3')
70 def doctest_hist_r():
70 def doctest_hist_r():
71 """Test %hist -r
71 """Test %hist -r
72
72
73 XXX - This test is not recording the output correctly. For some reason, in
73 XXX - This test is not recording the output correctly. For some reason, in
74 testing mode the raw history isn't getting populated. No idea why.
74 testing mode the raw history isn't getting populated. No idea why.
75 Disabling the output checking for now, though at least we do run it.
75 Disabling the output checking for now, though at least we do run it.
76
76
77 In [1]: 'hist' in _ip.lsmagic()
77 In [1]: 'hist' in _ip.lsmagic()
78 Out[1]: True
78 Out[1]: True
79
79
80 In [2]: x=1
80 In [2]: x=1
81
81
82 In [3]: %hist -rl 2
82 In [3]: %hist -rl 2
83 x=1 # random
83 x=1 # random
84 %hist -r 2
84 %hist -r 2
85 """
85 """
86
86
87
87
88 @dec.skip_without('sqlite3')
88 @dec.skip_without('sqlite3')
89 def doctest_hist_op():
89 def doctest_hist_op():
90 """Test %hist -op
90 """Test %hist -op
91
91
92 In [1]: class b(float):
92 In [1]: class b(float):
93 ...: pass
93 ...: pass
94 ...:
94 ...:
95
95
96 In [2]: class s(object):
96 In [2]: class s(object):
97 ...: def __str__(self):
97 ...: def __str__(self):
98 ...: return 's'
98 ...: return 's'
99 ...:
99 ...:
100
100
101 In [3]:
101 In [3]:
102
102
103 In [4]: class r(b):
103 In [4]: class r(b):
104 ...: def __repr__(self):
104 ...: def __repr__(self):
105 ...: return 'r'
105 ...: return 'r'
106 ...:
106 ...:
107
107
108 In [5]: class sr(s,r): pass
108 In [5]: class sr(s,r): pass
109 ...:
109 ...:
110
110
111 In [6]:
111 In [6]:
112
112
113 In [7]: bb=b()
113 In [7]: bb=b()
114
114
115 In [8]: ss=s()
115 In [8]: ss=s()
116
116
117 In [9]: rr=r()
117 In [9]: rr=r()
118
118
119 In [10]: ssrr=sr()
119 In [10]: ssrr=sr()
120
120
121 In [11]: 4.5
121 In [11]: 4.5
122 Out[11]: 4.5
122 Out[11]: 4.5
123
123
124 In [12]: str(ss)
124 In [12]: str(ss)
125 Out[12]: 's'
125 Out[12]: 's'
126
126
127 In [13]:
127 In [13]:
128
128
129 In [14]: %hist -op
129 In [14]: %hist -op
130 >>> class b:
130 >>> class b:
131 ... pass
131 ... pass
132 ...
132 ...
133 >>> class s(b):
133 >>> class s(b):
134 ... def __str__(self):
134 ... def __str__(self):
135 ... return 's'
135 ... return 's'
136 ...
136 ...
137 >>>
137 >>>
138 >>> class r(b):
138 >>> class r(b):
139 ... def __repr__(self):
139 ... def __repr__(self):
140 ... return 'r'
140 ... return 'r'
141 ...
141 ...
142 >>> class sr(s,r): pass
142 >>> class sr(s,r): pass
143 >>>
143 >>>
144 >>> bb=b()
144 >>> bb=b()
145 >>> ss=s()
145 >>> ss=s()
146 >>> rr=r()
146 >>> rr=r()
147 >>> ssrr=sr()
147 >>> ssrr=sr()
148 >>> 4.5
148 >>> 4.5
149 4.5
149 4.5
150 >>> str(ss)
150 >>> str(ss)
151 's'
151 's'
152 >>>
152 >>>
153 """
153 """
154
154
155
155
156 @dec.skip_without('sqlite3')
156 @dec.skip_without('sqlite3')
157 def test_macro():
157 def test_macro():
158 ip = get_ipython()
158 ip = get_ipython()
159 ip.history_manager.reset() # Clear any existing history.
159 ip.history_manager.reset() # Clear any existing history.
160 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
160 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
161 for i, cmd in enumerate(cmds, start=1):
161 for i, cmd in enumerate(cmds, start=1):
162 ip.history_manager.store_inputs(i, cmd)
162 ip.history_manager.store_inputs(i, cmd)
163 ip.magic("macro test 1-3")
163 ip.magic("macro test 1-3")
164 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
164 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
165
165
166 # List macros.
166 # List macros.
167 assert "test" in ip.magic("macro")
167 assert "test" in ip.magic("macro")
168
168
169
169
170 @dec.skip_without('sqlite3')
170 @dec.skip_without('sqlite3')
171 def test_macro_run():
171 def test_macro_run():
172 """Test that we can run a multi-line macro successfully."""
172 """Test that we can run a multi-line macro successfully."""
173 ip = get_ipython()
173 ip = get_ipython()
174 ip.history_manager.reset()
174 ip.history_manager.reset()
175 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
175 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
176 "%macro test 2-3"]
176 "%macro test 2-3"]
177 for cmd in cmds:
177 for cmd in cmds:
178 ip.run_cell(cmd, store_history=True)
178 ip.run_cell(cmd, store_history=True)
179 nt.assert_equal(ip.user_ns["test"].value,
179 nt.assert_equal(ip.user_ns["test"].value,
180 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
180 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
181 with tt.AssertPrints("12"):
181 with tt.AssertPrints("12"):
182 ip.run_cell("test")
182 ip.run_cell("test")
183 with tt.AssertPrints("13"):
183 with tt.AssertPrints("13"):
184 ip.run_cell("test")
184 ip.run_cell("test")
185
185
186
186
187 @dec.skipif_not_numpy
187 @dec.skipif_not_numpy
188 def test_numpy_clear_array_undec():
188 def test_numpy_clear_array_undec():
189 "Test '%clear array' functionality"
189 "Test '%clear array' functionality"
190 _ip.magic("load_ext clearcmd")
191 _ip.ex('import numpy as np')
190 _ip.ex('import numpy as np')
192 _ip.ex('a = np.empty(2)')
191 _ip.ex('a = np.empty(2)')
193 yield (nt.assert_true, 'a' in _ip.user_ns)
192 yield (nt.assert_true, 'a' in _ip.user_ns)
194 _ip.magic('clear array')
193 _ip.magic('clear array')
195 yield (nt.assert_false, 'a' in _ip.user_ns)
194 yield (nt.assert_false, 'a' in _ip.user_ns)
196
195
197 def test_clear():
196 def test_clear():
198 "Test '%clear' magic provided by IPython.extensions.clearcmd"
197 "Test '%clear' magic provided by IPython.extensions.clearcmd"
199 _ip = get_ipython()
198 _ip = get_ipython()
200 _ip.magic("load_ext clearcmd")
201 _ip.run_cell("parrot = 'dead'", store_history=True)
199 _ip.run_cell("parrot = 'dead'", store_history=True)
202 # test '%clear out', make an Out prompt
200 # test '%clear out', make an Out prompt
203 _ip.run_cell("parrot", store_history=True)
201 _ip.run_cell("parrot", store_history=True)
204 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
202 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
205 _ip.magic('clear out')
203 _ip.magic('clear out')
206 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
204 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
207 nt.assert_true(len(_ip.user_ns['Out']) == 0)
205 nt.assert_true(len(_ip.user_ns['Out']) == 0)
208
206
209 # test '%clear in'
207 # test '%clear in'
210 _ip.run_cell("parrot", store_history=True)
208 _ip.run_cell("parrot", store_history=True)
211 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
209 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
212 _ip.magic('%clear in')
210 _ip.magic('%clear in')
213 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
211 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
214 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
212 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
215
213
216 # test '%clear dhist'
214 # test '%clear dhist'
217 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
215 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
218 _ip.magic('cd')
216 _ip.magic('cd')
219 _ip.magic('cd -')
217 _ip.magic('cd -')
220 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
218 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
221 _ip.magic('clear dhist')
219 _ip.magic('clear dhist')
222 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
220 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
223 _ip.run_cell("_dh = [d for d in tmp]") #restore
221 _ip.run_cell("_dh = [d for d in tmp]") #restore
224
222
225 # test that In length is preserved for %macro
223 # test that In length is preserved for %macro
226 _ip.run_cell("print 'foo'")
224 _ip.run_cell("print 'foo'")
227 _ip.run_cell("clear in")
225 _ip.run_cell("clear in")
228 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
226 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
229
227
230 def test_time():
228 def test_time():
231 _ip.magic('time None')
229 _ip.magic('time None')
232
230
233
231
234 @py3compat.doctest_refactor_print
232 @py3compat.doctest_refactor_print
235 def doctest_time():
233 def doctest_time():
236 """
234 """
237 In [10]: %time None
235 In [10]: %time None
238 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
236 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
239 Wall time: 0.00 s
237 Wall time: 0.00 s
240
238
241 In [11]: def f(kmjy):
239 In [11]: def f(kmjy):
242 ....: %time print 2*kmjy
240 ....: %time print 2*kmjy
243
241
244 In [12]: f(3)
242 In [12]: f(3)
245 6
243 6
246 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
244 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
247 Wall time: 0.00 s
245 Wall time: 0.00 s
248 """
246 """
249
247
250
248
251 def test_doctest_mode():
249 def test_doctest_mode():
252 "Toggle doctest_mode twice, it should be a no-op and run without error"
250 "Toggle doctest_mode twice, it should be a no-op and run without error"
253 _ip.magic('doctest_mode')
251 _ip.magic('doctest_mode')
254 _ip.magic('doctest_mode')
252 _ip.magic('doctest_mode')
255
253
256
254
257 def test_parse_options():
255 def test_parse_options():
258 """Tests for basic options parsing in magics."""
256 """Tests for basic options parsing in magics."""
259 # These are only the most minimal of tests, more should be added later. At
257 # These are only the most minimal of tests, more should be added later. At
260 # the very least we check that basic text/unicode calls work OK.
258 # the very least we check that basic text/unicode calls work OK.
261 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
259 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
262 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
260 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
263
261
264
262
265 def test_dirops():
263 def test_dirops():
266 """Test various directory handling operations."""
264 """Test various directory handling operations."""
267 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
265 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
268 curpath = os.getcwdu
266 curpath = os.getcwdu
269 startdir = os.getcwdu()
267 startdir = os.getcwdu()
270 ipdir = os.path.realpath(_ip.ipython_dir)
268 ipdir = os.path.realpath(_ip.ipython_dir)
271 try:
269 try:
272 _ip.magic('cd "%s"' % ipdir)
270 _ip.magic('cd "%s"' % ipdir)
273 nt.assert_equal(curpath(), ipdir)
271 nt.assert_equal(curpath(), ipdir)
274 _ip.magic('cd -')
272 _ip.magic('cd -')
275 nt.assert_equal(curpath(), startdir)
273 nt.assert_equal(curpath(), startdir)
276 _ip.magic('pushd "%s"' % ipdir)
274 _ip.magic('pushd "%s"' % ipdir)
277 nt.assert_equal(curpath(), ipdir)
275 nt.assert_equal(curpath(), ipdir)
278 _ip.magic('popd')
276 _ip.magic('popd')
279 nt.assert_equal(curpath(), startdir)
277 nt.assert_equal(curpath(), startdir)
280 finally:
278 finally:
281 os.chdir(startdir)
279 os.chdir(startdir)
282
280
283
281
284 def test_xmode():
282 def test_xmode():
285 # Calling xmode three times should be a no-op
283 # Calling xmode three times should be a no-op
286 xmode = _ip.InteractiveTB.mode
284 xmode = _ip.InteractiveTB.mode
287 for i in range(3):
285 for i in range(3):
288 _ip.magic("xmode")
286 _ip.magic("xmode")
289 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
287 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
290
288
291 def test_reset_hard():
289 def test_reset_hard():
292 monitor = []
290 monitor = []
293 class A(object):
291 class A(object):
294 def __del__(self):
292 def __del__(self):
295 monitor.append(1)
293 monitor.append(1)
296 def __repr__(self):
294 def __repr__(self):
297 return "<A instance>"
295 return "<A instance>"
298
296
299 _ip.user_ns["a"] = A()
297 _ip.user_ns["a"] = A()
300 _ip.run_cell("a")
298 _ip.run_cell("a")
301
299
302 nt.assert_equal(monitor, [])
300 nt.assert_equal(monitor, [])
303 _ip.magic_reset("-f")
301 _ip.magic_reset("-f")
304 nt.assert_equal(monitor, [1])
302 nt.assert_equal(monitor, [1])
305
303
306 class TestXdel(tt.TempFileMixin):
304 class TestXdel(tt.TempFileMixin):
307 def test_xdel(self):
305 def test_xdel(self):
308 """Test that references from %run are cleared by xdel."""
306 """Test that references from %run are cleared by xdel."""
309 src = ("class A(object):\n"
307 src = ("class A(object):\n"
310 " monitor = []\n"
308 " monitor = []\n"
311 " def __del__(self):\n"
309 " def __del__(self):\n"
312 " self.monitor.append(1)\n"
310 " self.monitor.append(1)\n"
313 "a = A()\n")
311 "a = A()\n")
314 self.mktmp(src)
312 self.mktmp(src)
315 # %run creates some hidden references...
313 # %run creates some hidden references...
316 _ip.magic("run %s" % self.fname)
314 _ip.magic("run %s" % self.fname)
317 # ... as does the displayhook.
315 # ... as does the displayhook.
318 _ip.run_cell("a")
316 _ip.run_cell("a")
319
317
320 monitor = _ip.user_ns["A"].monitor
318 monitor = _ip.user_ns["A"].monitor
321 nt.assert_equal(monitor, [])
319 nt.assert_equal(monitor, [])
322
320
323 _ip.magic("xdel a")
321 _ip.magic("xdel a")
324
322
325 # Check that a's __del__ method has been called.
323 # Check that a's __del__ method has been called.
326 nt.assert_equal(monitor, [1])
324 nt.assert_equal(monitor, [1])
327
325
328 def doctest_who():
326 def doctest_who():
329 """doctest for %who
327 """doctest for %who
330
328
331 In [1]: %reset -f
329 In [1]: %reset -f
332
330
333 In [2]: alpha = 123
331 In [2]: alpha = 123
334
332
335 In [3]: beta = 'beta'
333 In [3]: beta = 'beta'
336
334
337 In [4]: %who int
335 In [4]: %who int
338 alpha
336 alpha
339
337
340 In [5]: %who str
338 In [5]: %who str
341 beta
339 beta
342
340
343 In [6]: %whos
341 In [6]: %whos
344 Variable Type Data/Info
342 Variable Type Data/Info
345 ----------------------------
343 ----------------------------
346 alpha int 123
344 alpha int 123
347 beta str beta
345 beta str beta
348
346
349 In [7]: %who_ls
347 In [7]: %who_ls
350 Out[7]: ['alpha', 'beta']
348 Out[7]: ['alpha', 'beta']
351 """
349 """
352
350
353 @py3compat.u_format
351 @py3compat.u_format
354 def doctest_precision():
352 def doctest_precision():
355 """doctest for %precision
353 """doctest for %precision
356
354
357 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
355 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
358
356
359 In [2]: %precision 5
357 In [2]: %precision 5
360 Out[2]: {u}'%.5f'
358 Out[2]: {u}'%.5f'
361
359
362 In [3]: f.float_format
360 In [3]: f.float_format
363 Out[3]: {u}'%.5f'
361 Out[3]: {u}'%.5f'
364
362
365 In [4]: %precision %e
363 In [4]: %precision %e
366 Out[4]: {u}'%e'
364 Out[4]: {u}'%e'
367
365
368 In [5]: f(3.1415927)
366 In [5]: f(3.1415927)
369 Out[5]: {u}'3.141593e+00'
367 Out[5]: {u}'3.141593e+00'
370 """
368 """
371
369
372 def test_psearch():
370 def test_psearch():
373 with tt.AssertPrints("dict.fromkeys"):
371 with tt.AssertPrints("dict.fromkeys"):
374 _ip.run_cell("dict.fr*?")
372 _ip.run_cell("dict.fr*?")
375
373
376 def test_timeit_shlex():
374 def test_timeit_shlex():
377 """test shlex issues with timeit (#1109)"""
375 """test shlex issues with timeit (#1109)"""
378 _ip.ex("def f(*a,**kw): pass")
376 _ip.ex("def f(*a,**kw): pass")
379 _ip.magic('timeit -n1 "this is a bug".count(" ")')
377 _ip.magic('timeit -n1 "this is a bug".count(" ")')
380 _ip.magic('timeit -r1 -n1 f(" ", 1)')
378 _ip.magic('timeit -r1 -n1 f(" ", 1)')
381 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
379 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
382 _ip.magic('timeit -r1 -n1 ("a " + "b")')
380 _ip.magic('timeit -r1 -n1 ("a " + "b")')
383 _ip.magic('timeit -r1 -n1 f("a " + "b")')
381 _ip.magic('timeit -r1 -n1 f("a " + "b")')
384 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
382 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
385
383
386
384
387 def test_timeit_arguments():
385 def test_timeit_arguments():
388 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
386 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
389 _ip.magic("timeit ('#')")
387 _ip.magic("timeit ('#')")
@@ -1,312 +1,310 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 %jot magic for lightweight persistence.
3 %jot magic for lightweight persistence.
4
4
5 Stores variables in Struct with some notes in PicleShare database
5 Stores variables in Struct with some notes in PicleShare database
6
6
7
7
8 """
8 """
9
9
10 from datetime import datetime
10 from datetime import datetime
11 from IPython.core import ipapi
11 from IPython.core import ipapi
12 ip = ipapi.get()
12 ip = ipapi.get()
13
13
14 import pickleshare
14 import pickleshare
15
15
16 import inspect,pickle,os,sys,textwrap
16 import inspect,pickle,os,sys,textwrap
17 from IPython.core.fakemodule import FakeModule
17 from IPython.core.fakemodule import FakeModule
18 from IPython.utils.ipstruct import Struct
18 from IPython.utils.ipstruct import Struct
19 from IPython.utils.warn import error
19 from IPython.utils.warn import error
20
20
21
21
22 def refresh_variables(ip, key=None):
22 def refresh_variables(ip, key=None):
23 db = ip.db
23 db = ip.db
24 if key is None:
24 if key is None:
25 keys = db.keys('jot/*')
25 keys = db.keys('jot/*')
26 else:
26 else:
27 keys = db.keys('jot/'+key)
27 keys = db.keys('jot/'+key)
28 for key in keys:
28 for key in keys:
29 # strip autorestore
29 # strip autorestore
30 justkey = os.path.basename(key)
30 justkey = os.path.basename(key)
31 print "Restoring from", justkey, "..."
31 print "Restoring from", justkey, "..."
32 try:
32 try:
33 obj = db[key]
33 obj = db[key]
34 except KeyError:
34 except KeyError:
35 print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey
35 print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey
36 print "The error was:",sys.exc_info()[0]
36 print "The error was:",sys.exc_info()[0]
37 else:
37 else:
38 #print "restored",justkey,"=",obj #dbg
38 #print "restored",justkey,"=",obj #dbg
39 try:
39 try:
40 origname = obj.name
40 origname = obj.name
41 except:
41 except:
42 ip.user_ns[justkey] = obj
42 ip.user_ns[justkey] = obj
43 print "Restored", justkey
43 print "Restored", justkey
44 else:
44 else:
45 ip.user_ns[origname] = obj['val']
45 ip.user_ns[origname] = obj['val']
46 print "Restored", origname
46 print "Restored", origname
47
47
48 def read_variables(ip, key=None):
48 def read_variables(ip, key=None):
49 db = ip.db
49 db = ip.db
50 if key is None:
50 if key is None:
51 return None
51 return None
52 else:
52 else:
53 keys = db.keys('jot/'+key)
53 keys = db.keys('jot/'+key)
54 for key in keys:
54 for key in keys:
55 # strip autorestore
55 # strip autorestore
56 justkey = os.path.basename(key)
56 justkey = os.path.basename(key)
57 print "restoring from ", justkey
57 print "restoring from ", justkey
58 try:
58 try:
59 obj = db[key]
59 obj = db[key]
60 except KeyError:
60 except KeyError:
61 print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey
61 print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey
62 print "The error was:",sys.exc_info()[0]
62 print "The error was:",sys.exc_info()[0]
63 else:
63 else:
64 return obj
64 return obj
65
65
66
66
67 def detail_variables(ip, key=None):
67 def detail_variables(ip, key=None):
68 db, get = ip.db, ip.db.get
68 db, get = ip.db, ip.db.get
69
69
70 if key is None:
70 if key is None:
71 keys = db.keys('jot/*')
71 keys = db.keys('jot/*')
72 else:
72 else:
73 keys = db.keys('jot/'+key)
73 keys = db.keys('jot/'+key)
74 if keys:
74 if keys:
75 size = max(map(len,keys))
75 size = max(map(len,keys))
76 else:
76 else:
77 size = 0
77 size = 0
78
78
79 fmthead = '%-'+str(size)+'s [%s]'
79 fmthead = '%-'+str(size)+'s [%s]'
80 fmtbody = 'Comment:\n %s'
80 fmtbody = 'Comment:\n %s'
81 fmtdata = 'Data:\n %s, %s'
81 fmtdata = 'Data:\n %s, %s'
82 for key in keys:
82 for key in keys:
83 v = get(key,'<unavailable>')
83 v = get(key,'<unavailable>')
84 justkey = os.path.basename(key)
84 justkey = os.path.basename(key)
85 try:
85 try:
86 print fmthead % (justkey, datetime.ctime(v.get('time','<unavailable>')))
86 print fmthead % (justkey, datetime.ctime(v.get('time','<unavailable>')))
87 print fmtbody % (v.get('comment','<unavailable>'))
87 print fmtbody % (v.get('comment','<unavailable>'))
88 d = v.get('val','unavailable')
88 d = v.get('val','unavailable')
89 print fmtdata % (repr(type(d)), '')
89 print fmtdata % (repr(type(d)), '')
90 print repr(d)[0:200]
90 print repr(d)[0:200]
91 print
91 print
92 print
92 print
93 except AttributeError:
93 except AttributeError:
94 print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50])
94 print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50])
95
95
96
96
97 def intm(n):
97 def intm(n):
98 try:
98 try:
99 return int(n)
99 return int(n)
100 except:
100 except:
101 return 0
101 return 0
102
102
103 def jot_obj(self, obj, name, comment=''):
103 def jot_obj(self, obj, name, comment=''):
104 """
104 """
105 write obj data to the note database, with whatever that should be noted.
105 write obj data to the note database, with whatever that should be noted.
106 """
106 """
107 had = self.db.keys('jot/'+name+'*')
107 had = self.db.keys('jot/'+name+'*')
108 # if it the same name but a later version, we stupidly add a number to the
108 # if it the same name but a later version, we stupidly add a number to the
109 # so the name doesn't collide. Any better idea?
109 # so the name doesn't collide. Any better idea?
110 suffix = ''
110 suffix = ''
111 if len(had)>0:
111 if len(had)>0:
112 pre = os.path.commonprefix(had)
112 pre = os.path.commonprefix(had)
113 suf = [n.split(pre)[1] for n in had]
113 suf = [n.split(pre)[1] for n in had]
114 versions = map(intm, suf)
114 versions = map(intm, suf)
115 suffix = str(max(versions)+1)
115 suffix = str(max(versions)+1)
116
116
117 uname = 'jot/'+name+suffix
117 uname = 'jot/'+name+suffix
118
118
119 # which one works better?
120 #all = ip.shadowhist.all()
121 all = ip.shell.history_manager.input_hist_parsed
119 all = ip.shell.history_manager.input_hist_parsed
122
120
123 # We may actually want to make snapshot of files that are run-ned.
121 # We may actually want to make snapshot of files that are run-ned.
124
122
125 # get the comment
123 # get the comment
126 try:
124 try:
127 comment = ip.magic_edit('-x').strip()
125 comment = ip.magic_edit('-x').strip()
128 except:
126 except:
129 print "No comment is recorded."
127 print "No comment is recorded."
130 comment = ''
128 comment = ''
131
129
132 self.db[uname] = Struct({'val':obj,
130 self.db[uname] = Struct({'val':obj,
133 'time' : datetime.now(),
131 'time' : datetime.now(),
134 'hist' : all,
132 'hist' : all,
135 'name' : name,
133 'name' : name,
136 'comment' : comment,})
134 'comment' : comment,})
137
135
138 print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__)
136 print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__)
139
137
140
138
141
139
142 def magic_jot(self, parameter_s=''):
140 def magic_jot(self, parameter_s=''):
143 """Lightweight persistence for python variables.
141 """Lightweight persistence for python variables.
144
142
145 Example:
143 Example:
146
144
147 ville@badger[~]|1> A = ['hello',10,'world']\\
145 ville@badger[~]|1> A = ['hello',10,'world']\\
148 ville@badger[~]|2> %jot A\\
146 ville@badger[~]|2> %jot A\\
149 ville@badger[~]|3> Exit
147 ville@badger[~]|3> Exit
150
148
151 (IPython session is closed and started again...)
149 (IPython session is closed and started again...)
152
150
153 ville@badger:~$ ipython -p pysh\\
151 ville@badger:~$ ipython -p pysh\\
154 ville@badger[~]|1> print A
152 ville@badger[~]|1> print A
155
153
156 ['hello', 10, 'world']
154 ['hello', 10, 'world']
157
155
158 Usage:
156 Usage:
159
157
160 %jot - Show list of all variables and their current values\\
158 %jot - Show list of all variables and their current values\\
161 %jot -l - Show list of all variables and their current values in detail\\
159 %jot -l - Show list of all variables and their current values in detail\\
162 %jot -l <var> - Show one variable and its current values in detail\\
160 %jot -l <var> - Show one variable and its current values in detail\\
163 %jot <var> - Store the *current* value of the variable to disk\\
161 %jot <var> - Store the *current* value of the variable to disk\\
164 %jot -d <var> - Remove the variable and its value from storage\\
162 %jot -d <var> - Remove the variable and its value from storage\\
165 %jot -z - Remove all variables from storage (disabled)\\
163 %jot -z - Remove all variables from storage (disabled)\\
166 %jot -r <var> - Refresh/Load variable from jot (delete current vals)\\
164 %jot -r <var> - Refresh/Load variable from jot (delete current vals)\\
167 %jot foo >a.txt - Store value of foo to new file a.txt\\
165 %jot foo >a.txt - Store value of foo to new file a.txt\\
168 %jot foo >>a.txt - Append value of foo to file a.txt\\
166 %jot foo >>a.txt - Append value of foo to file a.txt\\
169
167
170 It should be noted that if you change the value of a variable, you
168 It should be noted that if you change the value of a variable, you
171 need to %note it again if you want to persist the new value.
169 need to %note it again if you want to persist the new value.
172
170
173 Note also that the variables will need to be pickleable; most basic
171 Note also that the variables will need to be pickleable; most basic
174 python types can be safely %stored.
172 python types can be safely %stored.
175
173
176 """
174 """
177
175
178 opts,argsl = self.parse_options(parameter_s,'drzl',mode='string')
176 opts,argsl = self.parse_options(parameter_s,'drzl',mode='string')
179 args = argsl.split(None,1)
177 args = argsl.split(None,1)
180 ip = self.getapi()
178 ip = self.getapi()
181 db = ip.db
179 db = ip.db
182 # delete
180 # delete
183 if opts.has_key('d'):
181 if opts.has_key('d'):
184 try:
182 try:
185 todel = args[0]
183 todel = args[0]
186 except IndexError:
184 except IndexError:
187 error('You must provide the variable to forget')
185 error('You must provide the variable to forget')
188 else:
186 else:
189 try:
187 try:
190 del db['jot/' + todel]
188 del db['jot/' + todel]
191 except:
189 except:
192 error("Can't delete variable '%s'" % todel)
190 error("Can't delete variable '%s'" % todel)
193 # reset the whole database
191 # reset the whole database
194 elif opts.has_key('z'):
192 elif opts.has_key('z'):
195 print "reseting the whole database has been disabled."
193 print "reseting the whole database has been disabled."
196 #for k in db.keys('autorestore/*'):
194 #for k in db.keys('autorestore/*'):
197 # del db[k]
195 # del db[k]
198
196
199 elif opts.has_key('r'):
197 elif opts.has_key('r'):
200 try:
198 try:
201 toret = args[0]
199 toret = args[0]
202 except:
200 except:
203 print "restoring all the variables jotted down..."
201 print "restoring all the variables jotted down..."
204 refresh_variables(ip)
202 refresh_variables(ip)
205 else:
203 else:
206 refresh_variables(ip, toret)
204 refresh_variables(ip, toret)
207
205
208 elif opts.has_key('l'):
206 elif opts.has_key('l'):
209 try:
207 try:
210 tolist = args[0]
208 tolist = args[0]
211 except:
209 except:
212 print "List details for all the items."
210 print "List details for all the items."
213 detail_variables(ip)
211 detail_variables(ip)
214 else:
212 else:
215 print "Details for", tolist, ":"
213 print "Details for", tolist, ":"
216 detail_variables(ip, tolist)
214 detail_variables(ip, tolist)
217
215
218 # run without arguments -> list noted variables & notes
216 # run without arguments -> list noted variables & notes
219 elif not args:
217 elif not args:
220 vars = self.db.keys('jot/*')
218 vars = self.db.keys('jot/*')
221 vars.sort()
219 vars.sort()
222 if vars:
220 if vars:
223 size = max(map(len,vars)) - 4
221 size = max(map(len,vars)) - 4
224 else:
222 else:
225 size = 0
223 size = 0
226
224
227 print 'Variables and their in-db values:'
225 print 'Variables and their in-db values:'
228 fmt = '%-'+str(size)+'s [%s] -> %s'
226 fmt = '%-'+str(size)+'s [%s] -> %s'
229 get = db.get
227 get = db.get
230 for var in vars:
228 for var in vars:
231 justkey = os.path.basename(var)
229 justkey = os.path.basename(var)
232 v = get(var,'<unavailable>')
230 v = get(var,'<unavailable>')
233 try:
231 try:
234 print fmt % (justkey,\
232 print fmt % (justkey,\
235 datetime.ctime(v.get('time','<unavailable>')),\
233 datetime.ctime(v.get('time','<unavailable>')),\
236 v.get('comment','<unavailable>')[:70].replace('\n',' '),)
234 v.get('comment','<unavailable>')[:70].replace('\n',' '),)
237 except AttributeError:
235 except AttributeError:
238 print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50])
236 print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50])
239
237
240
238
241 # default action - store the variable
239 # default action - store the variable
242 else:
240 else:
243 # %store foo >file.txt or >>file.txt
241 # %store foo >file.txt or >>file.txt
244 if len(args) > 1 and args[1].startswith('>'):
242 if len(args) > 1 and args[1].startswith('>'):
245 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
243 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
246 if args[1].startswith('>>'):
244 if args[1].startswith('>>'):
247 fil = open(fnam,'a')
245 fil = open(fnam,'a')
248 else:
246 else:
249 fil = open(fnam,'w')
247 fil = open(fnam,'w')
250 obj = ip.ev(args[0])
248 obj = ip.ev(args[0])
251 print "Writing '%s' (%s) to file '%s'." % (args[0],
249 print "Writing '%s' (%s) to file '%s'." % (args[0],
252 obj.__class__.__name__, fnam)
250 obj.__class__.__name__, fnam)
253
251
254
252
255 if not isinstance (obj,basestring):
253 if not isinstance (obj,basestring):
256 from pprint import pprint
254 from pprint import pprint
257 pprint(obj,fil)
255 pprint(obj,fil)
258 else:
256 else:
259 fil.write(obj)
257 fil.write(obj)
260 if not obj.endswith('\n'):
258 if not obj.endswith('\n'):
261 fil.write('\n')
259 fil.write('\n')
262
260
263 fil.close()
261 fil.close()
264 return
262 return
265
263
266 # %note foo
264 # %note foo
267 try:
265 try:
268 obj = ip.user_ns[args[0]]
266 obj = ip.user_ns[args[0]]
269 except KeyError:
267 except KeyError:
270 # this should not be alias, for aliases, use %store
268 # this should not be alias, for aliases, use %store
271 print
269 print
272 print "Error: %s doesn't exist." % args[0]
270 print "Error: %s doesn't exist." % args[0]
273 print
271 print
274 print "Use %note -r <var> to retrieve variables. This should not be used " +\
272 print "Use %note -r <var> to retrieve variables. This should not be used " +\
275 "to store alias, for saving aliases, use %store"
273 "to store alias, for saving aliases, use %store"
276 return
274 return
277 else:
275 else:
278 if isinstance(inspect.getmodule(obj), FakeModule):
276 if isinstance(inspect.getmodule(obj), FakeModule):
279 print textwrap.dedent("""\
277 print textwrap.dedent("""\
280 Warning:%s is %s
278 Warning:%s is %s
281 Proper storage of interactively declared classes (or instances
279 Proper storage of interactively declared classes (or instances
282 of those classes) is not possible! Only instances
280 of those classes) is not possible! Only instances
283 of classes in real modules on file system can be %%store'd.
281 of classes in real modules on file system can be %%store'd.
284 """ % (args[0], obj) )
282 """ % (args[0], obj) )
285 return
283 return
286 #pickled = pickle.dumps(obj)
284 #pickled = pickle.dumps(obj)
287 #self.db[ 'jot/' + args[0] ] = obj
285 #self.db[ 'jot/' + args[0] ] = obj
288 jot_obj(self, obj, args[0])
286 jot_obj(self, obj, args[0])
289
287
290
288
291 def magic_read(self, parameter_s=''):
289 def magic_read(self, parameter_s=''):
292 """
290 """
293 %read <var> - Load variable from data that is jotted down.\\
291 %read <var> - Load variable from data that is jotted down.\\
294
292
295 """
293 """
296
294
297 opts,argsl = self.parse_options(parameter_s,'drzl',mode='string')
295 opts,argsl = self.parse_options(parameter_s,'drzl',mode='string')
298 args = argsl.split(None,1)
296 args = argsl.split(None,1)
299 ip = self.getapi()
297 ip = self.getapi()
300 db = ip.db
298 db = ip.db
301 #if opts.has_key('r'):
299 #if opts.has_key('r'):
302 try:
300 try:
303 toret = args[0]
301 toret = args[0]
304 except:
302 except:
305 print "which record do you want to read out?"
303 print "which record do you want to read out?"
306 return
304 return
307 else:
305 else:
308 return read_variables(ip, toret)
306 return read_variables(ip, toret)
309
307
310
308
311 ip.define_magic('jot',magic_jot)
309 ip.define_magic('jot',magic_jot)
312 ip.define_magic('read',magic_read)
310 ip.define_magic('read',magic_read)
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now