##// END OF EJS Templates
Merge pull request #1309 from ivanov/inoculate-clear-magic...
Fernando Perez -
r5979:12b8a648 merge
parent child Browse files
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 reset_completer(self, event):
320 "A completer for %reset magic"
321 return '-f -s 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, reset_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', reset_completer, str_key = '%reset')
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,3698 +1,3769 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, if
964 called without arguments, or by removing some types of objects, such
965 as everything currently in IPython's In[] and Out[] containers (see
966 the parameters for details).
963
967
964 Parameters
968 Parameters
965 ----------
969 ----------
966 -f : force reset without asking for confirmation.
970 -f : force reset without asking for confirmation.
971
972 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
973 References to objects may be kept. By default (without this option),
974 we do a 'hard' reset, giving you a new session and removing all
975 references to objects from the current session.
976
977 in : reset input history
978
979 out : reset output history
980
981 dhist : reset directory history
982
983 array : reset only variables that are NumPy arrays
967
984
968 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
985 See Also
969 References to objects may be kept. By default (without this option),
986 --------
970 we do a 'hard' reset, giving you a new session and removing all
987 %reset_selective
971 references to objects from the current session.
972
988
973 Examples
989 Examples
974 --------
990 --------
975 In [6]: a = 1
991 In [6]: a = 1
976
992
977 In [7]: a
993 In [7]: a
978 Out[7]: 1
994 Out[7]: 1
979
995
980 In [8]: 'a' in _ip.user_ns
996 In [8]: 'a' in _ip.user_ns
981 Out[8]: True
997 Out[8]: True
982
998
983 In [9]: %reset -f
999 In [9]: %reset -f
984
1000
985 In [1]: 'a' in _ip.user_ns
1001 In [1]: 'a' in _ip.user_ns
986 Out[1]: False
1002 Out[1]: False
987
1003
1004 In [2]: %reset -f in
1005 Flushing input history
1006
1007 In [3]: %reset -f dhist in
1008 Flushing directory history
1009 Flushing input history
1010
988 Notes
1011 Notes
989 -----
1012 -----
990 Calling this magic from clients that do not implement standard input,
1013 Calling this magic from clients that do not implement standard input,
991 such as the ipython notebook interface, will reset the namespace
1014 such as the ipython notebook interface, will reset the namespace
992 without confirmation.
1015 without confirmation.
993 """
1016 """
994 opts, args = self.parse_options(parameter_s,'sf')
1017 opts, args = self.parse_options(parameter_s,'sf', mode='list')
995 if 'f' in opts:
1018 if 'f' in opts:
996 ans = True
1019 ans = True
997 else:
1020 else:
998 try:
1021 try:
999 ans = self.shell.ask_yes_no(
1022 ans = self.shell.ask_yes_no(
1000 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1023 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1001 except StdinNotImplementedError:
1024 except StdinNotImplementedError:
1002 ans = True
1025 ans = True
1003 if not ans:
1026 if not ans:
1004 print 'Nothing done.'
1027 print 'Nothing done.'
1005 return
1028 return
1006
1029
1007 if 's' in opts: # Soft reset
1030 if 's' in opts: # Soft reset
1008 user_ns = self.shell.user_ns
1031 user_ns = self.shell.user_ns
1009 for i in self.magic_who_ls():
1032 for i in self.magic_who_ls():
1010 del(user_ns[i])
1033 del(user_ns[i])
1011
1034 elif len(args) == 0: # Hard reset
1012 else: # Hard reset
1013 self.shell.reset(new_session = False)
1035 self.shell.reset(new_session = False)
1036
1037 # reset in/out/dhist/array: previously extensinions/clearcmd.py
1038 ip = self.shell
1039 user_ns = self.user_ns # local lookup, heavily used
1040
1041 for target in args:
1042 target = target.lower() # make matches case insensitive
1043 if target == 'out':
1044 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1045 self.displayhook.flush()
1046
1047 elif target == 'in':
1048 print "Flushing input history"
1049 pc = self.displayhook.prompt_count + 1
1050 for n in range(1, pc):
1051 key = '_i'+repr(n)
1052 user_ns.pop(key,None)
1053 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1054 hm = ip.history_manager
1055 # don't delete these, as %save and %macro depending on the length
1056 # of these lists to be preserved
1057 hm.input_hist_parsed[:] = [''] * pc
1058 hm.input_hist_raw[:] = [''] * pc
1059 # hm has internal machinery for _i,_ii,_iii, clear it out
1060 hm._i = hm._ii = hm._iii = hm._i00 = u''
1061
1062 elif target == 'array':
1063 # Support cleaning up numpy arrays
1064 try:
1065 from numpy import ndarray
1066 # This must be done with items and not iteritems because we're
1067 # going to modify the dict in-place.
1068 for x,val in user_ns.items():
1069 if isinstance(val,ndarray):
1070 del user_ns[x]
1071 except ImportError:
1072 print "reset array only works if Numpy is available."
1073
1074 elif target == 'dhist':
1075 print "Flushing directory history"
1076 del user_ns['_dh'][:]
1014
1077
1078 else:
1079 print "Don't know how to reset ",
1080 print target + ", please run `%reset?` for details"
1015
1081
1082 gc.collect()
1016
1083
1017 def magic_reset_selective(self, parameter_s=''):
1084 def magic_reset_selective(self, parameter_s=''):
1018 """Resets the namespace by removing names defined by the user.
1085 """Resets the namespace by removing names defined by the user.
1019
1086
1020 Input/Output history are left around in case you need them.
1087 Input/Output history are left around in case you need them.
1021
1088
1022 %reset_selective [-f] regex
1089 %reset_selective [-f] regex
1023
1090
1024 No action is taken if regex is not included
1091 No action is taken if regex is not included
1025
1092
1026 Options
1093 Options
1027 -f : force reset without asking for confirmation.
1094 -f : force reset without asking for confirmation.
1028
1095
1096 See Also
1097 --------
1098 %reset
1099
1029 Examples
1100 Examples
1030 --------
1101 --------
1031
1102
1032 We first fully reset the namespace so your output looks identical to
1103 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
1104 this example for pedagogical reasons; in practice you do not need a
1034 full reset.
1105 full reset.
1035
1106
1036 In [1]: %reset -f
1107 In [1]: %reset -f
1037
1108
1038 Now, with a clean namespace we can make a few variables and use
1109 Now, with a clean namespace we can make a few variables and use
1039 %reset_selective to only delete names that match our regexp:
1110 %reset_selective to only delete names that match our regexp:
1040
1111
1041 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1112 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1042
1113
1043 In [3]: who_ls
1114 In [3]: who_ls
1044 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1115 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1045
1116
1046 In [4]: %reset_selective -f b[2-3]m
1117 In [4]: %reset_selective -f b[2-3]m
1047
1118
1048 In [5]: who_ls
1119 In [5]: who_ls
1049 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1120 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1050
1121
1051 In [6]: %reset_selective -f d
1122 In [6]: %reset_selective -f d
1052
1123
1053 In [7]: who_ls
1124 In [7]: who_ls
1054 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1125 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1055
1126
1056 In [8]: %reset_selective -f c
1127 In [8]: %reset_selective -f c
1057
1128
1058 In [9]: who_ls
1129 In [9]: who_ls
1059 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1130 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1060
1131
1061 In [10]: %reset_selective -f b
1132 In [10]: %reset_selective -f b
1062
1133
1063 In [11]: who_ls
1134 In [11]: who_ls
1064 Out[11]: ['a']
1135 Out[11]: ['a']
1065
1136
1066 Notes
1137 Notes
1067 -----
1138 -----
1068 Calling this magic from clients that do not implement standard input,
1139 Calling this magic from clients that do not implement standard input,
1069 such as the ipython notebook interface, will reset the namespace
1140 such as the ipython notebook interface, will reset the namespace
1070 without confirmation.
1141 without confirmation.
1071 """
1142 """
1072
1143
1073 opts, regex = self.parse_options(parameter_s,'f')
1144 opts, regex = self.parse_options(parameter_s,'f')
1074
1145
1075 if opts.has_key('f'):
1146 if opts.has_key('f'):
1076 ans = True
1147 ans = True
1077 else:
1148 else:
1078 try:
1149 try:
1079 ans = self.shell.ask_yes_no(
1150 ans = self.shell.ask_yes_no(
1080 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1151 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1081 default='n')
1152 default='n')
1082 except StdinNotImplementedError:
1153 except StdinNotImplementedError:
1083 ans = True
1154 ans = True
1084 if not ans:
1155 if not ans:
1085 print 'Nothing done.'
1156 print 'Nothing done.'
1086 return
1157 return
1087 user_ns = self.shell.user_ns
1158 user_ns = self.shell.user_ns
1088 if not regex:
1159 if not regex:
1089 print 'No regex pattern specified. Nothing done.'
1160 print 'No regex pattern specified. Nothing done.'
1090 return
1161 return
1091 else:
1162 else:
1092 try:
1163 try:
1093 m = re.compile(regex)
1164 m = re.compile(regex)
1094 except TypeError:
1165 except TypeError:
1095 raise TypeError('regex must be a string or compiled pattern')
1166 raise TypeError('regex must be a string or compiled pattern')
1096 for i in self.magic_who_ls():
1167 for i in self.magic_who_ls():
1097 if m.search(i):
1168 if m.search(i):
1098 del(user_ns[i])
1169 del(user_ns[i])
1099
1170
1100 def magic_xdel(self, parameter_s=''):
1171 def magic_xdel(self, parameter_s=''):
1101 """Delete a variable, trying to clear it from anywhere that
1172 """Delete a variable, trying to clear it from anywhere that
1102 IPython's machinery has references to it. By default, this uses
1173 IPython's machinery has references to it. By default, this uses
1103 the identity of the named object in the user namespace to remove
1174 the identity of the named object in the user namespace to remove
1104 references held under other names. The object is also removed
1175 references held under other names. The object is also removed
1105 from the output history.
1176 from the output history.
1106
1177
1107 Options
1178 Options
1108 -n : Delete the specified name from all namespaces, without
1179 -n : Delete the specified name from all namespaces, without
1109 checking their identity.
1180 checking their identity.
1110 """
1181 """
1111 opts, varname = self.parse_options(parameter_s,'n')
1182 opts, varname = self.parse_options(parameter_s,'n')
1112 try:
1183 try:
1113 self.shell.del_var(varname, ('n' in opts))
1184 self.shell.del_var(varname, ('n' in opts))
1114 except (NameError, ValueError) as e:
1185 except (NameError, ValueError) as e:
1115 print type(e).__name__ +": "+ str(e)
1186 print type(e).__name__ +": "+ str(e)
1116
1187
1117 def magic_logstart(self,parameter_s=''):
1188 def magic_logstart(self,parameter_s=''):
1118 """Start logging anywhere in a session.
1189 """Start logging anywhere in a session.
1119
1190
1120 %logstart [-o|-r|-t] [log_name [log_mode]]
1191 %logstart [-o|-r|-t] [log_name [log_mode]]
1121
1192
1122 If no name is given, it defaults to a file named 'ipython_log.py' in your
1193 If no name is given, it defaults to a file named 'ipython_log.py' in your
1123 current directory, in 'rotate' mode (see below).
1194 current directory, in 'rotate' mode (see below).
1124
1195
1125 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1196 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1126 history up to that point and then continues logging.
1197 history up to that point and then continues logging.
1127
1198
1128 %logstart takes a second optional parameter: logging mode. This can be one
1199 %logstart takes a second optional parameter: logging mode. This can be one
1129 of (note that the modes are given unquoted):\\
1200 of (note that the modes are given unquoted):\\
1130 append: well, that says it.\\
1201 append: well, that says it.\\
1131 backup: rename (if exists) to name~ and start name.\\
1202 backup: rename (if exists) to name~ and start name.\\
1132 global: single logfile in your home dir, appended to.\\
1203 global: single logfile in your home dir, appended to.\\
1133 over : overwrite existing log.\\
1204 over : overwrite existing log.\\
1134 rotate: create rotating logs name.1~, name.2~, etc.
1205 rotate: create rotating logs name.1~, name.2~, etc.
1135
1206
1136 Options:
1207 Options:
1137
1208
1138 -o: log also IPython's output. In this mode, all commands which
1209 -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
1210 generate an Out[NN] prompt are recorded to the logfile, right after
1140 their corresponding input line. The output lines are always
1211 their corresponding input line. The output lines are always
1141 prepended with a '#[Out]# ' marker, so that the log remains valid
1212 prepended with a '#[Out]# ' marker, so that the log remains valid
1142 Python code.
1213 Python code.
1143
1214
1144 Since this marker is always the same, filtering only the output from
1215 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:
1216 a log is very easy, using for example a simple awk call:
1146
1217
1147 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1218 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1148
1219
1149 -r: log 'raw' input. Normally, IPython's logs contain the processed
1220 -r: log 'raw' input. Normally, IPython's logs contain the processed
1150 input, so that user lines are logged in their final form, converted
1221 input, so that user lines are logged in their final form, converted
1151 into valid Python. For example, %Exit is logged as
1222 into valid Python. For example, %Exit is logged as
1152 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1223 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1153 exactly as typed, with no transformations applied.
1224 exactly as typed, with no transformations applied.
1154
1225
1155 -t: put timestamps before each input line logged (these are put in
1226 -t: put timestamps before each input line logged (these are put in
1156 comments)."""
1227 comments)."""
1157
1228
1158 opts,par = self.parse_options(parameter_s,'ort')
1229 opts,par = self.parse_options(parameter_s,'ort')
1159 log_output = 'o' in opts
1230 log_output = 'o' in opts
1160 log_raw_input = 'r' in opts
1231 log_raw_input = 'r' in opts
1161 timestamp = 't' in opts
1232 timestamp = 't' in opts
1162
1233
1163 logger = self.shell.logger
1234 logger = self.shell.logger
1164
1235
1165 # if no args are given, the defaults set in the logger constructor by
1236 # if no args are given, the defaults set in the logger constructor by
1166 # ipython remain valid
1237 # ipython remain valid
1167 if par:
1238 if par:
1168 try:
1239 try:
1169 logfname,logmode = par.split()
1240 logfname,logmode = par.split()
1170 except:
1241 except:
1171 logfname = par
1242 logfname = par
1172 logmode = 'backup'
1243 logmode = 'backup'
1173 else:
1244 else:
1174 logfname = logger.logfname
1245 logfname = logger.logfname
1175 logmode = logger.logmode
1246 logmode = logger.logmode
1176 # put logfname into rc struct as if it had been called on the command
1247 # 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
1248 # line, so it ends up saved in the log header Save it in case we need
1178 # to restore it...
1249 # to restore it...
1179 old_logfile = self.shell.logfile
1250 old_logfile = self.shell.logfile
1180 if logfname:
1251 if logfname:
1181 logfname = os.path.expanduser(logfname)
1252 logfname = os.path.expanduser(logfname)
1182 self.shell.logfile = logfname
1253 self.shell.logfile = logfname
1183
1254
1184 loghead = '# IPython log file\n\n'
1255 loghead = '# IPython log file\n\n'
1185 try:
1256 try:
1186 started = logger.logstart(logfname,loghead,logmode,
1257 started = logger.logstart(logfname,loghead,logmode,
1187 log_output,timestamp,log_raw_input)
1258 log_output,timestamp,log_raw_input)
1188 except:
1259 except:
1189 self.shell.logfile = old_logfile
1260 self.shell.logfile = old_logfile
1190 warn("Couldn't start log: %s" % sys.exc_info()[1])
1261 warn("Couldn't start log: %s" % sys.exc_info()[1])
1191 else:
1262 else:
1192 # log input history up to this point, optionally interleaving
1263 # log input history up to this point, optionally interleaving
1193 # output if requested
1264 # output if requested
1194
1265
1195 if timestamp:
1266 if timestamp:
1196 # disable timestamping for the previous history, since we've
1267 # disable timestamping for the previous history, since we've
1197 # lost those already (no time machine here).
1268 # lost those already (no time machine here).
1198 logger.timestamp = False
1269 logger.timestamp = False
1199
1270
1200 if log_raw_input:
1271 if log_raw_input:
1201 input_hist = self.shell.history_manager.input_hist_raw
1272 input_hist = self.shell.history_manager.input_hist_raw
1202 else:
1273 else:
1203 input_hist = self.shell.history_manager.input_hist_parsed
1274 input_hist = self.shell.history_manager.input_hist_parsed
1204
1275
1205 if log_output:
1276 if log_output:
1206 log_write = logger.log_write
1277 log_write = logger.log_write
1207 output_hist = self.shell.history_manager.output_hist
1278 output_hist = self.shell.history_manager.output_hist
1208 for n in range(1,len(input_hist)-1):
1279 for n in range(1,len(input_hist)-1):
1209 log_write(input_hist[n].rstrip() + '\n')
1280 log_write(input_hist[n].rstrip() + '\n')
1210 if n in output_hist:
1281 if n in output_hist:
1211 log_write(repr(output_hist[n]),'output')
1282 log_write(repr(output_hist[n]),'output')
1212 else:
1283 else:
1213 logger.log_write('\n'.join(input_hist[1:]))
1284 logger.log_write('\n'.join(input_hist[1:]))
1214 logger.log_write('\n')
1285 logger.log_write('\n')
1215 if timestamp:
1286 if timestamp:
1216 # re-enable timestamping
1287 # re-enable timestamping
1217 logger.timestamp = True
1288 logger.timestamp = True
1218
1289
1219 print ('Activating auto-logging. '
1290 print ('Activating auto-logging. '
1220 'Current session state plus future input saved.')
1291 'Current session state plus future input saved.')
1221 logger.logstate()
1292 logger.logstate()
1222
1293
1223 def magic_logstop(self,parameter_s=''):
1294 def magic_logstop(self,parameter_s=''):
1224 """Fully stop logging and close log file.
1295 """Fully stop logging and close log file.
1225
1296
1226 In order to start logging again, a new %logstart call needs to be made,
1297 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
1298 possibly (though not necessarily) with a new filename, mode and other
1228 options."""
1299 options."""
1229 self.logger.logstop()
1300 self.logger.logstop()
1230
1301
1231 def magic_logoff(self,parameter_s=''):
1302 def magic_logoff(self,parameter_s=''):
1232 """Temporarily stop logging.
1303 """Temporarily stop logging.
1233
1304
1234 You must have previously started logging."""
1305 You must have previously started logging."""
1235 self.shell.logger.switch_log(0)
1306 self.shell.logger.switch_log(0)
1236
1307
1237 def magic_logon(self,parameter_s=''):
1308 def magic_logon(self,parameter_s=''):
1238 """Restart logging.
1309 """Restart logging.
1239
1310
1240 This function is for restarting logging which you've temporarily
1311 This function is for restarting logging which you've temporarily
1241 stopped with %logoff. For starting logging for the first time, you
1312 stopped with %logoff. For starting logging for the first time, you
1242 must use the %logstart function, which allows you to specify an
1313 must use the %logstart function, which allows you to specify an
1243 optional log filename."""
1314 optional log filename."""
1244
1315
1245 self.shell.logger.switch_log(1)
1316 self.shell.logger.switch_log(1)
1246
1317
1247 def magic_logstate(self,parameter_s=''):
1318 def magic_logstate(self,parameter_s=''):
1248 """Print the status of the logging system."""
1319 """Print the status of the logging system."""
1249
1320
1250 self.shell.logger.logstate()
1321 self.shell.logger.logstate()
1251
1322
1252 def magic_pdb(self, parameter_s=''):
1323 def magic_pdb(self, parameter_s=''):
1253 """Control the automatic calling of the pdb interactive debugger.
1324 """Control the automatic calling of the pdb interactive debugger.
1254
1325
1255 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1256 argument it works as a toggle.
1327 argument it works as a toggle.
1257
1328
1258 When an exception is triggered, IPython can optionally call the
1329 When an exception is triggered, IPython can optionally call the
1259 interactive pdb debugger after the traceback printout. %pdb toggles
1330 interactive pdb debugger after the traceback printout. %pdb toggles
1260 this feature on and off.
1331 this feature on and off.
1261
1332
1262 The initial state of this feature is set in your configuration
1333 The initial state of this feature is set in your configuration
1263 file (the option is ``InteractiveShell.pdb``).
1334 file (the option is ``InteractiveShell.pdb``).
1264
1335
1265 If you want to just activate the debugger AFTER an exception has fired,
1336 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
1337 without having to type '%pdb on' and rerunning your code, you can use
1267 the %debug magic."""
1338 the %debug magic."""
1268
1339
1269 par = parameter_s.strip().lower()
1340 par = parameter_s.strip().lower()
1270
1341
1271 if par:
1342 if par:
1272 try:
1343 try:
1273 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1274 except KeyError:
1345 except KeyError:
1275 print ('Incorrect argument. Use on/1, off/0, '
1346 print ('Incorrect argument. Use on/1, off/0, '
1276 'or nothing for a toggle.')
1347 'or nothing for a toggle.')
1277 return
1348 return
1278 else:
1349 else:
1279 # toggle
1350 # toggle
1280 new_pdb = not self.shell.call_pdb
1351 new_pdb = not self.shell.call_pdb
1281
1352
1282 # set on the shell
1353 # set on the shell
1283 self.shell.call_pdb = new_pdb
1354 self.shell.call_pdb = new_pdb
1284 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1285
1356
1286 def magic_debug(self, parameter_s=''):
1357 def magic_debug(self, parameter_s=''):
1287 """Activate the interactive debugger in post-mortem mode.
1358 """Activate the interactive debugger in post-mortem mode.
1288
1359
1289 If an exception has just occurred, this lets you inspect its stack
1360 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
1361 frames interactively. Note that this will always work only on the last
1291 traceback that occurred, so you must call this quickly after an
1362 traceback that occurred, so you must call this quickly after an
1292 exception that you wish to inspect has fired, because if another one
1363 exception that you wish to inspect has fired, because if another one
1293 occurs, it clobbers the previous one.
1364 occurs, it clobbers the previous one.
1294
1365
1295 If you want IPython to automatically do this on every exception, see
1366 If you want IPython to automatically do this on every exception, see
1296 the %pdb magic for more details.
1367 the %pdb magic for more details.
1297 """
1368 """
1298 self.shell.debugger(force=True)
1369 self.shell.debugger(force=True)
1299
1370
1300 @skip_doctest
1371 @skip_doctest
1301 def magic_prun(self, parameter_s ='',user_mode=1,
1372 def magic_prun(self, parameter_s ='',user_mode=1,
1302 opts=None,arg_lst=None,prog_ns=None):
1373 opts=None,arg_lst=None,prog_ns=None):
1303
1374
1304 """Run a statement through the python code profiler.
1375 """Run a statement through the python code profiler.
1305
1376
1306 Usage:
1377 Usage:
1307 %prun [options] statement
1378 %prun [options] statement
1308
1379
1309 The given statement (which doesn't require quote marks) is run via the
1380 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.
1381 python profiler in a manner similar to the profile.run() function.
1311 Namespaces are internally managed to work correctly; profile.run
1382 Namespaces are internally managed to work correctly; profile.run
1312 cannot be used in IPython because it makes certain assumptions about
1383 cannot be used in IPython because it makes certain assumptions about
1313 namespaces which do not hold under IPython.
1384 namespaces which do not hold under IPython.
1314
1385
1315 Options:
1386 Options:
1316
1387
1317 -l <limit>: you can place restrictions on what or how much of the
1388 -l <limit>: you can place restrictions on what or how much of the
1318 profile gets printed. The limit value can be:
1389 profile gets printed. The limit value can be:
1319
1390
1320 * A string: only information for function names containing this string
1391 * A string: only information for function names containing this string
1321 is printed.
1392 is printed.
1322
1393
1323 * An integer: only these many lines are printed.
1394 * An integer: only these many lines are printed.
1324
1395
1325 * A float (between 0 and 1): this fraction of the report is printed
1396 * 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).
1397 (for example, use a limit of 0.4 to see the topmost 40% only).
1327
1398
1328 You can combine several limits with repeated use of the option. For
1399 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
1400 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1330 information about class constructors.
1401 information about class constructors.
1331
1402
1332 -r: return the pstats.Stats object generated by the profiling. This
1403 -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
1404 object has all the information about the profile in it, and you can
1334 later use it for further analysis or in other functions.
1405 later use it for further analysis or in other functions.
1335
1406
1336 -s <key>: sort profile by given key. You can provide more than one key
1407 -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
1408 by using the option several times: '-s key1 -s key2 -s key3...'. The
1338 default sorting key is 'time'.
1409 default sorting key is 'time'.
1339
1410
1340 The following is copied verbatim from the profile documentation
1411 The following is copied verbatim from the profile documentation
1341 referenced below:
1412 referenced below:
1342
1413
1343 When more than one key is provided, additional keys are used as
1414 When more than one key is provided, additional keys are used as
1344 secondary criteria when the there is equality in all keys selected
1415 secondary criteria when the there is equality in all keys selected
1345 before them.
1416 before them.
1346
1417
1347 Abbreviations can be used for any key names, as long as the
1418 Abbreviations can be used for any key names, as long as the
1348 abbreviation is unambiguous. The following are the keys currently
1419 abbreviation is unambiguous. The following are the keys currently
1349 defined:
1420 defined:
1350
1421
1351 Valid Arg Meaning
1422 Valid Arg Meaning
1352 "calls" call count
1423 "calls" call count
1353 "cumulative" cumulative time
1424 "cumulative" cumulative time
1354 "file" file name
1425 "file" file name
1355 "module" file name
1426 "module" file name
1356 "pcalls" primitive call count
1427 "pcalls" primitive call count
1357 "line" line number
1428 "line" line number
1358 "name" function name
1429 "name" function name
1359 "nfl" name/file/line
1430 "nfl" name/file/line
1360 "stdname" standard name
1431 "stdname" standard name
1361 "time" internal time
1432 "time" internal time
1362
1433
1363 Note that all sorts on statistics are in descending order (placing
1434 Note that all sorts on statistics are in descending order (placing
1364 most time consuming items first), where as name, file, and line number
1435 most time consuming items first), where as name, file, and line number
1365 searches are in ascending order (i.e., alphabetical). The subtle
1436 searches are in ascending order (i.e., alphabetical). The subtle
1366 distinction between "nfl" and "stdname" is that the standard name is a
1437 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
1438 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
1439 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
1440 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
1441 "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
1442 line numbers. In fact, sort_stats("nfl") is the same as
1372 sort_stats("name", "file", "line").
1443 sort_stats("name", "file", "line").
1373
1444
1374 -T <filename>: save profile results as shown on screen to a text
1445 -T <filename>: save profile results as shown on screen to a text
1375 file. The profile is still shown on screen.
1446 file. The profile is still shown on screen.
1376
1447
1377 -D <filename>: save (via dump_stats) profile statistics to given
1448 -D <filename>: save (via dump_stats) profile statistics to given
1378 filename. This data is in a format understood by the pstats module, and
1449 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
1450 is generated by a call to the dump_stats() method of profile
1380 objects. The profile is still shown on screen.
1451 objects. The profile is still shown on screen.
1381
1452
1382 -q: suppress output to the pager. Best used with -T and/or -D above.
1453 -q: suppress output to the pager. Best used with -T and/or -D above.
1383
1454
1384 If you want to run complete programs under the profiler's control, use
1455 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
1456 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1386 contains profiler specific options as described here.
1457 contains profiler specific options as described here.
1387
1458
1388 You can read the complete documentation for the profile module with::
1459 You can read the complete documentation for the profile module with::
1389
1460
1390 In [1]: import profile; profile.help()
1461 In [1]: import profile; profile.help()
1391 """
1462 """
1392
1463
1393 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1464 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1394
1465
1395 if user_mode: # regular user call
1466 if user_mode: # regular user call
1396 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1467 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1397 list_all=1, posix=False)
1468 list_all=1, posix=False)
1398 namespace = self.shell.user_ns
1469 namespace = self.shell.user_ns
1399 else: # called to run a program by %run -p
1470 else: # called to run a program by %run -p
1400 try:
1471 try:
1401 filename = get_py_filename(arg_lst[0])
1472 filename = get_py_filename(arg_lst[0])
1402 except IOError as e:
1473 except IOError as e:
1403 try:
1474 try:
1404 msg = str(e)
1475 msg = str(e)
1405 except UnicodeError:
1476 except UnicodeError:
1406 msg = e.message
1477 msg = e.message
1407 error(msg)
1478 error(msg)
1408 return
1479 return
1409
1480
1410 arg_str = 'execfile(filename,prog_ns)'
1481 arg_str = 'execfile(filename,prog_ns)'
1411 namespace = {
1482 namespace = {
1412 'execfile': self.shell.safe_execfile,
1483 'execfile': self.shell.safe_execfile,
1413 'prog_ns': prog_ns,
1484 'prog_ns': prog_ns,
1414 'filename': filename
1485 'filename': filename
1415 }
1486 }
1416
1487
1417 opts.merge(opts_def)
1488 opts.merge(opts_def)
1418
1489
1419 prof = profile.Profile()
1490 prof = profile.Profile()
1420 try:
1491 try:
1421 prof = prof.runctx(arg_str,namespace,namespace)
1492 prof = prof.runctx(arg_str,namespace,namespace)
1422 sys_exit = ''
1493 sys_exit = ''
1423 except SystemExit:
1494 except SystemExit:
1424 sys_exit = """*** SystemExit exception caught in code being profiled."""
1495 sys_exit = """*** SystemExit exception caught in code being profiled."""
1425
1496
1426 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1497 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1427
1498
1428 lims = opts.l
1499 lims = opts.l
1429 if lims:
1500 if lims:
1430 lims = [] # rebuild lims with ints/floats/strings
1501 lims = [] # rebuild lims with ints/floats/strings
1431 for lim in opts.l:
1502 for lim in opts.l:
1432 try:
1503 try:
1433 lims.append(int(lim))
1504 lims.append(int(lim))
1434 except ValueError:
1505 except ValueError:
1435 try:
1506 try:
1436 lims.append(float(lim))
1507 lims.append(float(lim))
1437 except ValueError:
1508 except ValueError:
1438 lims.append(lim)
1509 lims.append(lim)
1439
1510
1440 # Trap output.
1511 # Trap output.
1441 stdout_trap = StringIO()
1512 stdout_trap = StringIO()
1442
1513
1443 if hasattr(stats,'stream'):
1514 if hasattr(stats,'stream'):
1444 # In newer versions of python, the stats object has a 'stream'
1515 # In newer versions of python, the stats object has a 'stream'
1445 # attribute to write into.
1516 # attribute to write into.
1446 stats.stream = stdout_trap
1517 stats.stream = stdout_trap
1447 stats.print_stats(*lims)
1518 stats.print_stats(*lims)
1448 else:
1519 else:
1449 # For older versions, we manually redirect stdout during printing
1520 # For older versions, we manually redirect stdout during printing
1450 sys_stdout = sys.stdout
1521 sys_stdout = sys.stdout
1451 try:
1522 try:
1452 sys.stdout = stdout_trap
1523 sys.stdout = stdout_trap
1453 stats.print_stats(*lims)
1524 stats.print_stats(*lims)
1454 finally:
1525 finally:
1455 sys.stdout = sys_stdout
1526 sys.stdout = sys_stdout
1456
1527
1457 output = stdout_trap.getvalue()
1528 output = stdout_trap.getvalue()
1458 output = output.rstrip()
1529 output = output.rstrip()
1459
1530
1460 if 'q' not in opts:
1531 if 'q' not in opts:
1461 page.page(output)
1532 page.page(output)
1462 print sys_exit,
1533 print sys_exit,
1463
1534
1464 dump_file = opts.D[0]
1535 dump_file = opts.D[0]
1465 text_file = opts.T[0]
1536 text_file = opts.T[0]
1466 if dump_file:
1537 if dump_file:
1467 dump_file = unquote_filename(dump_file)
1538 dump_file = unquote_filename(dump_file)
1468 prof.dump_stats(dump_file)
1539 prof.dump_stats(dump_file)
1469 print '\n*** Profile stats marshalled to file',\
1540 print '\n*** Profile stats marshalled to file',\
1470 `dump_file`+'.',sys_exit
1541 `dump_file`+'.',sys_exit
1471 if text_file:
1542 if text_file:
1472 text_file = unquote_filename(text_file)
1543 text_file = unquote_filename(text_file)
1473 pfile = file(text_file,'w')
1544 pfile = file(text_file,'w')
1474 pfile.write(output)
1545 pfile.write(output)
1475 pfile.close()
1546 pfile.close()
1476 print '\n*** Profile printout saved to text file',\
1547 print '\n*** Profile printout saved to text file',\
1477 `text_file`+'.',sys_exit
1548 `text_file`+'.',sys_exit
1478
1549
1479 if opts.has_key('r'):
1550 if opts.has_key('r'):
1480 return stats
1551 return stats
1481 else:
1552 else:
1482 return None
1553 return None
1483
1554
1484 @skip_doctest
1555 @skip_doctest
1485 def magic_run(self, parameter_s ='', runner=None,
1556 def magic_run(self, parameter_s ='', runner=None,
1486 file_finder=get_py_filename):
1557 file_finder=get_py_filename):
1487 """Run the named file inside IPython as a program.
1558 """Run the named file inside IPython as a program.
1488
1559
1489 Usage:\\
1560 Usage:\\
1490 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1561 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1491
1562
1492 Parameters after the filename are passed as command-line arguments to
1563 Parameters after the filename are passed as command-line arguments to
1493 the program (put in sys.argv). Then, control returns to IPython's
1564 the program (put in sys.argv). Then, control returns to IPython's
1494 prompt.
1565 prompt.
1495
1566
1496 This is similar to running at a system prompt:\\
1567 This is similar to running at a system prompt:\\
1497 $ python file args\\
1568 $ python file args\\
1498 but with the advantage of giving you IPython's tracebacks, and of
1569 but with the advantage of giving you IPython's tracebacks, and of
1499 loading all variables into your interactive namespace for further use
1570 loading all variables into your interactive namespace for further use
1500 (unless -p is used, see below).
1571 (unless -p is used, see below).
1501
1572
1502 The file is executed in a namespace initially consisting only of
1573 The file is executed in a namespace initially consisting only of
1503 __name__=='__main__' and sys.argv constructed as indicated. It thus
1574 __name__=='__main__' and sys.argv constructed as indicated. It thus
1504 sees its environment as if it were being run as a stand-alone program
1575 sees its environment as if it were being run as a stand-alone program
1505 (except for sharing global objects such as previously imported
1576 (except for sharing global objects such as previously imported
1506 modules). But after execution, the IPython interactive namespace gets
1577 modules). But after execution, the IPython interactive namespace gets
1507 updated with all variables defined in the program (except for __name__
1578 updated with all variables defined in the program (except for __name__
1508 and sys.argv). This allows for very convenient loading of code for
1579 and sys.argv). This allows for very convenient loading of code for
1509 interactive work, while giving each program a 'clean sheet' to run in.
1580 interactive work, while giving each program a 'clean sheet' to run in.
1510
1581
1511 Options:
1582 Options:
1512
1583
1513 -n: __name__ is NOT set to '__main__', but to the running file's name
1584 -n: __name__ is NOT set to '__main__', but to the running file's name
1514 without extension (as python does under import). This allows running
1585 without extension (as python does under import). This allows running
1515 scripts and reloading the definitions in them without calling code
1586 scripts and reloading the definitions in them without calling code
1516 protected by an ' if __name__ == "__main__" ' clause.
1587 protected by an ' if __name__ == "__main__" ' clause.
1517
1588
1518 -i: run the file in IPython's namespace instead of an empty one. This
1589 -i: run the file in IPython's namespace instead of an empty one. This
1519 is useful if you are experimenting with code written in a text editor
1590 is useful if you are experimenting with code written in a text editor
1520 which depends on variables defined interactively.
1591 which depends on variables defined interactively.
1521
1592
1522 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1593 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1523 being run. This is particularly useful if IPython is being used to
1594 being run. This is particularly useful if IPython is being used to
1524 run unittests, which always exit with a sys.exit() call. In such
1595 run unittests, which always exit with a sys.exit() call. In such
1525 cases you are interested in the output of the test results, not in
1596 cases you are interested in the output of the test results, not in
1526 seeing a traceback of the unittest module.
1597 seeing a traceback of the unittest module.
1527
1598
1528 -t: print timing information at the end of the run. IPython will give
1599 -t: print timing information at the end of the run. IPython will give
1529 you an estimated CPU time consumption for your script, which under
1600 you an estimated CPU time consumption for your script, which under
1530 Unix uses the resource module to avoid the wraparound problems of
1601 Unix uses the resource module to avoid the wraparound problems of
1531 time.clock(). Under Unix, an estimate of time spent on system tasks
1602 time.clock(). Under Unix, an estimate of time spent on system tasks
1532 is also given (for Windows platforms this is reported as 0.0).
1603 is also given (for Windows platforms this is reported as 0.0).
1533
1604
1534 If -t is given, an additional -N<N> option can be given, where <N>
1605 If -t is given, an additional -N<N> option can be given, where <N>
1535 must be an integer indicating how many times you want the script to
1606 must be an integer indicating how many times you want the script to
1536 run. The final timing report will include total and per run results.
1607 run. The final timing report will include total and per run results.
1537
1608
1538 For example (testing the script uniq_stable.py):
1609 For example (testing the script uniq_stable.py):
1539
1610
1540 In [1]: run -t uniq_stable
1611 In [1]: run -t uniq_stable
1541
1612
1542 IPython CPU timings (estimated):\\
1613 IPython CPU timings (estimated):\\
1543 User : 0.19597 s.\\
1614 User : 0.19597 s.\\
1544 System: 0.0 s.\\
1615 System: 0.0 s.\\
1545
1616
1546 In [2]: run -t -N5 uniq_stable
1617 In [2]: run -t -N5 uniq_stable
1547
1618
1548 IPython CPU timings (estimated):\\
1619 IPython CPU timings (estimated):\\
1549 Total runs performed: 5\\
1620 Total runs performed: 5\\
1550 Times : Total Per run\\
1621 Times : Total Per run\\
1551 User : 0.910862 s, 0.1821724 s.\\
1622 User : 0.910862 s, 0.1821724 s.\\
1552 System: 0.0 s, 0.0 s.
1623 System: 0.0 s, 0.0 s.
1553
1624
1554 -d: run your program under the control of pdb, the Python debugger.
1625 -d: run your program under the control of pdb, the Python debugger.
1555 This allows you to execute your program step by step, watch variables,
1626 This allows you to execute your program step by step, watch variables,
1556 etc. Internally, what IPython does is similar to calling:
1627 etc. Internally, what IPython does is similar to calling:
1557
1628
1558 pdb.run('execfile("YOURFILENAME")')
1629 pdb.run('execfile("YOURFILENAME")')
1559
1630
1560 with a breakpoint set on line 1 of your file. You can change the line
1631 with a breakpoint set on line 1 of your file. You can change the line
1561 number for this automatic breakpoint to be <N> by using the -bN option
1632 number for this automatic breakpoint to be <N> by using the -bN option
1562 (where N must be an integer). For example:
1633 (where N must be an integer). For example:
1563
1634
1564 %run -d -b40 myscript
1635 %run -d -b40 myscript
1565
1636
1566 will set the first breakpoint at line 40 in myscript.py. Note that
1637 will set the first breakpoint at line 40 in myscript.py. Note that
1567 the first breakpoint must be set on a line which actually does
1638 the first breakpoint must be set on a line which actually does
1568 something (not a comment or docstring) for it to stop execution.
1639 something (not a comment or docstring) for it to stop execution.
1569
1640
1570 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1641 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1571 first enter 'c' (without quotes) to start execution up to the first
1642 first enter 'c' (without quotes) to start execution up to the first
1572 breakpoint.
1643 breakpoint.
1573
1644
1574 Entering 'help' gives information about the use of the debugger. You
1645 Entering 'help' gives information about the use of the debugger. You
1575 can easily see pdb's full documentation with "import pdb;pdb.help()"
1646 can easily see pdb's full documentation with "import pdb;pdb.help()"
1576 at a prompt.
1647 at a prompt.
1577
1648
1578 -p: run program under the control of the Python profiler module (which
1649 -p: run program under the control of the Python profiler module (which
1579 prints a detailed report of execution times, function calls, etc).
1650 prints a detailed report of execution times, function calls, etc).
1580
1651
1581 You can pass other options after -p which affect the behavior of the
1652 You can pass other options after -p which affect the behavior of the
1582 profiler itself. See the docs for %prun for details.
1653 profiler itself. See the docs for %prun for details.
1583
1654
1584 In this mode, the program's variables do NOT propagate back to the
1655 In this mode, the program's variables do NOT propagate back to the
1585 IPython interactive namespace (because they remain in the namespace
1656 IPython interactive namespace (because they remain in the namespace
1586 where the profiler executes them).
1657 where the profiler executes them).
1587
1658
1588 Internally this triggers a call to %prun, see its documentation for
1659 Internally this triggers a call to %prun, see its documentation for
1589 details on the options available specifically for profiling.
1660 details on the options available specifically for profiling.
1590
1661
1591 There is one special usage for which the text above doesn't apply:
1662 There is one special usage for which the text above doesn't apply:
1592 if the filename ends with .ipy, the file is run as ipython script,
1663 if the filename ends with .ipy, the file is run as ipython script,
1593 just as if the commands were written on IPython prompt.
1664 just as if the commands were written on IPython prompt.
1594
1665
1595 -m: specify module name to load instead of script path. Similar to
1666 -m: specify module name to load instead of script path. Similar to
1596 the -m option for the python interpreter. Use this option last if you
1667 the -m option for the python interpreter. Use this option last if you
1597 want to combine with other %run options. Unlike the python interpreter
1668 want to combine with other %run options. Unlike the python interpreter
1598 only source modules are allowed no .pyc or .pyo files.
1669 only source modules are allowed no .pyc or .pyo files.
1599 For example:
1670 For example:
1600
1671
1601 %run -m example
1672 %run -m example
1602
1673
1603 will run the example module.
1674 will run the example module.
1604
1675
1605 """
1676 """
1606
1677
1607 # get arguments and set sys.argv for program to be run.
1678 # get arguments and set sys.argv for program to be run.
1608 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1679 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1609 mode='list', list_all=1)
1680 mode='list', list_all=1)
1610 if "m" in opts:
1681 if "m" in opts:
1611 modulename = opts["m"][0]
1682 modulename = opts["m"][0]
1612 modpath = find_mod(modulename)
1683 modpath = find_mod(modulename)
1613 if modpath is None:
1684 if modpath is None:
1614 warn('%r is not a valid modulename on sys.path'%modulename)
1685 warn('%r is not a valid modulename on sys.path'%modulename)
1615 return
1686 return
1616 arg_lst = [modpath] + arg_lst
1687 arg_lst = [modpath] + arg_lst
1617 try:
1688 try:
1618 filename = file_finder(arg_lst[0])
1689 filename = file_finder(arg_lst[0])
1619 except IndexError:
1690 except IndexError:
1620 warn('you must provide at least a filename.')
1691 warn('you must provide at least a filename.')
1621 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1692 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1622 return
1693 return
1623 except IOError as e:
1694 except IOError as e:
1624 try:
1695 try:
1625 msg = str(e)
1696 msg = str(e)
1626 except UnicodeError:
1697 except UnicodeError:
1627 msg = e.message
1698 msg = e.message
1628 error(msg)
1699 error(msg)
1629 return
1700 return
1630
1701
1631 if filename.lower().endswith('.ipy'):
1702 if filename.lower().endswith('.ipy'):
1632 self.shell.safe_execfile_ipy(filename)
1703 self.shell.safe_execfile_ipy(filename)
1633 return
1704 return
1634
1705
1635 # Control the response to exit() calls made by the script being run
1706 # Control the response to exit() calls made by the script being run
1636 exit_ignore = 'e' in opts
1707 exit_ignore = 'e' in opts
1637
1708
1638 # Make sure that the running script gets a proper sys.argv as if it
1709 # Make sure that the running script gets a proper sys.argv as if it
1639 # were run from a system shell.
1710 # were run from a system shell.
1640 save_argv = sys.argv # save it for later restoring
1711 save_argv = sys.argv # save it for later restoring
1641
1712
1642 # simulate shell expansion on arguments, at least tilde expansion
1713 # simulate shell expansion on arguments, at least tilde expansion
1643 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1714 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1644
1715
1645 sys.argv = [filename] + args # put in the proper filename
1716 sys.argv = [filename] + args # put in the proper filename
1646 # protect sys.argv from potential unicode strings on Python 2:
1717 # protect sys.argv from potential unicode strings on Python 2:
1647 if not py3compat.PY3:
1718 if not py3compat.PY3:
1648 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1719 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1649
1720
1650 if 'i' in opts:
1721 if 'i' in opts:
1651 # Run in user's interactive namespace
1722 # Run in user's interactive namespace
1652 prog_ns = self.shell.user_ns
1723 prog_ns = self.shell.user_ns
1653 __name__save = self.shell.user_ns['__name__']
1724 __name__save = self.shell.user_ns['__name__']
1654 prog_ns['__name__'] = '__main__'
1725 prog_ns['__name__'] = '__main__'
1655 main_mod = self.shell.new_main_mod(prog_ns)
1726 main_mod = self.shell.new_main_mod(prog_ns)
1656 else:
1727 else:
1657 # Run in a fresh, empty namespace
1728 # Run in a fresh, empty namespace
1658 if 'n' in opts:
1729 if 'n' in opts:
1659 name = os.path.splitext(os.path.basename(filename))[0]
1730 name = os.path.splitext(os.path.basename(filename))[0]
1660 else:
1731 else:
1661 name = '__main__'
1732 name = '__main__'
1662
1733
1663 main_mod = self.shell.new_main_mod()
1734 main_mod = self.shell.new_main_mod()
1664 prog_ns = main_mod.__dict__
1735 prog_ns = main_mod.__dict__
1665 prog_ns['__name__'] = name
1736 prog_ns['__name__'] = name
1666
1737
1667 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1738 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1668 # set the __file__ global in the script's namespace
1739 # set the __file__ global in the script's namespace
1669 prog_ns['__file__'] = filename
1740 prog_ns['__file__'] = filename
1670
1741
1671 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1742 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1672 # that, if we overwrite __main__, we replace it at the end
1743 # that, if we overwrite __main__, we replace it at the end
1673 main_mod_name = prog_ns['__name__']
1744 main_mod_name = prog_ns['__name__']
1674
1745
1675 if main_mod_name == '__main__':
1746 if main_mod_name == '__main__':
1676 restore_main = sys.modules['__main__']
1747 restore_main = sys.modules['__main__']
1677 else:
1748 else:
1678 restore_main = False
1749 restore_main = False
1679
1750
1680 # This needs to be undone at the end to prevent holding references to
1751 # This needs to be undone at the end to prevent holding references to
1681 # every single object ever created.
1752 # every single object ever created.
1682 sys.modules[main_mod_name] = main_mod
1753 sys.modules[main_mod_name] = main_mod
1683
1754
1684 try:
1755 try:
1685 stats = None
1756 stats = None
1686 with self.readline_no_record:
1757 with self.readline_no_record:
1687 if 'p' in opts:
1758 if 'p' in opts:
1688 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1759 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1689 else:
1760 else:
1690 if 'd' in opts:
1761 if 'd' in opts:
1691 deb = debugger.Pdb(self.shell.colors)
1762 deb = debugger.Pdb(self.shell.colors)
1692 # reset Breakpoint state, which is moronically kept
1763 # reset Breakpoint state, which is moronically kept
1693 # in a class
1764 # in a class
1694 bdb.Breakpoint.next = 1
1765 bdb.Breakpoint.next = 1
1695 bdb.Breakpoint.bplist = {}
1766 bdb.Breakpoint.bplist = {}
1696 bdb.Breakpoint.bpbynumber = [None]
1767 bdb.Breakpoint.bpbynumber = [None]
1697 # Set an initial breakpoint to stop execution
1768 # Set an initial breakpoint to stop execution
1698 maxtries = 10
1769 maxtries = 10
1699 bp = int(opts.get('b', [1])[0])
1770 bp = int(opts.get('b', [1])[0])
1700 checkline = deb.checkline(filename, bp)
1771 checkline = deb.checkline(filename, bp)
1701 if not checkline:
1772 if not checkline:
1702 for bp in range(bp + 1, bp + maxtries + 1):
1773 for bp in range(bp + 1, bp + maxtries + 1):
1703 if deb.checkline(filename, bp):
1774 if deb.checkline(filename, bp):
1704 break
1775 break
1705 else:
1776 else:
1706 msg = ("\nI failed to find a valid line to set "
1777 msg = ("\nI failed to find a valid line to set "
1707 "a breakpoint\n"
1778 "a breakpoint\n"
1708 "after trying up to line: %s.\n"
1779 "after trying up to line: %s.\n"
1709 "Please set a valid breakpoint manually "
1780 "Please set a valid breakpoint manually "
1710 "with the -b option." % bp)
1781 "with the -b option." % bp)
1711 error(msg)
1782 error(msg)
1712 return
1783 return
1713 # if we find a good linenumber, set the breakpoint
1784 # if we find a good linenumber, set the breakpoint
1714 deb.do_break('%s:%s' % (filename, bp))
1785 deb.do_break('%s:%s' % (filename, bp))
1715 # Start file run
1786 # Start file run
1716 print "NOTE: Enter 'c' at the",
1787 print "NOTE: Enter 'c' at the",
1717 print "%s prompt to start your script." % deb.prompt
1788 print "%s prompt to start your script." % deb.prompt
1718 try:
1789 try:
1719 deb.run('execfile("%s")' % filename, prog_ns)
1790 deb.run('execfile("%s")' % filename, prog_ns)
1720
1791
1721 except:
1792 except:
1722 etype, value, tb = sys.exc_info()
1793 etype, value, tb = sys.exc_info()
1723 # Skip three frames in the traceback: the %run one,
1794 # Skip three frames in the traceback: the %run one,
1724 # one inside bdb.py, and the command-line typed by the
1795 # one inside bdb.py, and the command-line typed by the
1725 # user (run by exec in pdb itself).
1796 # user (run by exec in pdb itself).
1726 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1797 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1727 else:
1798 else:
1728 if runner is None:
1799 if runner is None:
1729 runner = self.shell.safe_execfile
1800 runner = self.shell.safe_execfile
1730 if 't' in opts:
1801 if 't' in opts:
1731 # timed execution
1802 # timed execution
1732 try:
1803 try:
1733 nruns = int(opts['N'][0])
1804 nruns = int(opts['N'][0])
1734 if nruns < 1:
1805 if nruns < 1:
1735 error('Number of runs must be >=1')
1806 error('Number of runs must be >=1')
1736 return
1807 return
1737 except (KeyError):
1808 except (KeyError):
1738 nruns = 1
1809 nruns = 1
1739 twall0 = time.time()
1810 twall0 = time.time()
1740 if nruns == 1:
1811 if nruns == 1:
1741 t0 = clock2()
1812 t0 = clock2()
1742 runner(filename, prog_ns, prog_ns,
1813 runner(filename, prog_ns, prog_ns,
1743 exit_ignore=exit_ignore)
1814 exit_ignore=exit_ignore)
1744 t1 = clock2()
1815 t1 = clock2()
1745 t_usr = t1[0] - t0[0]
1816 t_usr = t1[0] - t0[0]
1746 t_sys = t1[1] - t0[1]
1817 t_sys = t1[1] - t0[1]
1747 print "\nIPython CPU timings (estimated):"
1818 print "\nIPython CPU timings (estimated):"
1748 print " User : %10.2f s." % t_usr
1819 print " User : %10.2f s." % t_usr
1749 print " System : %10.2f s." % t_sys
1820 print " System : %10.2f s." % t_sys
1750 else:
1821 else:
1751 runs = range(nruns)
1822 runs = range(nruns)
1752 t0 = clock2()
1823 t0 = clock2()
1753 for nr in runs:
1824 for nr in runs:
1754 runner(filename, prog_ns, prog_ns,
1825 runner(filename, prog_ns, prog_ns,
1755 exit_ignore=exit_ignore)
1826 exit_ignore=exit_ignore)
1756 t1 = clock2()
1827 t1 = clock2()
1757 t_usr = t1[0] - t0[0]
1828 t_usr = t1[0] - t0[0]
1758 t_sys = t1[1] - t0[1]
1829 t_sys = t1[1] - t0[1]
1759 print "\nIPython CPU timings (estimated):"
1830 print "\nIPython CPU timings (estimated):"
1760 print "Total runs performed:", nruns
1831 print "Total runs performed:", nruns
1761 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1832 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1762 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1833 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1763 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1834 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1764 twall1 = time.time()
1835 twall1 = time.time()
1765 print "Wall time: %10.2f s." % (twall1 - twall0)
1836 print "Wall time: %10.2f s." % (twall1 - twall0)
1766
1837
1767 else:
1838 else:
1768 # regular execution
1839 # regular execution
1769 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1840 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1770
1841
1771 if 'i' in opts:
1842 if 'i' in opts:
1772 self.shell.user_ns['__name__'] = __name__save
1843 self.shell.user_ns['__name__'] = __name__save
1773 else:
1844 else:
1774 # The shell MUST hold a reference to prog_ns so after %run
1845 # The shell MUST hold a reference to prog_ns so after %run
1775 # exits, the python deletion mechanism doesn't zero it out
1846 # exits, the python deletion mechanism doesn't zero it out
1776 # (leaving dangling references).
1847 # (leaving dangling references).
1777 self.shell.cache_main_mod(prog_ns, filename)
1848 self.shell.cache_main_mod(prog_ns, filename)
1778 # update IPython interactive namespace
1849 # update IPython interactive namespace
1779
1850
1780 # Some forms of read errors on the file may mean the
1851 # Some forms of read errors on the file may mean the
1781 # __name__ key was never set; using pop we don't have to
1852 # __name__ key was never set; using pop we don't have to
1782 # worry about a possible KeyError.
1853 # worry about a possible KeyError.
1783 prog_ns.pop('__name__', None)
1854 prog_ns.pop('__name__', None)
1784
1855
1785 self.shell.user_ns.update(prog_ns)
1856 self.shell.user_ns.update(prog_ns)
1786 finally:
1857 finally:
1787 # It's a bit of a mystery why, but __builtins__ can change from
1858 # It's a bit of a mystery why, but __builtins__ can change from
1788 # being a module to becoming a dict missing some key data after
1859 # being a module to becoming a dict missing some key data after
1789 # %run. As best I can see, this is NOT something IPython is doing
1860 # %run. As best I can see, this is NOT something IPython is doing
1790 # at all, and similar problems have been reported before:
1861 # at all, and similar problems have been reported before:
1791 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1862 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1792 # Since this seems to be done by the interpreter itself, the best
1863 # Since this seems to be done by the interpreter itself, the best
1793 # we can do is to at least restore __builtins__ for the user on
1864 # we can do is to at least restore __builtins__ for the user on
1794 # exit.
1865 # exit.
1795 self.shell.user_ns['__builtins__'] = builtin_mod
1866 self.shell.user_ns['__builtins__'] = builtin_mod
1796
1867
1797 # Ensure key global structures are restored
1868 # Ensure key global structures are restored
1798 sys.argv = save_argv
1869 sys.argv = save_argv
1799 if restore_main:
1870 if restore_main:
1800 sys.modules['__main__'] = restore_main
1871 sys.modules['__main__'] = restore_main
1801 else:
1872 else:
1802 # Remove from sys.modules the reference to main_mod we'd
1873 # Remove from sys.modules the reference to main_mod we'd
1803 # added. Otherwise it will trap references to objects
1874 # added. Otherwise it will trap references to objects
1804 # contained therein.
1875 # contained therein.
1805 del sys.modules[main_mod_name]
1876 del sys.modules[main_mod_name]
1806
1877
1807 return stats
1878 return stats
1808
1879
1809 @skip_doctest
1880 @skip_doctest
1810 def magic_timeit(self, parameter_s =''):
1881 def magic_timeit(self, parameter_s =''):
1811 """Time execution of a Python statement or expression
1882 """Time execution of a Python statement or expression
1812
1883
1813 Usage:\\
1884 Usage:\\
1814 %timeit [-n<N> -r<R> [-t|-c]] statement
1885 %timeit [-n<N> -r<R> [-t|-c]] statement
1815
1886
1816 Time execution of a Python statement or expression using the timeit
1887 Time execution of a Python statement or expression using the timeit
1817 module.
1888 module.
1818
1889
1819 Options:
1890 Options:
1820 -n<N>: execute the given statement <N> times in a loop. If this value
1891 -n<N>: execute the given statement <N> times in a loop. If this value
1821 is not given, a fitting value is chosen.
1892 is not given, a fitting value is chosen.
1822
1893
1823 -r<R>: repeat the loop iteration <R> times and take the best result.
1894 -r<R>: repeat the loop iteration <R> times and take the best result.
1824 Default: 3
1895 Default: 3
1825
1896
1826 -t: use time.time to measure the time, which is the default on Unix.
1897 -t: use time.time to measure the time, which is the default on Unix.
1827 This function measures wall time.
1898 This function measures wall time.
1828
1899
1829 -c: use time.clock to measure the time, which is the default on
1900 -c: use time.clock to measure the time, which is the default on
1830 Windows and measures wall time. On Unix, resource.getrusage is used
1901 Windows and measures wall time. On Unix, resource.getrusage is used
1831 instead and returns the CPU user time.
1902 instead and returns the CPU user time.
1832
1903
1833 -p<P>: use a precision of <P> digits to display the timing result.
1904 -p<P>: use a precision of <P> digits to display the timing result.
1834 Default: 3
1905 Default: 3
1835
1906
1836
1907
1837 Examples:
1908 Examples:
1838
1909
1839 In [1]: %timeit pass
1910 In [1]: %timeit pass
1840 10000000 loops, best of 3: 53.3 ns per loop
1911 10000000 loops, best of 3: 53.3 ns per loop
1841
1912
1842 In [2]: u = None
1913 In [2]: u = None
1843
1914
1844 In [3]: %timeit u is None
1915 In [3]: %timeit u is None
1845 10000000 loops, best of 3: 184 ns per loop
1916 10000000 loops, best of 3: 184 ns per loop
1846
1917
1847 In [4]: %timeit -r 4 u == None
1918 In [4]: %timeit -r 4 u == None
1848 1000000 loops, best of 4: 242 ns per loop
1919 1000000 loops, best of 4: 242 ns per loop
1849
1920
1850 In [5]: import time
1921 In [5]: import time
1851
1922
1852 In [6]: %timeit -n1 time.sleep(2)
1923 In [6]: %timeit -n1 time.sleep(2)
1853 1 loops, best of 3: 2 s per loop
1924 1 loops, best of 3: 2 s per loop
1854
1925
1855
1926
1856 The times reported by %timeit will be slightly higher than those
1927 The times reported by %timeit will be slightly higher than those
1857 reported by the timeit.py script when variables are accessed. This is
1928 reported by the timeit.py script when variables are accessed. This is
1858 due to the fact that %timeit executes the statement in the namespace
1929 due to the fact that %timeit executes the statement in the namespace
1859 of the shell, compared with timeit.py, which uses a single setup
1930 of the shell, compared with timeit.py, which uses a single setup
1860 statement to import function or create variables. Generally, the bias
1931 statement to import function or create variables. Generally, the bias
1861 does not matter as long as results from timeit.py are not mixed with
1932 does not matter as long as results from timeit.py are not mixed with
1862 those from %timeit."""
1933 those from %timeit."""
1863
1934
1864 import timeit
1935 import timeit
1865 import math
1936 import math
1866
1937
1867 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1938 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1868 # certain terminals. Until we figure out a robust way of
1939 # certain terminals. Until we figure out a robust way of
1869 # auto-detecting if the terminal can deal with it, use plain 'us' for
1940 # auto-detecting if the terminal can deal with it, use plain 'us' for
1870 # microseconds. I am really NOT happy about disabling the proper
1941 # microseconds. I am really NOT happy about disabling the proper
1871 # 'micro' prefix, but crashing is worse... If anyone knows what the
1942 # 'micro' prefix, but crashing is worse... If anyone knows what the
1872 # right solution for this is, I'm all ears...
1943 # right solution for this is, I'm all ears...
1873 #
1944 #
1874 # Note: using
1945 # Note: using
1875 #
1946 #
1876 # s = u'\xb5'
1947 # s = u'\xb5'
1877 # s.encode(sys.getdefaultencoding())
1948 # s.encode(sys.getdefaultencoding())
1878 #
1949 #
1879 # is not sufficient, as I've seen terminals where that fails but
1950 # is not sufficient, as I've seen terminals where that fails but
1880 # print s
1951 # print s
1881 #
1952 #
1882 # succeeds
1953 # succeeds
1883 #
1954 #
1884 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1955 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1885
1956
1886 #units = [u"s", u"ms",u'\xb5',"ns"]
1957 #units = [u"s", u"ms",u'\xb5',"ns"]
1887 units = [u"s", u"ms",u'us',"ns"]
1958 units = [u"s", u"ms",u'us',"ns"]
1888
1959
1889 scaling = [1, 1e3, 1e6, 1e9]
1960 scaling = [1, 1e3, 1e6, 1e9]
1890
1961
1891 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1962 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1892 posix=False, strict=False)
1963 posix=False, strict=False)
1893 if stmt == "":
1964 if stmt == "":
1894 return
1965 return
1895 timefunc = timeit.default_timer
1966 timefunc = timeit.default_timer
1896 number = int(getattr(opts, "n", 0))
1967 number = int(getattr(opts, "n", 0))
1897 repeat = int(getattr(opts, "r", timeit.default_repeat))
1968 repeat = int(getattr(opts, "r", timeit.default_repeat))
1898 precision = int(getattr(opts, "p", 3))
1969 precision = int(getattr(opts, "p", 3))
1899 if hasattr(opts, "t"):
1970 if hasattr(opts, "t"):
1900 timefunc = time.time
1971 timefunc = time.time
1901 if hasattr(opts, "c"):
1972 if hasattr(opts, "c"):
1902 timefunc = clock
1973 timefunc = clock
1903
1974
1904 timer = timeit.Timer(timer=timefunc)
1975 timer = timeit.Timer(timer=timefunc)
1905 # this code has tight coupling to the inner workings of timeit.Timer,
1976 # this code has tight coupling to the inner workings of timeit.Timer,
1906 # but is there a better way to achieve that the code stmt has access
1977 # but is there a better way to achieve that the code stmt has access
1907 # to the shell namespace?
1978 # to the shell namespace?
1908
1979
1909 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1980 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1910 'setup': "pass"}
1981 'setup': "pass"}
1911 # Track compilation time so it can be reported if too long
1982 # Track compilation time so it can be reported if too long
1912 # Minimum time above which compilation time will be reported
1983 # Minimum time above which compilation time will be reported
1913 tc_min = 0.1
1984 tc_min = 0.1
1914
1985
1915 t0 = clock()
1986 t0 = clock()
1916 code = compile(src, "<magic-timeit>", "exec")
1987 code = compile(src, "<magic-timeit>", "exec")
1917 tc = clock()-t0
1988 tc = clock()-t0
1918
1989
1919 ns = {}
1990 ns = {}
1920 exec code in self.shell.user_ns, ns
1991 exec code in self.shell.user_ns, ns
1921 timer.inner = ns["inner"]
1992 timer.inner = ns["inner"]
1922
1993
1923 if number == 0:
1994 if number == 0:
1924 # determine number so that 0.2 <= total time < 2.0
1995 # determine number so that 0.2 <= total time < 2.0
1925 number = 1
1996 number = 1
1926 for i in range(1, 10):
1997 for i in range(1, 10):
1927 if timer.timeit(number) >= 0.2:
1998 if timer.timeit(number) >= 0.2:
1928 break
1999 break
1929 number *= 10
2000 number *= 10
1930
2001
1931 best = min(timer.repeat(repeat, number)) / number
2002 best = min(timer.repeat(repeat, number)) / number
1932
2003
1933 if best > 0.0 and best < 1000.0:
2004 if best > 0.0 and best < 1000.0:
1934 order = min(-int(math.floor(math.log10(best)) // 3), 3)
2005 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1935 elif best >= 1000.0:
2006 elif best >= 1000.0:
1936 order = 0
2007 order = 0
1937 else:
2008 else:
1938 order = 3
2009 order = 3
1939 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
2010 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1940 precision,
2011 precision,
1941 best * scaling[order],
2012 best * scaling[order],
1942 units[order])
2013 units[order])
1943 if tc > tc_min:
2014 if tc > tc_min:
1944 print "Compiler time: %.2f s" % tc
2015 print "Compiler time: %.2f s" % tc
1945
2016
1946 @skip_doctest
2017 @skip_doctest
1947 @needs_local_scope
2018 @needs_local_scope
1948 def magic_time(self,parameter_s = ''):
2019 def magic_time(self,parameter_s = ''):
1949 """Time execution of a Python statement or expression.
2020 """Time execution of a Python statement or expression.
1950
2021
1951 The CPU and wall clock times are printed, and the value of the
2022 The CPU and wall clock times are printed, and the value of the
1952 expression (if any) is returned. Note that under Win32, system time
2023 expression (if any) is returned. Note that under Win32, system time
1953 is always reported as 0, since it can not be measured.
2024 is always reported as 0, since it can not be measured.
1954
2025
1955 This function provides very basic timing functionality. In Python
2026 This function provides very basic timing functionality. In Python
1956 2.3, the timeit module offers more control and sophistication, so this
2027 2.3, the timeit module offers more control and sophistication, so this
1957 could be rewritten to use it (patches welcome).
2028 could be rewritten to use it (patches welcome).
1958
2029
1959 Some examples:
2030 Some examples:
1960
2031
1961 In [1]: time 2**128
2032 In [1]: time 2**128
1962 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2033 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1963 Wall time: 0.00
2034 Wall time: 0.00
1964 Out[1]: 340282366920938463463374607431768211456L
2035 Out[1]: 340282366920938463463374607431768211456L
1965
2036
1966 In [2]: n = 1000000
2037 In [2]: n = 1000000
1967
2038
1968 In [3]: time sum(range(n))
2039 In [3]: time sum(range(n))
1969 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2040 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1970 Wall time: 1.37
2041 Wall time: 1.37
1971 Out[3]: 499999500000L
2042 Out[3]: 499999500000L
1972
2043
1973 In [4]: time print 'hello world'
2044 In [4]: time print 'hello world'
1974 hello world
2045 hello world
1975 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2046 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1976 Wall time: 0.00
2047 Wall time: 0.00
1977
2048
1978 Note that the time needed by Python to compile the given expression
2049 Note that the time needed by Python to compile the given expression
1979 will be reported if it is more than 0.1s. In this example, the
2050 will be reported if it is more than 0.1s. In this example, the
1980 actual exponentiation is done by Python at compilation time, so while
2051 actual exponentiation is done by Python at compilation time, so while
1981 the expression can take a noticeable amount of time to compute, that
2052 the expression can take a noticeable amount of time to compute, that
1982 time is purely due to the compilation:
2053 time is purely due to the compilation:
1983
2054
1984 In [5]: time 3**9999;
2055 In [5]: time 3**9999;
1985 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2056 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1986 Wall time: 0.00 s
2057 Wall time: 0.00 s
1987
2058
1988 In [6]: time 3**999999;
2059 In [6]: time 3**999999;
1989 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2060 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1990 Wall time: 0.00 s
2061 Wall time: 0.00 s
1991 Compiler : 0.78 s
2062 Compiler : 0.78 s
1992 """
2063 """
1993
2064
1994 # fail immediately if the given expression can't be compiled
2065 # fail immediately if the given expression can't be compiled
1995
2066
1996 expr = self.shell.prefilter(parameter_s,False)
2067 expr = self.shell.prefilter(parameter_s,False)
1997
2068
1998 # Minimum time above which compilation time will be reported
2069 # Minimum time above which compilation time will be reported
1999 tc_min = 0.1
2070 tc_min = 0.1
2000
2071
2001 try:
2072 try:
2002 mode = 'eval'
2073 mode = 'eval'
2003 t0 = clock()
2074 t0 = clock()
2004 code = compile(expr,'<timed eval>',mode)
2075 code = compile(expr,'<timed eval>',mode)
2005 tc = clock()-t0
2076 tc = clock()-t0
2006 except SyntaxError:
2077 except SyntaxError:
2007 mode = 'exec'
2078 mode = 'exec'
2008 t0 = clock()
2079 t0 = clock()
2009 code = compile(expr,'<timed exec>',mode)
2080 code = compile(expr,'<timed exec>',mode)
2010 tc = clock()-t0
2081 tc = clock()-t0
2011 # skew measurement as little as possible
2082 # skew measurement as little as possible
2012 glob = self.shell.user_ns
2083 glob = self.shell.user_ns
2013 locs = self._magic_locals
2084 locs = self._magic_locals
2014 clk = clock2
2085 clk = clock2
2015 wtime = time.time
2086 wtime = time.time
2016 # time execution
2087 # time execution
2017 wall_st = wtime()
2088 wall_st = wtime()
2018 if mode=='eval':
2089 if mode=='eval':
2019 st = clk()
2090 st = clk()
2020 out = eval(code, glob, locs)
2091 out = eval(code, glob, locs)
2021 end = clk()
2092 end = clk()
2022 else:
2093 else:
2023 st = clk()
2094 st = clk()
2024 exec code in glob, locs
2095 exec code in glob, locs
2025 end = clk()
2096 end = clk()
2026 out = None
2097 out = None
2027 wall_end = wtime()
2098 wall_end = wtime()
2028 # Compute actual times and report
2099 # Compute actual times and report
2029 wall_time = wall_end-wall_st
2100 wall_time = wall_end-wall_st
2030 cpu_user = end[0]-st[0]
2101 cpu_user = end[0]-st[0]
2031 cpu_sys = end[1]-st[1]
2102 cpu_sys = end[1]-st[1]
2032 cpu_tot = cpu_user+cpu_sys
2103 cpu_tot = cpu_user+cpu_sys
2033 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2104 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2034 (cpu_user,cpu_sys,cpu_tot)
2105 (cpu_user,cpu_sys,cpu_tot)
2035 print "Wall time: %.2f s" % wall_time
2106 print "Wall time: %.2f s" % wall_time
2036 if tc > tc_min:
2107 if tc > tc_min:
2037 print "Compiler : %.2f s" % tc
2108 print "Compiler : %.2f s" % tc
2038 return out
2109 return out
2039
2110
2040 @skip_doctest
2111 @skip_doctest
2041 def magic_macro(self,parameter_s = ''):
2112 def magic_macro(self,parameter_s = ''):
2042 """Define a macro for future re-execution. It accepts ranges of history,
2113 """Define a macro for future re-execution. It accepts ranges of history,
2043 filenames or string objects.
2114 filenames or string objects.
2044
2115
2045 Usage:\\
2116 Usage:\\
2046 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2117 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2047
2118
2048 Options:
2119 Options:
2049
2120
2050 -r: use 'raw' input. By default, the 'processed' history is used,
2121 -r: use 'raw' input. By default, the 'processed' history is used,
2051 so that magics are loaded in their transformed version to valid
2122 so that magics are loaded in their transformed version to valid
2052 Python. If this option is given, the raw input as typed as the
2123 Python. If this option is given, the raw input as typed as the
2053 command line is used instead.
2124 command line is used instead.
2054
2125
2055 This will define a global variable called `name` which is a string
2126 This will define a global variable called `name` which is a string
2056 made of joining the slices and lines you specify (n1,n2,... numbers
2127 made of joining the slices and lines you specify (n1,n2,... numbers
2057 above) from your input history into a single string. This variable
2128 above) from your input history into a single string. This variable
2058 acts like an automatic function which re-executes those lines as if
2129 acts like an automatic function which re-executes those lines as if
2059 you had typed them. You just type 'name' at the prompt and the code
2130 you had typed them. You just type 'name' at the prompt and the code
2060 executes.
2131 executes.
2061
2132
2062 The syntax for indicating input ranges is described in %history.
2133 The syntax for indicating input ranges is described in %history.
2063
2134
2064 Note: as a 'hidden' feature, you can also use traditional python slice
2135 Note: as a 'hidden' feature, you can also use traditional python slice
2065 notation, where N:M means numbers N through M-1.
2136 notation, where N:M means numbers N through M-1.
2066
2137
2067 For example, if your history contains (%hist prints it):
2138 For example, if your history contains (%hist prints it):
2068
2139
2069 44: x=1
2140 44: x=1
2070 45: y=3
2141 45: y=3
2071 46: z=x+y
2142 46: z=x+y
2072 47: print x
2143 47: print x
2073 48: a=5
2144 48: a=5
2074 49: print 'x',x,'y',y
2145 49: print 'x',x,'y',y
2075
2146
2076 you can create a macro with lines 44 through 47 (included) and line 49
2147 you can create a macro with lines 44 through 47 (included) and line 49
2077 called my_macro with:
2148 called my_macro with:
2078
2149
2079 In [55]: %macro my_macro 44-47 49
2150 In [55]: %macro my_macro 44-47 49
2080
2151
2081 Now, typing `my_macro` (without quotes) will re-execute all this code
2152 Now, typing `my_macro` (without quotes) will re-execute all this code
2082 in one pass.
2153 in one pass.
2083
2154
2084 You don't need to give the line-numbers in order, and any given line
2155 You don't need to give the line-numbers in order, and any given line
2085 number can appear multiple times. You can assemble macros with any
2156 number can appear multiple times. You can assemble macros with any
2086 lines from your input history in any order.
2157 lines from your input history in any order.
2087
2158
2088 The macro is a simple object which holds its value in an attribute,
2159 The macro is a simple object which holds its value in an attribute,
2089 but IPython's display system checks for macros and executes them as
2160 but IPython's display system checks for macros and executes them as
2090 code instead of printing them when you type their name.
2161 code instead of printing them when you type their name.
2091
2162
2092 You can view a macro's contents by explicitly printing it with:
2163 You can view a macro's contents by explicitly printing it with:
2093
2164
2094 'print macro_name'.
2165 'print macro_name'.
2095
2166
2096 """
2167 """
2097 opts,args = self.parse_options(parameter_s,'r',mode='list')
2168 opts,args = self.parse_options(parameter_s,'r',mode='list')
2098 if not args: # List existing macros
2169 if not args: # List existing macros
2099 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2170 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2100 isinstance(v, Macro))
2171 isinstance(v, Macro))
2101 if len(args) == 1:
2172 if len(args) == 1:
2102 raise UsageError(
2173 raise UsageError(
2103 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2174 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2104 name, codefrom = args[0], " ".join(args[1:])
2175 name, codefrom = args[0], " ".join(args[1:])
2105
2176
2106 #print 'rng',ranges # dbg
2177 #print 'rng',ranges # dbg
2107 try:
2178 try:
2108 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2179 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2109 except (ValueError, TypeError) as e:
2180 except (ValueError, TypeError) as e:
2110 print e.args[0]
2181 print e.args[0]
2111 return
2182 return
2112 macro = Macro(lines)
2183 macro = Macro(lines)
2113 self.shell.define_macro(name, macro)
2184 self.shell.define_macro(name, macro)
2114 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2185 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2115 print '=== Macro contents: ==='
2186 print '=== Macro contents: ==='
2116 print macro,
2187 print macro,
2117
2188
2118 def magic_save(self,parameter_s = ''):
2189 def magic_save(self,parameter_s = ''):
2119 """Save a set of lines or a macro to a given filename.
2190 """Save a set of lines or a macro to a given filename.
2120
2191
2121 Usage:\\
2192 Usage:\\
2122 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2193 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2123
2194
2124 Options:
2195 Options:
2125
2196
2126 -r: use 'raw' input. By default, the 'processed' history is used,
2197 -r: use 'raw' input. By default, the 'processed' history is used,
2127 so that magics are loaded in their transformed version to valid
2198 so that magics are loaded in their transformed version to valid
2128 Python. If this option is given, the raw input as typed as the
2199 Python. If this option is given, the raw input as typed as the
2129 command line is used instead.
2200 command line is used instead.
2130
2201
2131 This function uses the same syntax as %history for input ranges,
2202 This function uses the same syntax as %history for input ranges,
2132 then saves the lines to the filename you specify.
2203 then saves the lines to the filename you specify.
2133
2204
2134 It adds a '.py' extension to the file if you don't do so yourself, and
2205 It adds a '.py' extension to the file if you don't do so yourself, and
2135 it asks for confirmation before overwriting existing files."""
2206 it asks for confirmation before overwriting existing files."""
2136
2207
2137 opts,args = self.parse_options(parameter_s,'r',mode='list')
2208 opts,args = self.parse_options(parameter_s,'r',mode='list')
2138 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2209 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2139 if not fname.endswith('.py'):
2210 if not fname.endswith('.py'):
2140 fname += '.py'
2211 fname += '.py'
2141 if os.path.isfile(fname):
2212 if os.path.isfile(fname):
2142 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2213 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2143 if ans.lower() not in ['y','yes']:
2214 if ans.lower() not in ['y','yes']:
2144 print 'Operation cancelled.'
2215 print 'Operation cancelled.'
2145 return
2216 return
2146 try:
2217 try:
2147 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2218 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2148 except (TypeError, ValueError) as e:
2219 except (TypeError, ValueError) as e:
2149 print e.args[0]
2220 print e.args[0]
2150 return
2221 return
2151 with py3compat.open(fname,'w', encoding="utf-8") as f:
2222 with py3compat.open(fname,'w', encoding="utf-8") as f:
2152 f.write(u"# coding: utf-8\n")
2223 f.write(u"# coding: utf-8\n")
2153 f.write(py3compat.cast_unicode(cmds))
2224 f.write(py3compat.cast_unicode(cmds))
2154 print 'The following commands were written to file `%s`:' % fname
2225 print 'The following commands were written to file `%s`:' % fname
2155 print cmds
2226 print cmds
2156
2227
2157 def magic_pastebin(self, parameter_s = ''):
2228 def magic_pastebin(self, parameter_s = ''):
2158 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2229 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2159 try:
2230 try:
2160 code = self.shell.find_user_code(parameter_s)
2231 code = self.shell.find_user_code(parameter_s)
2161 except (ValueError, TypeError) as e:
2232 except (ValueError, TypeError) as e:
2162 print e.args[0]
2233 print e.args[0]
2163 return
2234 return
2164 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2235 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2165 id = pbserver.pastes.newPaste("python", code)
2236 id = pbserver.pastes.newPaste("python", code)
2166 return "http://paste.pocoo.org/show/" + id
2237 return "http://paste.pocoo.org/show/" + id
2167
2238
2168 def magic_loadpy(self, arg_s):
2239 def magic_loadpy(self, arg_s):
2169 """Load a .py python script into the GUI console.
2240 """Load a .py python script into the GUI console.
2170
2241
2171 This magic command can either take a local filename or a url::
2242 This magic command can either take a local filename or a url::
2172
2243
2173 %loadpy myscript.py
2244 %loadpy myscript.py
2174 %loadpy http://www.example.com/myscript.py
2245 %loadpy http://www.example.com/myscript.py
2175 """
2246 """
2176 arg_s = unquote_filename(arg_s)
2247 arg_s = unquote_filename(arg_s)
2177 remote_url = arg_s.startswith(('http://', 'https://'))
2248 remote_url = arg_s.startswith(('http://', 'https://'))
2178 local_url = not remote_url
2249 local_url = not remote_url
2179 if local_url and not arg_s.endswith('.py'):
2250 if local_url and not arg_s.endswith('.py'):
2180 # Local files must be .py; for remote URLs it's possible that the
2251 # Local files must be .py; for remote URLs it's possible that the
2181 # fetch URL doesn't have a .py in it (many servers have an opaque
2252 # fetch URL doesn't have a .py in it (many servers have an opaque
2182 # URL, such as scipy-central.org).
2253 # URL, such as scipy-central.org).
2183 raise ValueError('%%load only works with .py files: %s' % arg_s)
2254 raise ValueError('%%load only works with .py files: %s' % arg_s)
2184 if remote_url:
2255 if remote_url:
2185 import urllib2
2256 import urllib2
2186 fileobj = urllib2.urlopen(arg_s)
2257 fileobj = urllib2.urlopen(arg_s)
2187 # While responses have a .info().getencoding() way of asking for
2258 # While responses have a .info().getencoding() way of asking for
2188 # their encoding, in *many* cases the return value is bogus. In
2259 # their encoding, in *many* cases the return value is bogus. In
2189 # the wild, servers serving utf-8 but declaring latin-1 are
2260 # the wild, servers serving utf-8 but declaring latin-1 are
2190 # extremely common, as the old HTTP standards specify latin-1 as
2261 # extremely common, as the old HTTP standards specify latin-1 as
2191 # the default but many modern filesystems use utf-8. So we can NOT
2262 # the default but many modern filesystems use utf-8. So we can NOT
2192 # rely on the headers. Short of building complex encoding-guessing
2263 # rely on the headers. Short of building complex encoding-guessing
2193 # logic, going with utf-8 is a simple solution likely to be right
2264 # logic, going with utf-8 is a simple solution likely to be right
2194 # in most real-world cases.
2265 # in most real-world cases.
2195 linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
2266 linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
2196 fileobj.close()
2267 fileobj.close()
2197 else:
2268 else:
2198 with open(arg_s) as fileobj:
2269 with open(arg_s) as fileobj:
2199 linesource = fileobj.read().splitlines()
2270 linesource = fileobj.read().splitlines()
2200
2271
2201 # Strip out encoding declarations
2272 # Strip out encoding declarations
2202 lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
2273 lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
2203
2274
2204 self.set_next_input(os.linesep.join(lines))
2275 self.set_next_input(os.linesep.join(lines))
2205
2276
2206 def _find_edit_target(self, args, opts, last_call):
2277 def _find_edit_target(self, args, opts, last_call):
2207 """Utility method used by magic_edit to find what to edit."""
2278 """Utility method used by magic_edit to find what to edit."""
2208
2279
2209 def make_filename(arg):
2280 def make_filename(arg):
2210 "Make a filename from the given args"
2281 "Make a filename from the given args"
2211 arg = unquote_filename(arg)
2282 arg = unquote_filename(arg)
2212 try:
2283 try:
2213 filename = get_py_filename(arg)
2284 filename = get_py_filename(arg)
2214 except IOError:
2285 except IOError:
2215 # If it ends with .py but doesn't already exist, assume we want
2286 # If it ends with .py but doesn't already exist, assume we want
2216 # a new file.
2287 # a new file.
2217 if arg.endswith('.py'):
2288 if arg.endswith('.py'):
2218 filename = arg
2289 filename = arg
2219 else:
2290 else:
2220 filename = None
2291 filename = None
2221 return filename
2292 return filename
2222
2293
2223 # Set a few locals from the options for convenience:
2294 # Set a few locals from the options for convenience:
2224 opts_prev = 'p' in opts
2295 opts_prev = 'p' in opts
2225 opts_raw = 'r' in opts
2296 opts_raw = 'r' in opts
2226
2297
2227 # custom exceptions
2298 # custom exceptions
2228 class DataIsObject(Exception): pass
2299 class DataIsObject(Exception): pass
2229
2300
2230 # Default line number value
2301 # Default line number value
2231 lineno = opts.get('n',None)
2302 lineno = opts.get('n',None)
2232
2303
2233 if opts_prev:
2304 if opts_prev:
2234 args = '_%s' % last_call[0]
2305 args = '_%s' % last_call[0]
2235 if not self.shell.user_ns.has_key(args):
2306 if not self.shell.user_ns.has_key(args):
2236 args = last_call[1]
2307 args = last_call[1]
2237
2308
2238 # use last_call to remember the state of the previous call, but don't
2309 # use last_call to remember the state of the previous call, but don't
2239 # let it be clobbered by successive '-p' calls.
2310 # let it be clobbered by successive '-p' calls.
2240 try:
2311 try:
2241 last_call[0] = self.shell.displayhook.prompt_count
2312 last_call[0] = self.shell.displayhook.prompt_count
2242 if not opts_prev:
2313 if not opts_prev:
2243 last_call[1] = parameter_s
2314 last_call[1] = parameter_s
2244 except:
2315 except:
2245 pass
2316 pass
2246
2317
2247 # by default this is done with temp files, except when the given
2318 # by default this is done with temp files, except when the given
2248 # arg is a filename
2319 # arg is a filename
2249 use_temp = True
2320 use_temp = True
2250
2321
2251 data = ''
2322 data = ''
2252
2323
2253 # First, see if the arguments should be a filename.
2324 # First, see if the arguments should be a filename.
2254 filename = make_filename(args)
2325 filename = make_filename(args)
2255 if filename:
2326 if filename:
2256 use_temp = False
2327 use_temp = False
2257 elif args:
2328 elif args:
2258 # Mode where user specifies ranges of lines, like in %macro.
2329 # Mode where user specifies ranges of lines, like in %macro.
2259 data = self.extract_input_lines(args, opts_raw)
2330 data = self.extract_input_lines(args, opts_raw)
2260 if not data:
2331 if not data:
2261 try:
2332 try:
2262 # Load the parameter given as a variable. If not a string,
2333 # Load the parameter given as a variable. If not a string,
2263 # process it as an object instead (below)
2334 # process it as an object instead (below)
2264
2335
2265 #print '*** args',args,'type',type(args) # dbg
2336 #print '*** args',args,'type',type(args) # dbg
2266 data = eval(args, self.shell.user_ns)
2337 data = eval(args, self.shell.user_ns)
2267 if not isinstance(data, basestring):
2338 if not isinstance(data, basestring):
2268 raise DataIsObject
2339 raise DataIsObject
2269
2340
2270 except (NameError,SyntaxError):
2341 except (NameError,SyntaxError):
2271 # given argument is not a variable, try as a filename
2342 # given argument is not a variable, try as a filename
2272 filename = make_filename(args)
2343 filename = make_filename(args)
2273 if filename is None:
2344 if filename is None:
2274 warn("Argument given (%s) can't be found as a variable "
2345 warn("Argument given (%s) can't be found as a variable "
2275 "or as a filename." % args)
2346 "or as a filename." % args)
2276 return
2347 return
2277 use_temp = False
2348 use_temp = False
2278
2349
2279 except DataIsObject:
2350 except DataIsObject:
2280 # macros have a special edit function
2351 # macros have a special edit function
2281 if isinstance(data, Macro):
2352 if isinstance(data, Macro):
2282 raise MacroToEdit(data)
2353 raise MacroToEdit(data)
2283
2354
2284 # For objects, try to edit the file where they are defined
2355 # For objects, try to edit the file where they are defined
2285 try:
2356 try:
2286 filename = inspect.getabsfile(data)
2357 filename = inspect.getabsfile(data)
2287 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2358 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2288 # class created by %edit? Try to find source
2359 # class created by %edit? Try to find source
2289 # by looking for method definitions instead, the
2360 # by looking for method definitions instead, the
2290 # __module__ in those classes is FakeModule.
2361 # __module__ in those classes is FakeModule.
2291 attrs = [getattr(data, aname) for aname in dir(data)]
2362 attrs = [getattr(data, aname) for aname in dir(data)]
2292 for attr in attrs:
2363 for attr in attrs:
2293 if not inspect.ismethod(attr):
2364 if not inspect.ismethod(attr):
2294 continue
2365 continue
2295 filename = inspect.getabsfile(attr)
2366 filename = inspect.getabsfile(attr)
2296 if filename and 'fakemodule' not in filename.lower():
2367 if filename and 'fakemodule' not in filename.lower():
2297 # change the attribute to be the edit target instead
2368 # change the attribute to be the edit target instead
2298 data = attr
2369 data = attr
2299 break
2370 break
2300
2371
2301 datafile = 1
2372 datafile = 1
2302 except TypeError:
2373 except TypeError:
2303 filename = make_filename(args)
2374 filename = make_filename(args)
2304 datafile = 1
2375 datafile = 1
2305 warn('Could not find file where `%s` is defined.\n'
2376 warn('Could not find file where `%s` is defined.\n'
2306 'Opening a file named `%s`' % (args,filename))
2377 'Opening a file named `%s`' % (args,filename))
2307 # Now, make sure we can actually read the source (if it was in
2378 # Now, make sure we can actually read the source (if it was in
2308 # a temp file it's gone by now).
2379 # a temp file it's gone by now).
2309 if datafile:
2380 if datafile:
2310 try:
2381 try:
2311 if lineno is None:
2382 if lineno is None:
2312 lineno = inspect.getsourcelines(data)[1]
2383 lineno = inspect.getsourcelines(data)[1]
2313 except IOError:
2384 except IOError:
2314 filename = make_filename(args)
2385 filename = make_filename(args)
2315 if filename is None:
2386 if filename is None:
2316 warn('The file `%s` where `%s` was defined cannot '
2387 warn('The file `%s` where `%s` was defined cannot '
2317 'be read.' % (filename,data))
2388 'be read.' % (filename,data))
2318 return
2389 return
2319 use_temp = False
2390 use_temp = False
2320
2391
2321 if use_temp:
2392 if use_temp:
2322 filename = self.shell.mktempfile(data)
2393 filename = self.shell.mktempfile(data)
2323 print 'IPython will make a temporary file named:',filename
2394 print 'IPython will make a temporary file named:',filename
2324
2395
2325 return filename, lineno, use_temp
2396 return filename, lineno, use_temp
2326
2397
2327 def _edit_macro(self,mname,macro):
2398 def _edit_macro(self,mname,macro):
2328 """open an editor with the macro data in a file"""
2399 """open an editor with the macro data in a file"""
2329 filename = self.shell.mktempfile(macro.value)
2400 filename = self.shell.mktempfile(macro.value)
2330 self.shell.hooks.editor(filename)
2401 self.shell.hooks.editor(filename)
2331
2402
2332 # and make a new macro object, to replace the old one
2403 # and make a new macro object, to replace the old one
2333 mfile = open(filename)
2404 mfile = open(filename)
2334 mvalue = mfile.read()
2405 mvalue = mfile.read()
2335 mfile.close()
2406 mfile.close()
2336 self.shell.user_ns[mname] = Macro(mvalue)
2407 self.shell.user_ns[mname] = Macro(mvalue)
2337
2408
2338 def magic_ed(self,parameter_s=''):
2409 def magic_ed(self,parameter_s=''):
2339 """Alias to %edit."""
2410 """Alias to %edit."""
2340 return self.magic_edit(parameter_s)
2411 return self.magic_edit(parameter_s)
2341
2412
2342 @skip_doctest
2413 @skip_doctest
2343 def magic_edit(self,parameter_s='',last_call=['','']):
2414 def magic_edit(self,parameter_s='',last_call=['','']):
2344 """Bring up an editor and execute the resulting code.
2415 """Bring up an editor and execute the resulting code.
2345
2416
2346 Usage:
2417 Usage:
2347 %edit [options] [args]
2418 %edit [options] [args]
2348
2419
2349 %edit runs IPython's editor hook. The default version of this hook is
2420 %edit runs IPython's editor hook. The default version of this hook is
2350 set to call the editor specified by your $EDITOR environment variable.
2421 set to call the editor specified by your $EDITOR environment variable.
2351 If this isn't found, it will default to vi under Linux/Unix and to
2422 If this isn't found, it will default to vi under Linux/Unix and to
2352 notepad under Windows. See the end of this docstring for how to change
2423 notepad under Windows. See the end of this docstring for how to change
2353 the editor hook.
2424 the editor hook.
2354
2425
2355 You can also set the value of this editor via the
2426 You can also set the value of this editor via the
2356 ``TerminalInteractiveShell.editor`` option in your configuration file.
2427 ``TerminalInteractiveShell.editor`` option in your configuration file.
2357 This is useful if you wish to use a different editor from your typical
2428 This is useful if you wish to use a different editor from your typical
2358 default with IPython (and for Windows users who typically don't set
2429 default with IPython (and for Windows users who typically don't set
2359 environment variables).
2430 environment variables).
2360
2431
2361 This command allows you to conveniently edit multi-line code right in
2432 This command allows you to conveniently edit multi-line code right in
2362 your IPython session.
2433 your IPython session.
2363
2434
2364 If called without arguments, %edit opens up an empty editor with a
2435 If called without arguments, %edit opens up an empty editor with a
2365 temporary file and will execute the contents of this file when you
2436 temporary file and will execute the contents of this file when you
2366 close it (don't forget to save it!).
2437 close it (don't forget to save it!).
2367
2438
2368
2439
2369 Options:
2440 Options:
2370
2441
2371 -n <number>: open the editor at a specified line number. By default,
2442 -n <number>: open the editor at a specified line number. By default,
2372 the IPython editor hook uses the unix syntax 'editor +N filename', but
2443 the IPython editor hook uses the unix syntax 'editor +N filename', but
2373 you can configure this by providing your own modified hook if your
2444 you can configure this by providing your own modified hook if your
2374 favorite editor supports line-number specifications with a different
2445 favorite editor supports line-number specifications with a different
2375 syntax.
2446 syntax.
2376
2447
2377 -p: this will call the editor with the same data as the previous time
2448 -p: this will call the editor with the same data as the previous time
2378 it was used, regardless of how long ago (in your current session) it
2449 it was used, regardless of how long ago (in your current session) it
2379 was.
2450 was.
2380
2451
2381 -r: use 'raw' input. This option only applies to input taken from the
2452 -r: use 'raw' input. This option only applies to input taken from the
2382 user's history. By default, the 'processed' history is used, so that
2453 user's history. By default, the 'processed' history is used, so that
2383 magics are loaded in their transformed version to valid Python. If
2454 magics are loaded in their transformed version to valid Python. If
2384 this option is given, the raw input as typed as the command line is
2455 this option is given, the raw input as typed as the command line is
2385 used instead. When you exit the editor, it will be executed by
2456 used instead. When you exit the editor, it will be executed by
2386 IPython's own processor.
2457 IPython's own processor.
2387
2458
2388 -x: do not execute the edited code immediately upon exit. This is
2459 -x: do not execute the edited code immediately upon exit. This is
2389 mainly useful if you are editing programs which need to be called with
2460 mainly useful if you are editing programs which need to be called with
2390 command line arguments, which you can then do using %run.
2461 command line arguments, which you can then do using %run.
2391
2462
2392
2463
2393 Arguments:
2464 Arguments:
2394
2465
2395 If arguments are given, the following possibilities exist:
2466 If arguments are given, the following possibilities exist:
2396
2467
2397 - If the argument is a filename, IPython will load that into the
2468 - If the argument is a filename, IPython will load that into the
2398 editor. It will execute its contents with execfile() when you exit,
2469 editor. It will execute its contents with execfile() when you exit,
2399 loading any code in the file into your interactive namespace.
2470 loading any code in the file into your interactive namespace.
2400
2471
2401 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2472 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2402 The syntax is the same as in the %history magic.
2473 The syntax is the same as in the %history magic.
2403
2474
2404 - If the argument is a string variable, its contents are loaded
2475 - If the argument is a string variable, its contents are loaded
2405 into the editor. You can thus edit any string which contains
2476 into the editor. You can thus edit any string which contains
2406 python code (including the result of previous edits).
2477 python code (including the result of previous edits).
2407
2478
2408 - If the argument is the name of an object (other than a string),
2479 - If the argument is the name of an object (other than a string),
2409 IPython will try to locate the file where it was defined and open the
2480 IPython will try to locate the file where it was defined and open the
2410 editor at the point where it is defined. You can use `%edit function`
2481 editor at the point where it is defined. You can use `%edit function`
2411 to load an editor exactly at the point where 'function' is defined,
2482 to load an editor exactly at the point where 'function' is defined,
2412 edit it and have the file be executed automatically.
2483 edit it and have the file be executed automatically.
2413
2484
2414 - If the object is a macro (see %macro for details), this opens up your
2485 - If the object is a macro (see %macro for details), this opens up your
2415 specified editor with a temporary file containing the macro's data.
2486 specified editor with a temporary file containing the macro's data.
2416 Upon exit, the macro is reloaded with the contents of the file.
2487 Upon exit, the macro is reloaded with the contents of the file.
2417
2488
2418 Note: opening at an exact line is only supported under Unix, and some
2489 Note: opening at an exact line is only supported under Unix, and some
2419 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2490 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2420 '+NUMBER' parameter necessary for this feature. Good editors like
2491 '+NUMBER' parameter necessary for this feature. Good editors like
2421 (X)Emacs, vi, jed, pico and joe all do.
2492 (X)Emacs, vi, jed, pico and joe all do.
2422
2493
2423 After executing your code, %edit will return as output the code you
2494 After executing your code, %edit will return as output the code you
2424 typed in the editor (except when it was an existing file). This way
2495 typed in the editor (except when it was an existing file). This way
2425 you can reload the code in further invocations of %edit as a variable,
2496 you can reload the code in further invocations of %edit as a variable,
2426 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2497 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2427 the output.
2498 the output.
2428
2499
2429 Note that %edit is also available through the alias %ed.
2500 Note that %edit is also available through the alias %ed.
2430
2501
2431 This is an example of creating a simple function inside the editor and
2502 This is an example of creating a simple function inside the editor and
2432 then modifying it. First, start up the editor:
2503 then modifying it. First, start up the editor:
2433
2504
2434 In [1]: ed
2505 In [1]: ed
2435 Editing... done. Executing edited code...
2506 Editing... done. Executing edited code...
2436 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2507 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2437
2508
2438 We can then call the function foo():
2509 We can then call the function foo():
2439
2510
2440 In [2]: foo()
2511 In [2]: foo()
2441 foo() was defined in an editing session
2512 foo() was defined in an editing session
2442
2513
2443 Now we edit foo. IPython automatically loads the editor with the
2514 Now we edit foo. IPython automatically loads the editor with the
2444 (temporary) file where foo() was previously defined:
2515 (temporary) file where foo() was previously defined:
2445
2516
2446 In [3]: ed foo
2517 In [3]: ed foo
2447 Editing... done. Executing edited code...
2518 Editing... done. Executing edited code...
2448
2519
2449 And if we call foo() again we get the modified version:
2520 And if we call foo() again we get the modified version:
2450
2521
2451 In [4]: foo()
2522 In [4]: foo()
2452 foo() has now been changed!
2523 foo() has now been changed!
2453
2524
2454 Here is an example of how to edit a code snippet successive
2525 Here is an example of how to edit a code snippet successive
2455 times. First we call the editor:
2526 times. First we call the editor:
2456
2527
2457 In [5]: ed
2528 In [5]: ed
2458 Editing... done. Executing edited code...
2529 Editing... done. Executing edited code...
2459 hello
2530 hello
2460 Out[5]: "print 'hello'n"
2531 Out[5]: "print 'hello'n"
2461
2532
2462 Now we call it again with the previous output (stored in _):
2533 Now we call it again with the previous output (stored in _):
2463
2534
2464 In [6]: ed _
2535 In [6]: ed _
2465 Editing... done. Executing edited code...
2536 Editing... done. Executing edited code...
2466 hello world
2537 hello world
2467 Out[6]: "print 'hello world'n"
2538 Out[6]: "print 'hello world'n"
2468
2539
2469 Now we call it with the output #8 (stored in _8, also as Out[8]):
2540 Now we call it with the output #8 (stored in _8, also as Out[8]):
2470
2541
2471 In [7]: ed _8
2542 In [7]: ed _8
2472 Editing... done. Executing edited code...
2543 Editing... done. Executing edited code...
2473 hello again
2544 hello again
2474 Out[7]: "print 'hello again'n"
2545 Out[7]: "print 'hello again'n"
2475
2546
2476
2547
2477 Changing the default editor hook:
2548 Changing the default editor hook:
2478
2549
2479 If you wish to write your own editor hook, you can put it in a
2550 If you wish to write your own editor hook, you can put it in a
2480 configuration file which you load at startup time. The default hook
2551 configuration file which you load at startup time. The default hook
2481 is defined in the IPython.core.hooks module, and you can use that as a
2552 is defined in the IPython.core.hooks module, and you can use that as a
2482 starting example for further modifications. That file also has
2553 starting example for further modifications. That file also has
2483 general instructions on how to set a new hook for use once you've
2554 general instructions on how to set a new hook for use once you've
2484 defined it."""
2555 defined it."""
2485 opts,args = self.parse_options(parameter_s,'prxn:')
2556 opts,args = self.parse_options(parameter_s,'prxn:')
2486
2557
2487 try:
2558 try:
2488 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2559 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2489 except MacroToEdit as e:
2560 except MacroToEdit as e:
2490 self._edit_macro(args, e.args[0])
2561 self._edit_macro(args, e.args[0])
2491 return
2562 return
2492
2563
2493 # do actual editing here
2564 # do actual editing here
2494 print 'Editing...',
2565 print 'Editing...',
2495 sys.stdout.flush()
2566 sys.stdout.flush()
2496 try:
2567 try:
2497 # Quote filenames that may have spaces in them
2568 # Quote filenames that may have spaces in them
2498 if ' ' in filename:
2569 if ' ' in filename:
2499 filename = "'%s'" % filename
2570 filename = "'%s'" % filename
2500 self.shell.hooks.editor(filename,lineno)
2571 self.shell.hooks.editor(filename,lineno)
2501 except TryNext:
2572 except TryNext:
2502 warn('Could not open editor')
2573 warn('Could not open editor')
2503 return
2574 return
2504
2575
2505 # XXX TODO: should this be generalized for all string vars?
2576 # XXX TODO: should this be generalized for all string vars?
2506 # For now, this is special-cased to blocks created by cpaste
2577 # For now, this is special-cased to blocks created by cpaste
2507 if args.strip() == 'pasted_block':
2578 if args.strip() == 'pasted_block':
2508 self.shell.user_ns['pasted_block'] = file_read(filename)
2579 self.shell.user_ns['pasted_block'] = file_read(filename)
2509
2580
2510 if 'x' in opts: # -x prevents actual execution
2581 if 'x' in opts: # -x prevents actual execution
2511 print
2582 print
2512 else:
2583 else:
2513 print 'done. Executing edited code...'
2584 print 'done. Executing edited code...'
2514 if 'r' in opts: # Untranslated IPython code
2585 if 'r' in opts: # Untranslated IPython code
2515 self.shell.run_cell(file_read(filename),
2586 self.shell.run_cell(file_read(filename),
2516 store_history=False)
2587 store_history=False)
2517 else:
2588 else:
2518 self.shell.safe_execfile(filename,self.shell.user_ns,
2589 self.shell.safe_execfile(filename,self.shell.user_ns,
2519 self.shell.user_ns)
2590 self.shell.user_ns)
2520
2591
2521 if is_temp:
2592 if is_temp:
2522 try:
2593 try:
2523 return open(filename).read()
2594 return open(filename).read()
2524 except IOError,msg:
2595 except IOError,msg:
2525 if msg.filename == filename:
2596 if msg.filename == filename:
2526 warn('File not found. Did you forget to save?')
2597 warn('File not found. Did you forget to save?')
2527 return
2598 return
2528 else:
2599 else:
2529 self.shell.showtraceback()
2600 self.shell.showtraceback()
2530
2601
2531 def magic_xmode(self,parameter_s = ''):
2602 def magic_xmode(self,parameter_s = ''):
2532 """Switch modes for the exception handlers.
2603 """Switch modes for the exception handlers.
2533
2604
2534 Valid modes: Plain, Context and Verbose.
2605 Valid modes: Plain, Context and Verbose.
2535
2606
2536 If called without arguments, acts as a toggle."""
2607 If called without arguments, acts as a toggle."""
2537
2608
2538 def xmode_switch_err(name):
2609 def xmode_switch_err(name):
2539 warn('Error changing %s exception modes.\n%s' %
2610 warn('Error changing %s exception modes.\n%s' %
2540 (name,sys.exc_info()[1]))
2611 (name,sys.exc_info()[1]))
2541
2612
2542 shell = self.shell
2613 shell = self.shell
2543 new_mode = parameter_s.strip().capitalize()
2614 new_mode = parameter_s.strip().capitalize()
2544 try:
2615 try:
2545 shell.InteractiveTB.set_mode(mode=new_mode)
2616 shell.InteractiveTB.set_mode(mode=new_mode)
2546 print 'Exception reporting mode:',shell.InteractiveTB.mode
2617 print 'Exception reporting mode:',shell.InteractiveTB.mode
2547 except:
2618 except:
2548 xmode_switch_err('user')
2619 xmode_switch_err('user')
2549
2620
2550 def magic_colors(self,parameter_s = ''):
2621 def magic_colors(self,parameter_s = ''):
2551 """Switch color scheme for prompts, info system and exception handlers.
2622 """Switch color scheme for prompts, info system and exception handlers.
2552
2623
2553 Currently implemented schemes: NoColor, Linux, LightBG.
2624 Currently implemented schemes: NoColor, Linux, LightBG.
2554
2625
2555 Color scheme names are not case-sensitive.
2626 Color scheme names are not case-sensitive.
2556
2627
2557 Examples
2628 Examples
2558 --------
2629 --------
2559 To get a plain black and white terminal::
2630 To get a plain black and white terminal::
2560
2631
2561 %colors nocolor
2632 %colors nocolor
2562 """
2633 """
2563
2634
2564 def color_switch_err(name):
2635 def color_switch_err(name):
2565 warn('Error changing %s color schemes.\n%s' %
2636 warn('Error changing %s color schemes.\n%s' %
2566 (name,sys.exc_info()[1]))
2637 (name,sys.exc_info()[1]))
2567
2638
2568
2639
2569 new_scheme = parameter_s.strip()
2640 new_scheme = parameter_s.strip()
2570 if not new_scheme:
2641 if not new_scheme:
2571 raise UsageError(
2642 raise UsageError(
2572 "%colors: you must specify a color scheme. See '%colors?'")
2643 "%colors: you must specify a color scheme. See '%colors?'")
2573 return
2644 return
2574 # local shortcut
2645 # local shortcut
2575 shell = self.shell
2646 shell = self.shell
2576
2647
2577 import IPython.utils.rlineimpl as readline
2648 import IPython.utils.rlineimpl as readline
2578
2649
2579 if not shell.colors_force and \
2650 if not shell.colors_force and \
2580 not readline.have_readline and sys.platform == "win32":
2651 not readline.have_readline and sys.platform == "win32":
2581 msg = """\
2652 msg = """\
2582 Proper color support under MS Windows requires the pyreadline library.
2653 Proper color support under MS Windows requires the pyreadline library.
2583 You can find it at:
2654 You can find it at:
2584 http://ipython.org/pyreadline.html
2655 http://ipython.org/pyreadline.html
2585 Gary's readline needs the ctypes module, from:
2656 Gary's readline needs the ctypes module, from:
2586 http://starship.python.net/crew/theller/ctypes
2657 http://starship.python.net/crew/theller/ctypes
2587 (Note that ctypes is already part of Python versions 2.5 and newer).
2658 (Note that ctypes is already part of Python versions 2.5 and newer).
2588
2659
2589 Defaulting color scheme to 'NoColor'"""
2660 Defaulting color scheme to 'NoColor'"""
2590 new_scheme = 'NoColor'
2661 new_scheme = 'NoColor'
2591 warn(msg)
2662 warn(msg)
2592
2663
2593 # readline option is 0
2664 # readline option is 0
2594 if not shell.colors_force and not shell.has_readline:
2665 if not shell.colors_force and not shell.has_readline:
2595 new_scheme = 'NoColor'
2666 new_scheme = 'NoColor'
2596
2667
2597 # Set prompt colors
2668 # Set prompt colors
2598 try:
2669 try:
2599 shell.prompt_manager.color_scheme = new_scheme
2670 shell.prompt_manager.color_scheme = new_scheme
2600 except:
2671 except:
2601 color_switch_err('prompt')
2672 color_switch_err('prompt')
2602 else:
2673 else:
2603 shell.colors = \
2674 shell.colors = \
2604 shell.prompt_manager.color_scheme_table.active_scheme_name
2675 shell.prompt_manager.color_scheme_table.active_scheme_name
2605 # Set exception colors
2676 # Set exception colors
2606 try:
2677 try:
2607 shell.InteractiveTB.set_colors(scheme = new_scheme)
2678 shell.InteractiveTB.set_colors(scheme = new_scheme)
2608 shell.SyntaxTB.set_colors(scheme = new_scheme)
2679 shell.SyntaxTB.set_colors(scheme = new_scheme)
2609 except:
2680 except:
2610 color_switch_err('exception')
2681 color_switch_err('exception')
2611
2682
2612 # Set info (for 'object?') colors
2683 # Set info (for 'object?') colors
2613 if shell.color_info:
2684 if shell.color_info:
2614 try:
2685 try:
2615 shell.inspector.set_active_scheme(new_scheme)
2686 shell.inspector.set_active_scheme(new_scheme)
2616 except:
2687 except:
2617 color_switch_err('object inspector')
2688 color_switch_err('object inspector')
2618 else:
2689 else:
2619 shell.inspector.set_active_scheme('NoColor')
2690 shell.inspector.set_active_scheme('NoColor')
2620
2691
2621 def magic_pprint(self, parameter_s=''):
2692 def magic_pprint(self, parameter_s=''):
2622 """Toggle pretty printing on/off."""
2693 """Toggle pretty printing on/off."""
2623 ptformatter = self.shell.display_formatter.formatters['text/plain']
2694 ptformatter = self.shell.display_formatter.formatters['text/plain']
2624 ptformatter.pprint = bool(1 - ptformatter.pprint)
2695 ptformatter.pprint = bool(1 - ptformatter.pprint)
2625 print 'Pretty printing has been turned', \
2696 print 'Pretty printing has been turned', \
2626 ['OFF','ON'][ptformatter.pprint]
2697 ['OFF','ON'][ptformatter.pprint]
2627
2698
2628 #......................................................................
2699 #......................................................................
2629 # Functions to implement unix shell-type things
2700 # Functions to implement unix shell-type things
2630
2701
2631 @skip_doctest
2702 @skip_doctest
2632 def magic_alias(self, parameter_s = ''):
2703 def magic_alias(self, parameter_s = ''):
2633 """Define an alias for a system command.
2704 """Define an alias for a system command.
2634
2705
2635 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2706 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2636
2707
2637 Then, typing 'alias_name params' will execute the system command 'cmd
2708 Then, typing 'alias_name params' will execute the system command 'cmd
2638 params' (from your underlying operating system).
2709 params' (from your underlying operating system).
2639
2710
2640 Aliases have lower precedence than magic functions and Python normal
2711 Aliases have lower precedence than magic functions and Python normal
2641 variables, so if 'foo' is both a Python variable and an alias, the
2712 variables, so if 'foo' is both a Python variable and an alias, the
2642 alias can not be executed until 'del foo' removes the Python variable.
2713 alias can not be executed until 'del foo' removes the Python variable.
2643
2714
2644 You can use the %l specifier in an alias definition to represent the
2715 You can use the %l specifier in an alias definition to represent the
2645 whole line when the alias is called. For example:
2716 whole line when the alias is called. For example:
2646
2717
2647 In [2]: alias bracket echo "Input in brackets: <%l>"
2718 In [2]: alias bracket echo "Input in brackets: <%l>"
2648 In [3]: bracket hello world
2719 In [3]: bracket hello world
2649 Input in brackets: <hello world>
2720 Input in brackets: <hello world>
2650
2721
2651 You can also define aliases with parameters using %s specifiers (one
2722 You can also define aliases with parameters using %s specifiers (one
2652 per parameter):
2723 per parameter):
2653
2724
2654 In [1]: alias parts echo first %s second %s
2725 In [1]: alias parts echo first %s second %s
2655 In [2]: %parts A B
2726 In [2]: %parts A B
2656 first A second B
2727 first A second B
2657 In [3]: %parts A
2728 In [3]: %parts A
2658 Incorrect number of arguments: 2 expected.
2729 Incorrect number of arguments: 2 expected.
2659 parts is an alias to: 'echo first %s second %s'
2730 parts is an alias to: 'echo first %s second %s'
2660
2731
2661 Note that %l and %s are mutually exclusive. You can only use one or
2732 Note that %l and %s are mutually exclusive. You can only use one or
2662 the other in your aliases.
2733 the other in your aliases.
2663
2734
2664 Aliases expand Python variables just like system calls using ! or !!
2735 Aliases expand Python variables just like system calls using ! or !!
2665 do: all expressions prefixed with '$' get expanded. For details of
2736 do: all expressions prefixed with '$' get expanded. For details of
2666 the semantic rules, see PEP-215:
2737 the semantic rules, see PEP-215:
2667 http://www.python.org/peps/pep-0215.html. This is the library used by
2738 http://www.python.org/peps/pep-0215.html. This is the library used by
2668 IPython for variable expansion. If you want to access a true shell
2739 IPython for variable expansion. If you want to access a true shell
2669 variable, an extra $ is necessary to prevent its expansion by IPython:
2740 variable, an extra $ is necessary to prevent its expansion by IPython:
2670
2741
2671 In [6]: alias show echo
2742 In [6]: alias show echo
2672 In [7]: PATH='A Python string'
2743 In [7]: PATH='A Python string'
2673 In [8]: show $PATH
2744 In [8]: show $PATH
2674 A Python string
2745 A Python string
2675 In [9]: show $$PATH
2746 In [9]: show $$PATH
2676 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2747 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2677
2748
2678 You can use the alias facility to acess all of $PATH. See the %rehash
2749 You can use the alias facility to acess all of $PATH. See the %rehash
2679 and %rehashx functions, which automatically create aliases for the
2750 and %rehashx functions, which automatically create aliases for the
2680 contents of your $PATH.
2751 contents of your $PATH.
2681
2752
2682 If called with no parameters, %alias prints the current alias table."""
2753 If called with no parameters, %alias prints the current alias table."""
2683
2754
2684 par = parameter_s.strip()
2755 par = parameter_s.strip()
2685 if not par:
2756 if not par:
2686 stored = self.db.get('stored_aliases', {} )
2757 stored = self.db.get('stored_aliases', {} )
2687 aliases = sorted(self.shell.alias_manager.aliases)
2758 aliases = sorted(self.shell.alias_manager.aliases)
2688 # for k, v in stored:
2759 # for k, v in stored:
2689 # atab.append(k, v[0])
2760 # atab.append(k, v[0])
2690
2761
2691 print "Total number of aliases:", len(aliases)
2762 print "Total number of aliases:", len(aliases)
2692 sys.stdout.flush()
2763 sys.stdout.flush()
2693 return aliases
2764 return aliases
2694
2765
2695 # Now try to define a new one
2766 # Now try to define a new one
2696 try:
2767 try:
2697 alias,cmd = par.split(None, 1)
2768 alias,cmd = par.split(None, 1)
2698 except:
2769 except:
2699 print oinspect.getdoc(self.magic_alias)
2770 print oinspect.getdoc(self.magic_alias)
2700 else:
2771 else:
2701 self.shell.alias_manager.soft_define_alias(alias, cmd)
2772 self.shell.alias_manager.soft_define_alias(alias, cmd)
2702 # end magic_alias
2773 # end magic_alias
2703
2774
2704 def magic_unalias(self, parameter_s = ''):
2775 def magic_unalias(self, parameter_s = ''):
2705 """Remove an alias"""
2776 """Remove an alias"""
2706
2777
2707 aname = parameter_s.strip()
2778 aname = parameter_s.strip()
2708 self.shell.alias_manager.undefine_alias(aname)
2779 self.shell.alias_manager.undefine_alias(aname)
2709 stored = self.db.get('stored_aliases', {} )
2780 stored = self.db.get('stored_aliases', {} )
2710 if aname in stored:
2781 if aname in stored:
2711 print "Removing %stored alias",aname
2782 print "Removing %stored alias",aname
2712 del stored[aname]
2783 del stored[aname]
2713 self.db['stored_aliases'] = stored
2784 self.db['stored_aliases'] = stored
2714
2785
2715 def magic_rehashx(self, parameter_s = ''):
2786 def magic_rehashx(self, parameter_s = ''):
2716 """Update the alias table with all executable files in $PATH.
2787 """Update the alias table with all executable files in $PATH.
2717
2788
2718 This version explicitly checks that every entry in $PATH is a file
2789 This version explicitly checks that every entry in $PATH is a file
2719 with execute access (os.X_OK), so it is much slower than %rehash.
2790 with execute access (os.X_OK), so it is much slower than %rehash.
2720
2791
2721 Under Windows, it checks executability as a match against a
2792 Under Windows, it checks executability as a match against a
2722 '|'-separated string of extensions, stored in the IPython config
2793 '|'-separated string of extensions, stored in the IPython config
2723 variable win_exec_ext. This defaults to 'exe|com|bat'.
2794 variable win_exec_ext. This defaults to 'exe|com|bat'.
2724
2795
2725 This function also resets the root module cache of module completer,
2796 This function also resets the root module cache of module completer,
2726 used on slow filesystems.
2797 used on slow filesystems.
2727 """
2798 """
2728 from IPython.core.alias import InvalidAliasError
2799 from IPython.core.alias import InvalidAliasError
2729
2800
2730 # for the benefit of module completer in ipy_completers.py
2801 # for the benefit of module completer in ipy_completers.py
2731 del self.shell.db['rootmodules']
2802 del self.shell.db['rootmodules']
2732
2803
2733 path = [os.path.abspath(os.path.expanduser(p)) for p in
2804 path = [os.path.abspath(os.path.expanduser(p)) for p in
2734 os.environ.get('PATH','').split(os.pathsep)]
2805 os.environ.get('PATH','').split(os.pathsep)]
2735 path = filter(os.path.isdir,path)
2806 path = filter(os.path.isdir,path)
2736
2807
2737 syscmdlist = []
2808 syscmdlist = []
2738 # Now define isexec in a cross platform manner.
2809 # Now define isexec in a cross platform manner.
2739 if os.name == 'posix':
2810 if os.name == 'posix':
2740 isexec = lambda fname:os.path.isfile(fname) and \
2811 isexec = lambda fname:os.path.isfile(fname) and \
2741 os.access(fname,os.X_OK)
2812 os.access(fname,os.X_OK)
2742 else:
2813 else:
2743 try:
2814 try:
2744 winext = os.environ['pathext'].replace(';','|').replace('.','')
2815 winext = os.environ['pathext'].replace(';','|').replace('.','')
2745 except KeyError:
2816 except KeyError:
2746 winext = 'exe|com|bat|py'
2817 winext = 'exe|com|bat|py'
2747 if 'py' not in winext:
2818 if 'py' not in winext:
2748 winext += '|py'
2819 winext += '|py'
2749 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2820 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2750 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2821 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2751 savedir = os.getcwdu()
2822 savedir = os.getcwdu()
2752
2823
2753 # Now walk the paths looking for executables to alias.
2824 # Now walk the paths looking for executables to alias.
2754 try:
2825 try:
2755 # write the whole loop for posix/Windows so we don't have an if in
2826 # write the whole loop for posix/Windows so we don't have an if in
2756 # the innermost part
2827 # the innermost part
2757 if os.name == 'posix':
2828 if os.name == 'posix':
2758 for pdir in path:
2829 for pdir in path:
2759 os.chdir(pdir)
2830 os.chdir(pdir)
2760 for ff in os.listdir(pdir):
2831 for ff in os.listdir(pdir):
2761 if isexec(ff):
2832 if isexec(ff):
2762 try:
2833 try:
2763 # Removes dots from the name since ipython
2834 # Removes dots from the name since ipython
2764 # will assume names with dots to be python.
2835 # will assume names with dots to be python.
2765 self.shell.alias_manager.define_alias(
2836 self.shell.alias_manager.define_alias(
2766 ff.replace('.',''), ff)
2837 ff.replace('.',''), ff)
2767 except InvalidAliasError:
2838 except InvalidAliasError:
2768 pass
2839 pass
2769 else:
2840 else:
2770 syscmdlist.append(ff)
2841 syscmdlist.append(ff)
2771 else:
2842 else:
2772 no_alias = self.shell.alias_manager.no_alias
2843 no_alias = self.shell.alias_manager.no_alias
2773 for pdir in path:
2844 for pdir in path:
2774 os.chdir(pdir)
2845 os.chdir(pdir)
2775 for ff in os.listdir(pdir):
2846 for ff in os.listdir(pdir):
2776 base, ext = os.path.splitext(ff)
2847 base, ext = os.path.splitext(ff)
2777 if isexec(ff) and base.lower() not in no_alias:
2848 if isexec(ff) and base.lower() not in no_alias:
2778 if ext.lower() == '.exe':
2849 if ext.lower() == '.exe':
2779 ff = base
2850 ff = base
2780 try:
2851 try:
2781 # Removes dots from the name since ipython
2852 # Removes dots from the name since ipython
2782 # will assume names with dots to be python.
2853 # will assume names with dots to be python.
2783 self.shell.alias_manager.define_alias(
2854 self.shell.alias_manager.define_alias(
2784 base.lower().replace('.',''), ff)
2855 base.lower().replace('.',''), ff)
2785 except InvalidAliasError:
2856 except InvalidAliasError:
2786 pass
2857 pass
2787 syscmdlist.append(ff)
2858 syscmdlist.append(ff)
2788 self.shell.db['syscmdlist'] = syscmdlist
2859 self.shell.db['syscmdlist'] = syscmdlist
2789 finally:
2860 finally:
2790 os.chdir(savedir)
2861 os.chdir(savedir)
2791
2862
2792 @skip_doctest
2863 @skip_doctest
2793 def magic_pwd(self, parameter_s = ''):
2864 def magic_pwd(self, parameter_s = ''):
2794 """Return the current working directory path.
2865 """Return the current working directory path.
2795
2866
2796 Examples
2867 Examples
2797 --------
2868 --------
2798 ::
2869 ::
2799
2870
2800 In [9]: pwd
2871 In [9]: pwd
2801 Out[9]: '/home/tsuser/sprint/ipython'
2872 Out[9]: '/home/tsuser/sprint/ipython'
2802 """
2873 """
2803 return os.getcwdu()
2874 return os.getcwdu()
2804
2875
2805 @skip_doctest
2876 @skip_doctest
2806 def magic_cd(self, parameter_s=''):
2877 def magic_cd(self, parameter_s=''):
2807 """Change the current working directory.
2878 """Change the current working directory.
2808
2879
2809 This command automatically maintains an internal list of directories
2880 This command automatically maintains an internal list of directories
2810 you visit during your IPython session, in the variable _dh. The
2881 you visit during your IPython session, in the variable _dh. The
2811 command %dhist shows this history nicely formatted. You can also
2882 command %dhist shows this history nicely formatted. You can also
2812 do 'cd -<tab>' to see directory history conveniently.
2883 do 'cd -<tab>' to see directory history conveniently.
2813
2884
2814 Usage:
2885 Usage:
2815
2886
2816 cd 'dir': changes to directory 'dir'.
2887 cd 'dir': changes to directory 'dir'.
2817
2888
2818 cd -: changes to the last visited directory.
2889 cd -: changes to the last visited directory.
2819
2890
2820 cd -<n>: changes to the n-th directory in the directory history.
2891 cd -<n>: changes to the n-th directory in the directory history.
2821
2892
2822 cd --foo: change to directory that matches 'foo' in history
2893 cd --foo: change to directory that matches 'foo' in history
2823
2894
2824 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2895 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2825 (note: cd <bookmark_name> is enough if there is no
2896 (note: cd <bookmark_name> is enough if there is no
2826 directory <bookmark_name>, but a bookmark with the name exists.)
2897 directory <bookmark_name>, but a bookmark with the name exists.)
2827 'cd -b <tab>' allows you to tab-complete bookmark names.
2898 'cd -b <tab>' allows you to tab-complete bookmark names.
2828
2899
2829 Options:
2900 Options:
2830
2901
2831 -q: quiet. Do not print the working directory after the cd command is
2902 -q: quiet. Do not print the working directory after the cd command is
2832 executed. By default IPython's cd command does print this directory,
2903 executed. By default IPython's cd command does print this directory,
2833 since the default prompts do not display path information.
2904 since the default prompts do not display path information.
2834
2905
2835 Note that !cd doesn't work for this purpose because the shell where
2906 Note that !cd doesn't work for this purpose because the shell where
2836 !command runs is immediately discarded after executing 'command'.
2907 !command runs is immediately discarded after executing 'command'.
2837
2908
2838 Examples
2909 Examples
2839 --------
2910 --------
2840 ::
2911 ::
2841
2912
2842 In [10]: cd parent/child
2913 In [10]: cd parent/child
2843 /home/tsuser/parent/child
2914 /home/tsuser/parent/child
2844 """
2915 """
2845
2916
2846 parameter_s = parameter_s.strip()
2917 parameter_s = parameter_s.strip()
2847 #bkms = self.shell.persist.get("bookmarks",{})
2918 #bkms = self.shell.persist.get("bookmarks",{})
2848
2919
2849 oldcwd = os.getcwdu()
2920 oldcwd = os.getcwdu()
2850 numcd = re.match(r'(-)(\d+)$',parameter_s)
2921 numcd = re.match(r'(-)(\d+)$',parameter_s)
2851 # jump in directory history by number
2922 # jump in directory history by number
2852 if numcd:
2923 if numcd:
2853 nn = int(numcd.group(2))
2924 nn = int(numcd.group(2))
2854 try:
2925 try:
2855 ps = self.shell.user_ns['_dh'][nn]
2926 ps = self.shell.user_ns['_dh'][nn]
2856 except IndexError:
2927 except IndexError:
2857 print 'The requested directory does not exist in history.'
2928 print 'The requested directory does not exist in history.'
2858 return
2929 return
2859 else:
2930 else:
2860 opts = {}
2931 opts = {}
2861 elif parameter_s.startswith('--'):
2932 elif parameter_s.startswith('--'):
2862 ps = None
2933 ps = None
2863 fallback = None
2934 fallback = None
2864 pat = parameter_s[2:]
2935 pat = parameter_s[2:]
2865 dh = self.shell.user_ns['_dh']
2936 dh = self.shell.user_ns['_dh']
2866 # first search only by basename (last component)
2937 # first search only by basename (last component)
2867 for ent in reversed(dh):
2938 for ent in reversed(dh):
2868 if pat in os.path.basename(ent) and os.path.isdir(ent):
2939 if pat in os.path.basename(ent) and os.path.isdir(ent):
2869 ps = ent
2940 ps = ent
2870 break
2941 break
2871
2942
2872 if fallback is None and pat in ent and os.path.isdir(ent):
2943 if fallback is None and pat in ent and os.path.isdir(ent):
2873 fallback = ent
2944 fallback = ent
2874
2945
2875 # if we have no last part match, pick the first full path match
2946 # if we have no last part match, pick the first full path match
2876 if ps is None:
2947 if ps is None:
2877 ps = fallback
2948 ps = fallback
2878
2949
2879 if ps is None:
2950 if ps is None:
2880 print "No matching entry in directory history"
2951 print "No matching entry in directory history"
2881 return
2952 return
2882 else:
2953 else:
2883 opts = {}
2954 opts = {}
2884
2955
2885
2956
2886 else:
2957 else:
2887 #turn all non-space-escaping backslashes to slashes,
2958 #turn all non-space-escaping backslashes to slashes,
2888 # for c:\windows\directory\names\
2959 # for c:\windows\directory\names\
2889 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2960 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2890 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2961 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2891 # jump to previous
2962 # jump to previous
2892 if ps == '-':
2963 if ps == '-':
2893 try:
2964 try:
2894 ps = self.shell.user_ns['_dh'][-2]
2965 ps = self.shell.user_ns['_dh'][-2]
2895 except IndexError:
2966 except IndexError:
2896 raise UsageError('%cd -: No previous directory to change to.')
2967 raise UsageError('%cd -: No previous directory to change to.')
2897 # jump to bookmark if needed
2968 # jump to bookmark if needed
2898 else:
2969 else:
2899 if not os.path.isdir(ps) or opts.has_key('b'):
2970 if not os.path.isdir(ps) or opts.has_key('b'):
2900 bkms = self.db.get('bookmarks', {})
2971 bkms = self.db.get('bookmarks', {})
2901
2972
2902 if bkms.has_key(ps):
2973 if bkms.has_key(ps):
2903 target = bkms[ps]
2974 target = bkms[ps]
2904 print '(bookmark:%s) -> %s' % (ps,target)
2975 print '(bookmark:%s) -> %s' % (ps,target)
2905 ps = target
2976 ps = target
2906 else:
2977 else:
2907 if opts.has_key('b'):
2978 if opts.has_key('b'):
2908 raise UsageError("Bookmark '%s' not found. "
2979 raise UsageError("Bookmark '%s' not found. "
2909 "Use '%%bookmark -l' to see your bookmarks." % ps)
2980 "Use '%%bookmark -l' to see your bookmarks." % ps)
2910
2981
2911 # strip extra quotes on Windows, because os.chdir doesn't like them
2982 # strip extra quotes on Windows, because os.chdir doesn't like them
2912 ps = unquote_filename(ps)
2983 ps = unquote_filename(ps)
2913 # at this point ps should point to the target dir
2984 # at this point ps should point to the target dir
2914 if ps:
2985 if ps:
2915 try:
2986 try:
2916 os.chdir(os.path.expanduser(ps))
2987 os.chdir(os.path.expanduser(ps))
2917 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2988 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2918 set_term_title('IPython: ' + abbrev_cwd())
2989 set_term_title('IPython: ' + abbrev_cwd())
2919 except OSError:
2990 except OSError:
2920 print sys.exc_info()[1]
2991 print sys.exc_info()[1]
2921 else:
2992 else:
2922 cwd = os.getcwdu()
2993 cwd = os.getcwdu()
2923 dhist = self.shell.user_ns['_dh']
2994 dhist = self.shell.user_ns['_dh']
2924 if oldcwd != cwd:
2995 if oldcwd != cwd:
2925 dhist.append(cwd)
2996 dhist.append(cwd)
2926 self.db['dhist'] = compress_dhist(dhist)[-100:]
2997 self.db['dhist'] = compress_dhist(dhist)[-100:]
2927
2998
2928 else:
2999 else:
2929 os.chdir(self.shell.home_dir)
3000 os.chdir(self.shell.home_dir)
2930 if hasattr(self.shell, 'term_title') and self.shell.term_title:
3001 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2931 set_term_title('IPython: ' + '~')
3002 set_term_title('IPython: ' + '~')
2932 cwd = os.getcwdu()
3003 cwd = os.getcwdu()
2933 dhist = self.shell.user_ns['_dh']
3004 dhist = self.shell.user_ns['_dh']
2934
3005
2935 if oldcwd != cwd:
3006 if oldcwd != cwd:
2936 dhist.append(cwd)
3007 dhist.append(cwd)
2937 self.db['dhist'] = compress_dhist(dhist)[-100:]
3008 self.db['dhist'] = compress_dhist(dhist)[-100:]
2938 if not 'q' in opts and self.shell.user_ns['_dh']:
3009 if not 'q' in opts and self.shell.user_ns['_dh']:
2939 print self.shell.user_ns['_dh'][-1]
3010 print self.shell.user_ns['_dh'][-1]
2940
3011
2941
3012
2942 def magic_env(self, parameter_s=''):
3013 def magic_env(self, parameter_s=''):
2943 """List environment variables."""
3014 """List environment variables."""
2944
3015
2945 return os.environ.data
3016 return os.environ.data
2946
3017
2947 def magic_pushd(self, parameter_s=''):
3018 def magic_pushd(self, parameter_s=''):
2948 """Place the current dir on stack and change directory.
3019 """Place the current dir on stack and change directory.
2949
3020
2950 Usage:\\
3021 Usage:\\
2951 %pushd ['dirname']
3022 %pushd ['dirname']
2952 """
3023 """
2953
3024
2954 dir_s = self.shell.dir_stack
3025 dir_s = self.shell.dir_stack
2955 tgt = os.path.expanduser(unquote_filename(parameter_s))
3026 tgt = os.path.expanduser(unquote_filename(parameter_s))
2956 cwd = os.getcwdu().replace(self.home_dir,'~')
3027 cwd = os.getcwdu().replace(self.home_dir,'~')
2957 if tgt:
3028 if tgt:
2958 self.magic_cd(parameter_s)
3029 self.magic_cd(parameter_s)
2959 dir_s.insert(0,cwd)
3030 dir_s.insert(0,cwd)
2960 return self.magic_dirs()
3031 return self.magic_dirs()
2961
3032
2962 def magic_popd(self, parameter_s=''):
3033 def magic_popd(self, parameter_s=''):
2963 """Change to directory popped off the top of the stack.
3034 """Change to directory popped off the top of the stack.
2964 """
3035 """
2965 if not self.shell.dir_stack:
3036 if not self.shell.dir_stack:
2966 raise UsageError("%popd on empty stack")
3037 raise UsageError("%popd on empty stack")
2967 top = self.shell.dir_stack.pop(0)
3038 top = self.shell.dir_stack.pop(0)
2968 self.magic_cd(top)
3039 self.magic_cd(top)
2969 print "popd ->",top
3040 print "popd ->",top
2970
3041
2971 def magic_dirs(self, parameter_s=''):
3042 def magic_dirs(self, parameter_s=''):
2972 """Return the current directory stack."""
3043 """Return the current directory stack."""
2973
3044
2974 return self.shell.dir_stack
3045 return self.shell.dir_stack
2975
3046
2976 def magic_dhist(self, parameter_s=''):
3047 def magic_dhist(self, parameter_s=''):
2977 """Print your history of visited directories.
3048 """Print your history of visited directories.
2978
3049
2979 %dhist -> print full history\\
3050 %dhist -> print full history\\
2980 %dhist n -> print last n entries only\\
3051 %dhist n -> print last n entries only\\
2981 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
3052 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2982
3053
2983 This history is automatically maintained by the %cd command, and
3054 This history is automatically maintained by the %cd command, and
2984 always available as the global list variable _dh. You can use %cd -<n>
3055 always available as the global list variable _dh. You can use %cd -<n>
2985 to go to directory number <n>.
3056 to go to directory number <n>.
2986
3057
2987 Note that most of time, you should view directory history by entering
3058 Note that most of time, you should view directory history by entering
2988 cd -<TAB>.
3059 cd -<TAB>.
2989
3060
2990 """
3061 """
2991
3062
2992 dh = self.shell.user_ns['_dh']
3063 dh = self.shell.user_ns['_dh']
2993 if parameter_s:
3064 if parameter_s:
2994 try:
3065 try:
2995 args = map(int,parameter_s.split())
3066 args = map(int,parameter_s.split())
2996 except:
3067 except:
2997 self.arg_err(Magic.magic_dhist)
3068 self.arg_err(Magic.magic_dhist)
2998 return
3069 return
2999 if len(args) == 1:
3070 if len(args) == 1:
3000 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3071 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3001 elif len(args) == 2:
3072 elif len(args) == 2:
3002 ini,fin = args
3073 ini,fin = args
3003 else:
3074 else:
3004 self.arg_err(Magic.magic_dhist)
3075 self.arg_err(Magic.magic_dhist)
3005 return
3076 return
3006 else:
3077 else:
3007 ini,fin = 0,len(dh)
3078 ini,fin = 0,len(dh)
3008 nlprint(dh,
3079 nlprint(dh,
3009 header = 'Directory history (kept in _dh)',
3080 header = 'Directory history (kept in _dh)',
3010 start=ini,stop=fin)
3081 start=ini,stop=fin)
3011
3082
3012 @skip_doctest
3083 @skip_doctest
3013 def magic_sc(self, parameter_s=''):
3084 def magic_sc(self, parameter_s=''):
3014 """Shell capture - execute a shell command and capture its output.
3085 """Shell capture - execute a shell command and capture its output.
3015
3086
3016 DEPRECATED. Suboptimal, retained for backwards compatibility.
3087 DEPRECATED. Suboptimal, retained for backwards compatibility.
3017
3088
3018 You should use the form 'var = !command' instead. Example:
3089 You should use the form 'var = !command' instead. Example:
3019
3090
3020 "%sc -l myfiles = ls ~" should now be written as
3091 "%sc -l myfiles = ls ~" should now be written as
3021
3092
3022 "myfiles = !ls ~"
3093 "myfiles = !ls ~"
3023
3094
3024 myfiles.s, myfiles.l and myfiles.n still apply as documented
3095 myfiles.s, myfiles.l and myfiles.n still apply as documented
3025 below.
3096 below.
3026
3097
3027 --
3098 --
3028 %sc [options] varname=command
3099 %sc [options] varname=command
3029
3100
3030 IPython will run the given command using commands.getoutput(), and
3101 IPython will run the given command using commands.getoutput(), and
3031 will then update the user's interactive namespace with a variable
3102 will then update the user's interactive namespace with a variable
3032 called varname, containing the value of the call. Your command can
3103 called varname, containing the value of the call. Your command can
3033 contain shell wildcards, pipes, etc.
3104 contain shell wildcards, pipes, etc.
3034
3105
3035 The '=' sign in the syntax is mandatory, and the variable name you
3106 The '=' sign in the syntax is mandatory, and the variable name you
3036 supply must follow Python's standard conventions for valid names.
3107 supply must follow Python's standard conventions for valid names.
3037
3108
3038 (A special format without variable name exists for internal use)
3109 (A special format without variable name exists for internal use)
3039
3110
3040 Options:
3111 Options:
3041
3112
3042 -l: list output. Split the output on newlines into a list before
3113 -l: list output. Split the output on newlines into a list before
3043 assigning it to the given variable. By default the output is stored
3114 assigning it to the given variable. By default the output is stored
3044 as a single string.
3115 as a single string.
3045
3116
3046 -v: verbose. Print the contents of the variable.
3117 -v: verbose. Print the contents of the variable.
3047
3118
3048 In most cases you should not need to split as a list, because the
3119 In most cases you should not need to split as a list, because the
3049 returned value is a special type of string which can automatically
3120 returned value is a special type of string which can automatically
3050 provide its contents either as a list (split on newlines) or as a
3121 provide its contents either as a list (split on newlines) or as a
3051 space-separated string. These are convenient, respectively, either
3122 space-separated string. These are convenient, respectively, either
3052 for sequential processing or to be passed to a shell command.
3123 for sequential processing or to be passed to a shell command.
3053
3124
3054 For example:
3125 For example:
3055
3126
3056 # all-random
3127 # all-random
3057
3128
3058 # Capture into variable a
3129 # Capture into variable a
3059 In [1]: sc a=ls *py
3130 In [1]: sc a=ls *py
3060
3131
3061 # a is a string with embedded newlines
3132 # a is a string with embedded newlines
3062 In [2]: a
3133 In [2]: a
3063 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3134 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3064
3135
3065 # which can be seen as a list:
3136 # which can be seen as a list:
3066 In [3]: a.l
3137 In [3]: a.l
3067 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3138 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3068
3139
3069 # or as a whitespace-separated string:
3140 # or as a whitespace-separated string:
3070 In [4]: a.s
3141 In [4]: a.s
3071 Out[4]: 'setup.py win32_manual_post_install.py'
3142 Out[4]: 'setup.py win32_manual_post_install.py'
3072
3143
3073 # a.s is useful to pass as a single command line:
3144 # a.s is useful to pass as a single command line:
3074 In [5]: !wc -l $a.s
3145 In [5]: !wc -l $a.s
3075 146 setup.py
3146 146 setup.py
3076 130 win32_manual_post_install.py
3147 130 win32_manual_post_install.py
3077 276 total
3148 276 total
3078
3149
3079 # while the list form is useful to loop over:
3150 # while the list form is useful to loop over:
3080 In [6]: for f in a.l:
3151 In [6]: for f in a.l:
3081 ...: !wc -l $f
3152 ...: !wc -l $f
3082 ...:
3153 ...:
3083 146 setup.py
3154 146 setup.py
3084 130 win32_manual_post_install.py
3155 130 win32_manual_post_install.py
3085
3156
3086 Similarly, the lists returned by the -l option are also special, in
3157 Similarly, the lists returned by the -l option are also special, in
3087 the sense that you can equally invoke the .s attribute on them to
3158 the sense that you can equally invoke the .s attribute on them to
3088 automatically get a whitespace-separated string from their contents:
3159 automatically get a whitespace-separated string from their contents:
3089
3160
3090 In [7]: sc -l b=ls *py
3161 In [7]: sc -l b=ls *py
3091
3162
3092 In [8]: b
3163 In [8]: b
3093 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3164 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3094
3165
3095 In [9]: b.s
3166 In [9]: b.s
3096 Out[9]: 'setup.py win32_manual_post_install.py'
3167 Out[9]: 'setup.py win32_manual_post_install.py'
3097
3168
3098 In summary, both the lists and strings used for output capture have
3169 In summary, both the lists and strings used for output capture have
3099 the following special attributes:
3170 the following special attributes:
3100
3171
3101 .l (or .list) : value as list.
3172 .l (or .list) : value as list.
3102 .n (or .nlstr): value as newline-separated string.
3173 .n (or .nlstr): value as newline-separated string.
3103 .s (or .spstr): value as space-separated string.
3174 .s (or .spstr): value as space-separated string.
3104 """
3175 """
3105
3176
3106 opts,args = self.parse_options(parameter_s,'lv')
3177 opts,args = self.parse_options(parameter_s,'lv')
3107 # Try to get a variable name and command to run
3178 # Try to get a variable name and command to run
3108 try:
3179 try:
3109 # the variable name must be obtained from the parse_options
3180 # the variable name must be obtained from the parse_options
3110 # output, which uses shlex.split to strip options out.
3181 # output, which uses shlex.split to strip options out.
3111 var,_ = args.split('=',1)
3182 var,_ = args.split('=',1)
3112 var = var.strip()
3183 var = var.strip()
3113 # But the command has to be extracted from the original input
3184 # But the command has to be extracted from the original input
3114 # parameter_s, not on what parse_options returns, to avoid the
3185 # parameter_s, not on what parse_options returns, to avoid the
3115 # quote stripping which shlex.split performs on it.
3186 # quote stripping which shlex.split performs on it.
3116 _,cmd = parameter_s.split('=',1)
3187 _,cmd = parameter_s.split('=',1)
3117 except ValueError:
3188 except ValueError:
3118 var,cmd = '',''
3189 var,cmd = '',''
3119 # If all looks ok, proceed
3190 # If all looks ok, proceed
3120 split = 'l' in opts
3191 split = 'l' in opts
3121 out = self.shell.getoutput(cmd, split=split)
3192 out = self.shell.getoutput(cmd, split=split)
3122 if opts.has_key('v'):
3193 if opts.has_key('v'):
3123 print '%s ==\n%s' % (var,pformat(out))
3194 print '%s ==\n%s' % (var,pformat(out))
3124 if var:
3195 if var:
3125 self.shell.user_ns.update({var:out})
3196 self.shell.user_ns.update({var:out})
3126 else:
3197 else:
3127 return out
3198 return out
3128
3199
3129 def magic_sx(self, parameter_s=''):
3200 def magic_sx(self, parameter_s=''):
3130 """Shell execute - run a shell command and capture its output.
3201 """Shell execute - run a shell command and capture its output.
3131
3202
3132 %sx command
3203 %sx command
3133
3204
3134 IPython will run the given command using commands.getoutput(), and
3205 IPython will run the given command using commands.getoutput(), and
3135 return the result formatted as a list (split on '\\n'). Since the
3206 return the result formatted as a list (split on '\\n'). Since the
3136 output is _returned_, it will be stored in ipython's regular output
3207 output is _returned_, it will be stored in ipython's regular output
3137 cache Out[N] and in the '_N' automatic variables.
3208 cache Out[N] and in the '_N' automatic variables.
3138
3209
3139 Notes:
3210 Notes:
3140
3211
3141 1) If an input line begins with '!!', then %sx is automatically
3212 1) If an input line begins with '!!', then %sx is automatically
3142 invoked. That is, while:
3213 invoked. That is, while:
3143 !ls
3214 !ls
3144 causes ipython to simply issue system('ls'), typing
3215 causes ipython to simply issue system('ls'), typing
3145 !!ls
3216 !!ls
3146 is a shorthand equivalent to:
3217 is a shorthand equivalent to:
3147 %sx ls
3218 %sx ls
3148
3219
3149 2) %sx differs from %sc in that %sx automatically splits into a list,
3220 2) %sx differs from %sc in that %sx automatically splits into a list,
3150 like '%sc -l'. The reason for this is to make it as easy as possible
3221 like '%sc -l'. The reason for this is to make it as easy as possible
3151 to process line-oriented shell output via further python commands.
3222 to process line-oriented shell output via further python commands.
3152 %sc is meant to provide much finer control, but requires more
3223 %sc is meant to provide much finer control, but requires more
3153 typing.
3224 typing.
3154
3225
3155 3) Just like %sc -l, this is a list with special attributes:
3226 3) Just like %sc -l, this is a list with special attributes:
3156
3227
3157 .l (or .list) : value as list.
3228 .l (or .list) : value as list.
3158 .n (or .nlstr): value as newline-separated string.
3229 .n (or .nlstr): value as newline-separated string.
3159 .s (or .spstr): value as whitespace-separated string.
3230 .s (or .spstr): value as whitespace-separated string.
3160
3231
3161 This is very useful when trying to use such lists as arguments to
3232 This is very useful when trying to use such lists as arguments to
3162 system commands."""
3233 system commands."""
3163
3234
3164 if parameter_s:
3235 if parameter_s:
3165 return self.shell.getoutput(parameter_s)
3236 return self.shell.getoutput(parameter_s)
3166
3237
3167
3238
3168 def magic_bookmark(self, parameter_s=''):
3239 def magic_bookmark(self, parameter_s=''):
3169 """Manage IPython's bookmark system.
3240 """Manage IPython's bookmark system.
3170
3241
3171 %bookmark <name> - set bookmark to current dir
3242 %bookmark <name> - set bookmark to current dir
3172 %bookmark <name> <dir> - set bookmark to <dir>
3243 %bookmark <name> <dir> - set bookmark to <dir>
3173 %bookmark -l - list all bookmarks
3244 %bookmark -l - list all bookmarks
3174 %bookmark -d <name> - remove bookmark
3245 %bookmark -d <name> - remove bookmark
3175 %bookmark -r - remove all bookmarks
3246 %bookmark -r - remove all bookmarks
3176
3247
3177 You can later on access a bookmarked folder with:
3248 You can later on access a bookmarked folder with:
3178 %cd -b <name>
3249 %cd -b <name>
3179 or simply '%cd <name>' if there is no directory called <name> AND
3250 or simply '%cd <name>' if there is no directory called <name> AND
3180 there is such a bookmark defined.
3251 there is such a bookmark defined.
3181
3252
3182 Your bookmarks persist through IPython sessions, but they are
3253 Your bookmarks persist through IPython sessions, but they are
3183 associated with each profile."""
3254 associated with each profile."""
3184
3255
3185 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3256 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3186 if len(args) > 2:
3257 if len(args) > 2:
3187 raise UsageError("%bookmark: too many arguments")
3258 raise UsageError("%bookmark: too many arguments")
3188
3259
3189 bkms = self.db.get('bookmarks',{})
3260 bkms = self.db.get('bookmarks',{})
3190
3261
3191 if opts.has_key('d'):
3262 if opts.has_key('d'):
3192 try:
3263 try:
3193 todel = args[0]
3264 todel = args[0]
3194 except IndexError:
3265 except IndexError:
3195 raise UsageError(
3266 raise UsageError(
3196 "%bookmark -d: must provide a bookmark to delete")
3267 "%bookmark -d: must provide a bookmark to delete")
3197 else:
3268 else:
3198 try:
3269 try:
3199 del bkms[todel]
3270 del bkms[todel]
3200 except KeyError:
3271 except KeyError:
3201 raise UsageError(
3272 raise UsageError(
3202 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3273 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3203
3274
3204 elif opts.has_key('r'):
3275 elif opts.has_key('r'):
3205 bkms = {}
3276 bkms = {}
3206 elif opts.has_key('l'):
3277 elif opts.has_key('l'):
3207 bks = bkms.keys()
3278 bks = bkms.keys()
3208 bks.sort()
3279 bks.sort()
3209 if bks:
3280 if bks:
3210 size = max(map(len,bks))
3281 size = max(map(len,bks))
3211 else:
3282 else:
3212 size = 0
3283 size = 0
3213 fmt = '%-'+str(size)+'s -> %s'
3284 fmt = '%-'+str(size)+'s -> %s'
3214 print 'Current bookmarks:'
3285 print 'Current bookmarks:'
3215 for bk in bks:
3286 for bk in bks:
3216 print fmt % (bk,bkms[bk])
3287 print fmt % (bk,bkms[bk])
3217 else:
3288 else:
3218 if not args:
3289 if not args:
3219 raise UsageError("%bookmark: You must specify the bookmark name")
3290 raise UsageError("%bookmark: You must specify the bookmark name")
3220 elif len(args)==1:
3291 elif len(args)==1:
3221 bkms[args[0]] = os.getcwdu()
3292 bkms[args[0]] = os.getcwdu()
3222 elif len(args)==2:
3293 elif len(args)==2:
3223 bkms[args[0]] = args[1]
3294 bkms[args[0]] = args[1]
3224 self.db['bookmarks'] = bkms
3295 self.db['bookmarks'] = bkms
3225
3296
3226 def magic_pycat(self, parameter_s=''):
3297 def magic_pycat(self, parameter_s=''):
3227 """Show a syntax-highlighted file through a pager.
3298 """Show a syntax-highlighted file through a pager.
3228
3299
3229 This magic is similar to the cat utility, but it will assume the file
3300 This magic is similar to the cat utility, but it will assume the file
3230 to be Python source and will show it with syntax highlighting. """
3301 to be Python source and will show it with syntax highlighting. """
3231
3302
3232 try:
3303 try:
3233 filename = get_py_filename(parameter_s)
3304 filename = get_py_filename(parameter_s)
3234 cont = file_read(filename)
3305 cont = file_read(filename)
3235 except IOError:
3306 except IOError:
3236 try:
3307 try:
3237 cont = eval(parameter_s,self.user_ns)
3308 cont = eval(parameter_s,self.user_ns)
3238 except NameError:
3309 except NameError:
3239 cont = None
3310 cont = None
3240 if cont is None:
3311 if cont is None:
3241 print "Error: no such file or variable"
3312 print "Error: no such file or variable"
3242 return
3313 return
3243
3314
3244 page.page(self.shell.pycolorize(cont))
3315 page.page(self.shell.pycolorize(cont))
3245
3316
3246 def magic_quickref(self,arg):
3317 def magic_quickref(self,arg):
3247 """ Show a quick reference sheet """
3318 """ Show a quick reference sheet """
3248 import IPython.core.usage
3319 import IPython.core.usage
3249 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3320 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3250
3321
3251 page.page(qr)
3322 page.page(qr)
3252
3323
3253 def magic_doctest_mode(self,parameter_s=''):
3324 def magic_doctest_mode(self,parameter_s=''):
3254 """Toggle doctest mode on and off.
3325 """Toggle doctest mode on and off.
3255
3326
3256 This mode is intended to make IPython behave as much as possible like a
3327 This mode is intended to make IPython behave as much as possible like a
3257 plain Python shell, from the perspective of how its prompts, exceptions
3328 plain Python shell, from the perspective of how its prompts, exceptions
3258 and output look. This makes it easy to copy and paste parts of a
3329 and output look. This makes it easy to copy and paste parts of a
3259 session into doctests. It does so by:
3330 session into doctests. It does so by:
3260
3331
3261 - Changing the prompts to the classic ``>>>`` ones.
3332 - Changing the prompts to the classic ``>>>`` ones.
3262 - Changing the exception reporting mode to 'Plain'.
3333 - Changing the exception reporting mode to 'Plain'.
3263 - Disabling pretty-printing of output.
3334 - Disabling pretty-printing of output.
3264
3335
3265 Note that IPython also supports the pasting of code snippets that have
3336 Note that IPython also supports the pasting of code snippets that have
3266 leading '>>>' and '...' prompts in them. This means that you can paste
3337 leading '>>>' and '...' prompts in them. This means that you can paste
3267 doctests from files or docstrings (even if they have leading
3338 doctests from files or docstrings (even if they have leading
3268 whitespace), and the code will execute correctly. You can then use
3339 whitespace), and the code will execute correctly. You can then use
3269 '%history -t' to see the translated history; this will give you the
3340 '%history -t' to see the translated history; this will give you the
3270 input after removal of all the leading prompts and whitespace, which
3341 input after removal of all the leading prompts and whitespace, which
3271 can be pasted back into an editor.
3342 can be pasted back into an editor.
3272
3343
3273 With these features, you can switch into this mode easily whenever you
3344 With these features, you can switch into this mode easily whenever you
3274 need to do testing and changes to doctests, without having to leave
3345 need to do testing and changes to doctests, without having to leave
3275 your existing IPython session.
3346 your existing IPython session.
3276 """
3347 """
3277
3348
3278 from IPython.utils.ipstruct import Struct
3349 from IPython.utils.ipstruct import Struct
3279
3350
3280 # Shorthands
3351 # Shorthands
3281 shell = self.shell
3352 shell = self.shell
3282 pm = shell.prompt_manager
3353 pm = shell.prompt_manager
3283 meta = shell.meta
3354 meta = shell.meta
3284 disp_formatter = self.shell.display_formatter
3355 disp_formatter = self.shell.display_formatter
3285 ptformatter = disp_formatter.formatters['text/plain']
3356 ptformatter = disp_formatter.formatters['text/plain']
3286 # dstore is a data store kept in the instance metadata bag to track any
3357 # dstore is a data store kept in the instance metadata bag to track any
3287 # changes we make, so we can undo them later.
3358 # changes we make, so we can undo them later.
3288 dstore = meta.setdefault('doctest_mode',Struct())
3359 dstore = meta.setdefault('doctest_mode',Struct())
3289 save_dstore = dstore.setdefault
3360 save_dstore = dstore.setdefault
3290
3361
3291 # save a few values we'll need to recover later
3362 # save a few values we'll need to recover later
3292 mode = save_dstore('mode',False)
3363 mode = save_dstore('mode',False)
3293 save_dstore('rc_pprint',ptformatter.pprint)
3364 save_dstore('rc_pprint',ptformatter.pprint)
3294 save_dstore('xmode',shell.InteractiveTB.mode)
3365 save_dstore('xmode',shell.InteractiveTB.mode)
3295 save_dstore('rc_separate_out',shell.separate_out)
3366 save_dstore('rc_separate_out',shell.separate_out)
3296 save_dstore('rc_separate_out2',shell.separate_out2)
3367 save_dstore('rc_separate_out2',shell.separate_out2)
3297 save_dstore('rc_prompts_pad_left',pm.justify)
3368 save_dstore('rc_prompts_pad_left',pm.justify)
3298 save_dstore('rc_separate_in',shell.separate_in)
3369 save_dstore('rc_separate_in',shell.separate_in)
3299 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3370 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3300 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3371 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3301
3372
3302 if mode == False:
3373 if mode == False:
3303 # turn on
3374 # turn on
3304 pm.in_template = '>>> '
3375 pm.in_template = '>>> '
3305 pm.in2_template = '... '
3376 pm.in2_template = '... '
3306 pm.out_template = ''
3377 pm.out_template = ''
3307
3378
3308 # Prompt separators like plain python
3379 # Prompt separators like plain python
3309 shell.separate_in = ''
3380 shell.separate_in = ''
3310 shell.separate_out = ''
3381 shell.separate_out = ''
3311 shell.separate_out2 = ''
3382 shell.separate_out2 = ''
3312
3383
3313 pm.justify = False
3384 pm.justify = False
3314
3385
3315 ptformatter.pprint = False
3386 ptformatter.pprint = False
3316 disp_formatter.plain_text_only = True
3387 disp_formatter.plain_text_only = True
3317
3388
3318 shell.magic_xmode('Plain')
3389 shell.magic_xmode('Plain')
3319 else:
3390 else:
3320 # turn off
3391 # turn off
3321 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3392 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3322
3393
3323 shell.separate_in = dstore.rc_separate_in
3394 shell.separate_in = dstore.rc_separate_in
3324
3395
3325 shell.separate_out = dstore.rc_separate_out
3396 shell.separate_out = dstore.rc_separate_out
3326 shell.separate_out2 = dstore.rc_separate_out2
3397 shell.separate_out2 = dstore.rc_separate_out2
3327
3398
3328 pm.justify = dstore.rc_prompts_pad_left
3399 pm.justify = dstore.rc_prompts_pad_left
3329
3400
3330 ptformatter.pprint = dstore.rc_pprint
3401 ptformatter.pprint = dstore.rc_pprint
3331 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3402 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3332
3403
3333 shell.magic_xmode(dstore.xmode)
3404 shell.magic_xmode(dstore.xmode)
3334
3405
3335 # Store new mode and inform
3406 # Store new mode and inform
3336 dstore.mode = bool(1-int(mode))
3407 dstore.mode = bool(1-int(mode))
3337 mode_label = ['OFF','ON'][dstore.mode]
3408 mode_label = ['OFF','ON'][dstore.mode]
3338 print 'Doctest mode is:', mode_label
3409 print 'Doctest mode is:', mode_label
3339
3410
3340 def magic_gui(self, parameter_s=''):
3411 def magic_gui(self, parameter_s=''):
3341 """Enable or disable IPython GUI event loop integration.
3412 """Enable or disable IPython GUI event loop integration.
3342
3413
3343 %gui [GUINAME]
3414 %gui [GUINAME]
3344
3415
3345 This magic replaces IPython's threaded shells that were activated
3416 This magic replaces IPython's threaded shells that were activated
3346 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3417 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3347 can now be enabled at runtime and keyboard
3418 can now be enabled at runtime and keyboard
3348 interrupts should work without any problems. The following toolkits
3419 interrupts should work without any problems. The following toolkits
3349 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3420 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3350
3421
3351 %gui wx # enable wxPython event loop integration
3422 %gui wx # enable wxPython event loop integration
3352 %gui qt4|qt # enable PyQt4 event loop integration
3423 %gui qt4|qt # enable PyQt4 event loop integration
3353 %gui gtk # enable PyGTK event loop integration
3424 %gui gtk # enable PyGTK event loop integration
3354 %gui tk # enable Tk event loop integration
3425 %gui tk # enable Tk event loop integration
3355 %gui OSX # enable Cocoa event loop integration
3426 %gui OSX # enable Cocoa event loop integration
3356 # (requires %matplotlib 1.1)
3427 # (requires %matplotlib 1.1)
3357 %gui # disable all event loop integration
3428 %gui # disable all event loop integration
3358
3429
3359 WARNING: after any of these has been called you can simply create
3430 WARNING: after any of these has been called you can simply create
3360 an application object, but DO NOT start the event loop yourself, as
3431 an application object, but DO NOT start the event loop yourself, as
3361 we have already handled that.
3432 we have already handled that.
3362 """
3433 """
3363 opts, arg = self.parse_options(parameter_s, '')
3434 opts, arg = self.parse_options(parameter_s, '')
3364 if arg=='': arg = None
3435 if arg=='': arg = None
3365 try:
3436 try:
3366 return self.enable_gui(arg)
3437 return self.enable_gui(arg)
3367 except Exception as e:
3438 except Exception as e:
3368 # print simple error message, rather than traceback if we can't
3439 # print simple error message, rather than traceback if we can't
3369 # hook up the GUI
3440 # hook up the GUI
3370 error(str(e))
3441 error(str(e))
3371
3442
3372 def magic_load_ext(self, module_str):
3443 def magic_load_ext(self, module_str):
3373 """Load an IPython extension by its module name."""
3444 """Load an IPython extension by its module name."""
3374 return self.extension_manager.load_extension(module_str)
3445 return self.extension_manager.load_extension(module_str)
3375
3446
3376 def magic_unload_ext(self, module_str):
3447 def magic_unload_ext(self, module_str):
3377 """Unload an IPython extension by its module name."""
3448 """Unload an IPython extension by its module name."""
3378 self.extension_manager.unload_extension(module_str)
3449 self.extension_manager.unload_extension(module_str)
3379
3450
3380 def magic_reload_ext(self, module_str):
3451 def magic_reload_ext(self, module_str):
3381 """Reload an IPython extension by its module name."""
3452 """Reload an IPython extension by its module name."""
3382 self.extension_manager.reload_extension(module_str)
3453 self.extension_manager.reload_extension(module_str)
3383
3454
3384 def magic_install_profiles(self, s):
3455 def magic_install_profiles(self, s):
3385 """%install_profiles has been deprecated."""
3456 """%install_profiles has been deprecated."""
3386 print '\n'.join([
3457 print '\n'.join([
3387 "%install_profiles has been deprecated.",
3458 "%install_profiles has been deprecated.",
3388 "Use `ipython profile list` to view available profiles.",
3459 "Use `ipython profile list` to view available profiles.",
3389 "Requesting a profile with `ipython profile create <name>`",
3460 "Requesting a profile with `ipython profile create <name>`",
3390 "or `ipython --profile=<name>` will start with the bundled",
3461 "or `ipython --profile=<name>` will start with the bundled",
3391 "profile of that name if it exists."
3462 "profile of that name if it exists."
3392 ])
3463 ])
3393
3464
3394 def magic_install_default_config(self, s):
3465 def magic_install_default_config(self, s):
3395 """%install_default_config has been deprecated."""
3466 """%install_default_config has been deprecated."""
3396 print '\n'.join([
3467 print '\n'.join([
3397 "%install_default_config has been deprecated.",
3468 "%install_default_config has been deprecated.",
3398 "Use `ipython profile create <name>` to initialize a profile",
3469 "Use `ipython profile create <name>` to initialize a profile",
3399 "with the default config files.",
3470 "with the default config files.",
3400 "Add `--reset` to overwrite already existing config files with defaults."
3471 "Add `--reset` to overwrite already existing config files with defaults."
3401 ])
3472 ])
3402
3473
3403 # Pylab support: simple wrappers that activate pylab, load gui input
3474 # Pylab support: simple wrappers that activate pylab, load gui input
3404 # handling and modify slightly %run
3475 # handling and modify slightly %run
3405
3476
3406 @skip_doctest
3477 @skip_doctest
3407 def _pylab_magic_run(self, parameter_s=''):
3478 def _pylab_magic_run(self, parameter_s=''):
3408 Magic.magic_run(self, parameter_s,
3479 Magic.magic_run(self, parameter_s,
3409 runner=mpl_runner(self.shell.safe_execfile))
3480 runner=mpl_runner(self.shell.safe_execfile))
3410
3481
3411 _pylab_magic_run.__doc__ = magic_run.__doc__
3482 _pylab_magic_run.__doc__ = magic_run.__doc__
3412
3483
3413 @skip_doctest
3484 @skip_doctest
3414 def magic_pylab(self, s):
3485 def magic_pylab(self, s):
3415 """Load numpy and matplotlib to work interactively.
3486 """Load numpy and matplotlib to work interactively.
3416
3487
3417 %pylab [GUINAME]
3488 %pylab [GUINAME]
3418
3489
3419 This function lets you activate pylab (matplotlib, numpy and
3490 This function lets you activate pylab (matplotlib, numpy and
3420 interactive support) at any point during an IPython session.
3491 interactive support) at any point during an IPython session.
3421
3492
3422 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3493 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3423 pylab and mlab, as well as all names from numpy and pylab.
3494 pylab and mlab, as well as all names from numpy and pylab.
3424
3495
3425 If you are using the inline matplotlib backend for embedded figures,
3496 If you are using the inline matplotlib backend for embedded figures,
3426 you can adjust its behavior via the %config magic::
3497 you can adjust its behavior via the %config magic::
3427
3498
3428 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3499 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3429 In [1]: %config InlineBackend.figure_format = 'svg'
3500 In [1]: %config InlineBackend.figure_format = 'svg'
3430
3501
3431 # change the behavior of closing all figures at the end of each
3502 # change the behavior of closing all figures at the end of each
3432 # execution (cell), or allowing reuse of active figures across
3503 # execution (cell), or allowing reuse of active figures across
3433 # cells:
3504 # cells:
3434 In [2]: %config InlineBackend.close_figures = False
3505 In [2]: %config InlineBackend.close_figures = False
3435
3506
3436 Parameters
3507 Parameters
3437 ----------
3508 ----------
3438 guiname : optional
3509 guiname : optional
3439 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3510 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3440 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3511 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3441 used, otherwise matplotlib's default (which you can override in your
3512 used, otherwise matplotlib's default (which you can override in your
3442 matplotlib config file) is used.
3513 matplotlib config file) is used.
3443
3514
3444 Examples
3515 Examples
3445 --------
3516 --------
3446 In this case, where the MPL default is TkAgg::
3517 In this case, where the MPL default is TkAgg::
3447
3518
3448 In [2]: %pylab
3519 In [2]: %pylab
3449
3520
3450 Welcome to pylab, a matplotlib-based Python environment.
3521 Welcome to pylab, a matplotlib-based Python environment.
3451 Backend in use: TkAgg
3522 Backend in use: TkAgg
3452 For more information, type 'help(pylab)'.
3523 For more information, type 'help(pylab)'.
3453
3524
3454 But you can explicitly request a different backend::
3525 But you can explicitly request a different backend::
3455
3526
3456 In [3]: %pylab qt
3527 In [3]: %pylab qt
3457
3528
3458 Welcome to pylab, a matplotlib-based Python environment.
3529 Welcome to pylab, a matplotlib-based Python environment.
3459 Backend in use: Qt4Agg
3530 Backend in use: Qt4Agg
3460 For more information, type 'help(pylab)'.
3531 For more information, type 'help(pylab)'.
3461 """
3532 """
3462
3533
3463 if Application.initialized():
3534 if Application.initialized():
3464 app = Application.instance()
3535 app = Application.instance()
3465 try:
3536 try:
3466 import_all_status = app.pylab_import_all
3537 import_all_status = app.pylab_import_all
3467 except AttributeError:
3538 except AttributeError:
3468 import_all_status = True
3539 import_all_status = True
3469 else:
3540 else:
3470 import_all_status = True
3541 import_all_status = True
3471
3542
3472 self.shell.enable_pylab(s, import_all=import_all_status)
3543 self.shell.enable_pylab(s, import_all=import_all_status)
3473
3544
3474 def magic_tb(self, s):
3545 def magic_tb(self, s):
3475 """Print the last traceback with the currently active exception mode.
3546 """Print the last traceback with the currently active exception mode.
3476
3547
3477 See %xmode for changing exception reporting modes."""
3548 See %xmode for changing exception reporting modes."""
3478 self.shell.showtraceback()
3549 self.shell.showtraceback()
3479
3550
3480 @skip_doctest
3551 @skip_doctest
3481 def magic_precision(self, s=''):
3552 def magic_precision(self, s=''):
3482 """Set floating point precision for pretty printing.
3553 """Set floating point precision for pretty printing.
3483
3554
3484 Can set either integer precision or a format string.
3555 Can set either integer precision or a format string.
3485
3556
3486 If numpy has been imported and precision is an int,
3557 If numpy has been imported and precision is an int,
3487 numpy display precision will also be set, via ``numpy.set_printoptions``.
3558 numpy display precision will also be set, via ``numpy.set_printoptions``.
3488
3559
3489 If no argument is given, defaults will be restored.
3560 If no argument is given, defaults will be restored.
3490
3561
3491 Examples
3562 Examples
3492 --------
3563 --------
3493 ::
3564 ::
3494
3565
3495 In [1]: from math import pi
3566 In [1]: from math import pi
3496
3567
3497 In [2]: %precision 3
3568 In [2]: %precision 3
3498 Out[2]: u'%.3f'
3569 Out[2]: u'%.3f'
3499
3570
3500 In [3]: pi
3571 In [3]: pi
3501 Out[3]: 3.142
3572 Out[3]: 3.142
3502
3573
3503 In [4]: %precision %i
3574 In [4]: %precision %i
3504 Out[4]: u'%i'
3575 Out[4]: u'%i'
3505
3576
3506 In [5]: pi
3577 In [5]: pi
3507 Out[5]: 3
3578 Out[5]: 3
3508
3579
3509 In [6]: %precision %e
3580 In [6]: %precision %e
3510 Out[6]: u'%e'
3581 Out[6]: u'%e'
3511
3582
3512 In [7]: pi**10
3583 In [7]: pi**10
3513 Out[7]: 9.364805e+04
3584 Out[7]: 9.364805e+04
3514
3585
3515 In [8]: %precision
3586 In [8]: %precision
3516 Out[8]: u'%r'
3587 Out[8]: u'%r'
3517
3588
3518 In [9]: pi**10
3589 In [9]: pi**10
3519 Out[9]: 93648.047476082982
3590 Out[9]: 93648.047476082982
3520
3591
3521 """
3592 """
3522
3593
3523 ptformatter = self.shell.display_formatter.formatters['text/plain']
3594 ptformatter = self.shell.display_formatter.formatters['text/plain']
3524 ptformatter.float_precision = s
3595 ptformatter.float_precision = s
3525 return ptformatter.float_format
3596 return ptformatter.float_format
3526
3597
3527
3598
3528 @magic_arguments.magic_arguments()
3599 @magic_arguments.magic_arguments()
3529 @magic_arguments.argument(
3600 @magic_arguments.argument(
3530 '-e', '--export', action='store_true', default=False,
3601 '-e', '--export', action='store_true', default=False,
3531 help='Export IPython history as a notebook. The filename argument '
3602 help='Export IPython history as a notebook. The filename argument '
3532 'is used to specify the notebook name and format. For example '
3603 'is used to specify the notebook name and format. For example '
3533 'a filename of notebook.ipynb will result in a notebook name '
3604 'a filename of notebook.ipynb will result in a notebook name '
3534 'of "notebook" and a format of "xml". Likewise using a ".json" '
3605 'of "notebook" and a format of "xml". Likewise using a ".json" '
3535 'or ".py" file extension will write the notebook in the json '
3606 'or ".py" file extension will write the notebook in the json '
3536 'or py formats.'
3607 'or py formats.'
3537 )
3608 )
3538 @magic_arguments.argument(
3609 @magic_arguments.argument(
3539 '-f', '--format',
3610 '-f', '--format',
3540 help='Convert an existing IPython notebook to a new format. This option '
3611 help='Convert an existing IPython notebook to a new format. This option '
3541 'specifies the new format and can have the values: xml, json, py. '
3612 'specifies the new format and can have the values: xml, json, py. '
3542 'The target filename is chosen automatically based on the new '
3613 'The target filename is chosen automatically based on the new '
3543 'format. The filename argument gives the name of the source file.'
3614 'format. The filename argument gives the name of the source file.'
3544 )
3615 )
3545 @magic_arguments.argument(
3616 @magic_arguments.argument(
3546 'filename', type=unicode,
3617 'filename', type=unicode,
3547 help='Notebook name or filename'
3618 help='Notebook name or filename'
3548 )
3619 )
3549 def magic_notebook(self, s):
3620 def magic_notebook(self, s):
3550 """Export and convert IPython notebooks.
3621 """Export and convert IPython notebooks.
3551
3622
3552 This function can export the current IPython history to a notebook file
3623 This function can export the current IPython history to a notebook file
3553 or can convert an existing notebook file into a different format. For
3624 or can convert an existing notebook file into a different format. For
3554 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3625 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3555 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3626 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3556 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3627 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3557 formats include (json/ipynb, py).
3628 formats include (json/ipynb, py).
3558 """
3629 """
3559 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3630 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3560
3631
3561 from IPython.nbformat import current
3632 from IPython.nbformat import current
3562 args.filename = unquote_filename(args.filename)
3633 args.filename = unquote_filename(args.filename)
3563 if args.export:
3634 if args.export:
3564 fname, name, format = current.parse_filename(args.filename)
3635 fname, name, format = current.parse_filename(args.filename)
3565 cells = []
3636 cells = []
3566 hist = list(self.history_manager.get_range())
3637 hist = list(self.history_manager.get_range())
3567 for session, prompt_number, input in hist[:-1]:
3638 for session, prompt_number, input in hist[:-1]:
3568 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3639 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3569 worksheet = current.new_worksheet(cells=cells)
3640 worksheet = current.new_worksheet(cells=cells)
3570 nb = current.new_notebook(name=name,worksheets=[worksheet])
3641 nb = current.new_notebook(name=name,worksheets=[worksheet])
3571 with open(fname, 'w') as f:
3642 with open(fname, 'w') as f:
3572 current.write(nb, f, format);
3643 current.write(nb, f, format);
3573 elif args.format is not None:
3644 elif args.format is not None:
3574 old_fname, old_name, old_format = current.parse_filename(args.filename)
3645 old_fname, old_name, old_format = current.parse_filename(args.filename)
3575 new_format = args.format
3646 new_format = args.format
3576 if new_format == u'xml':
3647 if new_format == u'xml':
3577 raise ValueError('Notebooks cannot be written as xml.')
3648 raise ValueError('Notebooks cannot be written as xml.')
3578 elif new_format == u'ipynb' or new_format == u'json':
3649 elif new_format == u'ipynb' or new_format == u'json':
3579 new_fname = old_name + u'.ipynb'
3650 new_fname = old_name + u'.ipynb'
3580 new_format = u'json'
3651 new_format = u'json'
3581 elif new_format == u'py':
3652 elif new_format == u'py':
3582 new_fname = old_name + u'.py'
3653 new_fname = old_name + u'.py'
3583 else:
3654 else:
3584 raise ValueError('Invalid notebook format: %s' % new_format)
3655 raise ValueError('Invalid notebook format: %s' % new_format)
3585 with open(old_fname, 'r') as f:
3656 with open(old_fname, 'r') as f:
3586 s = f.read()
3657 s = f.read()
3587 try:
3658 try:
3588 nb = current.reads(s, old_format)
3659 nb = current.reads(s, old_format)
3589 except:
3660 except:
3590 nb = current.reads(s, u'xml')
3661 nb = current.reads(s, u'xml')
3591 with open(new_fname, 'w') as f:
3662 with open(new_fname, 'w') as f:
3592 current.write(nb, f, new_format)
3663 current.write(nb, f, new_format)
3593
3664
3594 def magic_config(self, s):
3665 def magic_config(self, s):
3595 """configure IPython
3666 """configure IPython
3596
3667
3597 %config Class[.trait=value]
3668 %config Class[.trait=value]
3598
3669
3599 This magic exposes most of the IPython config system. Any
3670 This magic exposes most of the IPython config system. Any
3600 Configurable class should be able to be configured with the simple
3671 Configurable class should be able to be configured with the simple
3601 line::
3672 line::
3602
3673
3603 %config Class.trait=value
3674 %config Class.trait=value
3604
3675
3605 Where `value` will be resolved in the user's namespace, if it is an
3676 Where `value` will be resolved in the user's namespace, if it is an
3606 expression or variable name.
3677 expression or variable name.
3607
3678
3608 Examples
3679 Examples
3609 --------
3680 --------
3610
3681
3611 To see what classes are available for config, pass no arguments::
3682 To see what classes are available for config, pass no arguments::
3612
3683
3613 In [1]: %config
3684 In [1]: %config
3614 Available objects for config:
3685 Available objects for config:
3615 TerminalInteractiveShell
3686 TerminalInteractiveShell
3616 HistoryManager
3687 HistoryManager
3617 PrefilterManager
3688 PrefilterManager
3618 AliasManager
3689 AliasManager
3619 IPCompleter
3690 IPCompleter
3620 PromptManager
3691 PromptManager
3621 DisplayFormatter
3692 DisplayFormatter
3622
3693
3623 To view what is configurable on a given class, just pass the class name::
3694 To view what is configurable on a given class, just pass the class name::
3624
3695
3625 In [2]: %config IPCompleter
3696 In [2]: %config IPCompleter
3626 IPCompleter options
3697 IPCompleter options
3627 -----------------
3698 -----------------
3628 IPCompleter.omit__names=<Enum>
3699 IPCompleter.omit__names=<Enum>
3629 Current: 2
3700 Current: 2
3630 Choices: (0, 1, 2)
3701 Choices: (0, 1, 2)
3631 Instruct the completer to omit private method names
3702 Instruct the completer to omit private method names
3632 Specifically, when completing on ``object.<tab>``.
3703 Specifically, when completing on ``object.<tab>``.
3633 When 2 [default]: all names that start with '_' will be excluded.
3704 When 2 [default]: all names that start with '_' will be excluded.
3634 When 1: all 'magic' names (``__foo__``) will be excluded.
3705 When 1: all 'magic' names (``__foo__``) will be excluded.
3635 When 0: nothing will be excluded.
3706 When 0: nothing will be excluded.
3636 IPCompleter.merge_completions=<CBool>
3707 IPCompleter.merge_completions=<CBool>
3637 Current: True
3708 Current: True
3638 Whether to merge completion results into a single list
3709 Whether to merge completion results into a single list
3639 If False, only the completion results from the first non-empty completer
3710 If False, only the completion results from the first non-empty completer
3640 will be returned.
3711 will be returned.
3641 IPCompleter.greedy=<CBool>
3712 IPCompleter.greedy=<CBool>
3642 Current: False
3713 Current: False
3643 Activate greedy completion
3714 Activate greedy completion
3644 This will enable completion on elements of lists, results of function calls,
3715 This will enable completion on elements of lists, results of function calls,
3645 etc., but can be unsafe because the code is actually evaluated on TAB.
3716 etc., but can be unsafe because the code is actually evaluated on TAB.
3646
3717
3647 but the real use is in setting values::
3718 but the real use is in setting values::
3648
3719
3649 In [3]: %config IPCompleter.greedy = True
3720 In [3]: %config IPCompleter.greedy = True
3650
3721
3651 and these values are read from the user_ns if they are variables::
3722 and these values are read from the user_ns if they are variables::
3652
3723
3653 In [4]: feeling_greedy=False
3724 In [4]: feeling_greedy=False
3654
3725
3655 In [5]: %config IPCompleter.greedy = feeling_greedy
3726 In [5]: %config IPCompleter.greedy = feeling_greedy
3656
3727
3657 """
3728 """
3658 from IPython.config.loader import Config
3729 from IPython.config.loader import Config
3659 # some IPython objects are Configurable, but do not yet have
3730 # some IPython objects are Configurable, but do not yet have
3660 # any configurable traits. Exclude them from the effects of
3731 # any configurable traits. Exclude them from the effects of
3661 # this magic, as their presence is just noise:
3732 # this magic, as their presence is just noise:
3662 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3733 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3663 classnames = [ c.__class__.__name__ for c in configurables ]
3734 classnames = [ c.__class__.__name__ for c in configurables ]
3664
3735
3665 line = s.strip()
3736 line = s.strip()
3666 if not line:
3737 if not line:
3667 # print available configurable names
3738 # print available configurable names
3668 print "Available objects for config:"
3739 print "Available objects for config:"
3669 for name in classnames:
3740 for name in classnames:
3670 print " ", name
3741 print " ", name
3671 return
3742 return
3672 elif line in classnames:
3743 elif line in classnames:
3673 # `%config TerminalInteractiveShell` will print trait info for
3744 # `%config TerminalInteractiveShell` will print trait info for
3674 # TerminalInteractiveShell
3745 # TerminalInteractiveShell
3675 c = configurables[classnames.index(line)]
3746 c = configurables[classnames.index(line)]
3676 cls = c.__class__
3747 cls = c.__class__
3677 help = cls.class_get_help(c)
3748 help = cls.class_get_help(c)
3678 # strip leading '--' from cl-args:
3749 # strip leading '--' from cl-args:
3679 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3750 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3680 print help
3751 print help
3681 return
3752 return
3682 elif '=' not in line:
3753 elif '=' not in line:
3683 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3754 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3684
3755
3685
3756
3686 # otherwise, assume we are setting configurables.
3757 # otherwise, assume we are setting configurables.
3687 # leave quotes on args when splitting, because we want
3758 # leave quotes on args when splitting, because we want
3688 # unquoted args to eval in user_ns
3759 # unquoted args to eval in user_ns
3689 cfg = Config()
3760 cfg = Config()
3690 exec "cfg."+line in locals(), self.user_ns
3761 exec "cfg."+line in locals(), self.user_ns
3691
3762
3692 for configurable in configurables:
3763 for configurable in configurables:
3693 try:
3764 try:
3694 configurable.update_config(cfg)
3765 configurable.update_config(cfg)
3695 except Exception as e:
3766 except Exception as e:
3696 error(e)
3767 error(e)
3697
3768
3698 # end Magic
3769 # end Magic
@@ -1,366 +1,396 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
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
188 # fix this and revert the skip to happen only if numpy is not around.
189 #@dec.skipif_not_numpy
190 @dec.skip_known_failure
191 def test_numpy_clear_array_undec():
192 from IPython.extensions import clearcmd
193
186
187 @dec.skipif_not_numpy
188 def test_numpy_reset_array_undec():
189 "Test '%reset array' functionality"
194 _ip.ex('import numpy as np')
190 _ip.ex('import numpy as np')
195 _ip.ex('a = np.empty(2)')
191 _ip.ex('a = np.empty(2)')
196 yield (nt.assert_true, 'a' in _ip.user_ns)
192 yield (nt.assert_true, 'a' in _ip.user_ns)
197 _ip.magic('clear array')
193 _ip.magic('reset -f array')
198 yield (nt.assert_false, 'a' in _ip.user_ns)
194 yield (nt.assert_false, 'a' in _ip.user_ns)
199
195
196 def test_reset_out():
197 "Test '%reset out' magic"
198 _ip.run_cell("parrot = 'dead'", store_history=True)
199 # test '%reset -f out', make an Out prompt
200 _ip.run_cell("parrot", store_history=True)
201 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
202 _ip.magic('reset -f out')
203 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
204 nt.assert_true(len(_ip.user_ns['Out']) == 0)
205
206 def test_reset_in():
207 "Test '%reset in' magic"
208 # test '%reset -f in'
209 _ip.run_cell("parrot", store_history=True)
210 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
211 _ip.magic('%reset -f in')
212 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
213 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
214
215 def test_reset_dhist():
216 "Test '%reset dhist' magic"
217 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
218 _ip.magic('cd ' + os.path.dirname(nt.__file__))
219 _ip.magic('cd -')
220 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
221 _ip.magic('reset -f dhist')
222 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
223 _ip.run_cell("_dh = [d for d in tmp]") #restore
224
225 def test_reset_in_length():
226 "Test that '%reset in' preserves In[] length"
227 _ip.run_cell("print 'foo'")
228 _ip.run_cell("reset -f in")
229 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
200
230
201 def test_time():
231 def test_time():
202 _ip.magic('time None')
232 _ip.magic('time None')
203
233
204
234
205 @py3compat.doctest_refactor_print
235 @py3compat.doctest_refactor_print
206 def doctest_time():
236 def doctest_time():
207 """
237 """
208 In [10]: %time None
238 In [10]: %time None
209 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
239 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
210 Wall time: 0.00 s
240 Wall time: 0.00 s
211
241
212 In [11]: def f(kmjy):
242 In [11]: def f(kmjy):
213 ....: %time print 2*kmjy
243 ....: %time print 2*kmjy
214
244
215 In [12]: f(3)
245 In [12]: f(3)
216 6
246 6
217 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
247 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
218 Wall time: 0.00 s
248 Wall time: 0.00 s
219 """
249 """
220
250
221
251
222 def test_doctest_mode():
252 def test_doctest_mode():
223 "Toggle doctest_mode twice, it should be a no-op and run without error"
253 "Toggle doctest_mode twice, it should be a no-op and run without error"
224 _ip.magic('doctest_mode')
254 _ip.magic('doctest_mode')
225 _ip.magic('doctest_mode')
255 _ip.magic('doctest_mode')
226
256
227
257
228 def test_parse_options():
258 def test_parse_options():
229 """Tests for basic options parsing in magics."""
259 """Tests for basic options parsing in magics."""
230 # These are only the most minimal of tests, more should be added later. At
260 # These are only the most minimal of tests, more should be added later. At
231 # the very least we check that basic text/unicode calls work OK.
261 # the very least we check that basic text/unicode calls work OK.
232 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
262 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
233 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
263 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
234
264
235
265
236 def test_dirops():
266 def test_dirops():
237 """Test various directory handling operations."""
267 """Test various directory handling operations."""
238 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
268 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
239 curpath = os.getcwdu
269 curpath = os.getcwdu
240 startdir = os.getcwdu()
270 startdir = os.getcwdu()
241 ipdir = os.path.realpath(_ip.ipython_dir)
271 ipdir = os.path.realpath(_ip.ipython_dir)
242 try:
272 try:
243 _ip.magic('cd "%s"' % ipdir)
273 _ip.magic('cd "%s"' % ipdir)
244 nt.assert_equal(curpath(), ipdir)
274 nt.assert_equal(curpath(), ipdir)
245 _ip.magic('cd -')
275 _ip.magic('cd -')
246 nt.assert_equal(curpath(), startdir)
276 nt.assert_equal(curpath(), startdir)
247 _ip.magic('pushd "%s"' % ipdir)
277 _ip.magic('pushd "%s"' % ipdir)
248 nt.assert_equal(curpath(), ipdir)
278 nt.assert_equal(curpath(), ipdir)
249 _ip.magic('popd')
279 _ip.magic('popd')
250 nt.assert_equal(curpath(), startdir)
280 nt.assert_equal(curpath(), startdir)
251 finally:
281 finally:
252 os.chdir(startdir)
282 os.chdir(startdir)
253
283
254
284
255 def test_xmode():
285 def test_xmode():
256 # Calling xmode three times should be a no-op
286 # Calling xmode three times should be a no-op
257 xmode = _ip.InteractiveTB.mode
287 xmode = _ip.InteractiveTB.mode
258 for i in range(3):
288 for i in range(3):
259 _ip.magic("xmode")
289 _ip.magic("xmode")
260 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
290 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
261
291
262 def test_reset_hard():
292 def test_reset_hard():
263 monitor = []
293 monitor = []
264 class A(object):
294 class A(object):
265 def __del__(self):
295 def __del__(self):
266 monitor.append(1)
296 monitor.append(1)
267 def __repr__(self):
297 def __repr__(self):
268 return "<A instance>"
298 return "<A instance>"
269
299
270 _ip.user_ns["a"] = A()
300 _ip.user_ns["a"] = A()
271 _ip.run_cell("a")
301 _ip.run_cell("a")
272
302
273 nt.assert_equal(monitor, [])
303 nt.assert_equal(monitor, [])
274 _ip.magic_reset("-f")
304 _ip.magic_reset("-f")
275 nt.assert_equal(monitor, [1])
305 nt.assert_equal(monitor, [1])
276
306
277 class TestXdel(tt.TempFileMixin):
307 class TestXdel(tt.TempFileMixin):
278 def test_xdel(self):
308 def test_xdel(self):
279 """Test that references from %run are cleared by xdel."""
309 """Test that references from %run are cleared by xdel."""
280 src = ("class A(object):\n"
310 src = ("class A(object):\n"
281 " monitor = []\n"
311 " monitor = []\n"
282 " def __del__(self):\n"
312 " def __del__(self):\n"
283 " self.monitor.append(1)\n"
313 " self.monitor.append(1)\n"
284 "a = A()\n")
314 "a = A()\n")
285 self.mktmp(src)
315 self.mktmp(src)
286 # %run creates some hidden references...
316 # %run creates some hidden references...
287 _ip.magic("run %s" % self.fname)
317 _ip.magic("run %s" % self.fname)
288 # ... as does the displayhook.
318 # ... as does the displayhook.
289 _ip.run_cell("a")
319 _ip.run_cell("a")
290
320
291 monitor = _ip.user_ns["A"].monitor
321 monitor = _ip.user_ns["A"].monitor
292 nt.assert_equal(monitor, [])
322 nt.assert_equal(monitor, [])
293
323
294 _ip.magic("xdel a")
324 _ip.magic("xdel a")
295
325
296 # Check that a's __del__ method has been called.
326 # Check that a's __del__ method has been called.
297 nt.assert_equal(monitor, [1])
327 nt.assert_equal(monitor, [1])
298
328
299 def doctest_who():
329 def doctest_who():
300 """doctest for %who
330 """doctest for %who
301
331
302 In [1]: %reset -f
332 In [1]: %reset -f
303
333
304 In [2]: alpha = 123
334 In [2]: alpha = 123
305
335
306 In [3]: beta = 'beta'
336 In [3]: beta = 'beta'
307
337
308 In [4]: %who int
338 In [4]: %who int
309 alpha
339 alpha
310
340
311 In [5]: %who str
341 In [5]: %who str
312 beta
342 beta
313
343
314 In [6]: %whos
344 In [6]: %whos
315 Variable Type Data/Info
345 Variable Type Data/Info
316 ----------------------------
346 ----------------------------
317 alpha int 123
347 alpha int 123
318 beta str beta
348 beta str beta
319
349
320 In [7]: %who_ls
350 In [7]: %who_ls
321 Out[7]: ['alpha', 'beta']
351 Out[7]: ['alpha', 'beta']
322 """
352 """
323
353
324 @py3compat.u_format
354 @py3compat.u_format
325 def doctest_precision():
355 def doctest_precision():
326 """doctest for %precision
356 """doctest for %precision
327
357
328 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
358 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
329
359
330 In [2]: %precision 5
360 In [2]: %precision 5
331 Out[2]: {u}'%.5f'
361 Out[2]: {u}'%.5f'
332
362
333 In [3]: f.float_format
363 In [3]: f.float_format
334 Out[3]: {u}'%.5f'
364 Out[3]: {u}'%.5f'
335
365
336 In [4]: %precision %e
366 In [4]: %precision %e
337 Out[4]: {u}'%e'
367 Out[4]: {u}'%e'
338
368
339 In [5]: f(3.1415927)
369 In [5]: f(3.1415927)
340 Out[5]: {u}'3.141593e+00'
370 Out[5]: {u}'3.141593e+00'
341 """
371 """
342
372
343 def test_psearch():
373 def test_psearch():
344 with tt.AssertPrints("dict.fromkeys"):
374 with tt.AssertPrints("dict.fromkeys"):
345 _ip.run_cell("dict.fr*?")
375 _ip.run_cell("dict.fr*?")
346
376
347 def test_timeit_shlex():
377 def test_timeit_shlex():
348 """test shlex issues with timeit (#1109)"""
378 """test shlex issues with timeit (#1109)"""
349 _ip.ex("def f(*a,**kw): pass")
379 _ip.ex("def f(*a,**kw): pass")
350 _ip.magic('timeit -n1 "this is a bug".count(" ")')
380 _ip.magic('timeit -n1 "this is a bug".count(" ")')
351 _ip.magic('timeit -r1 -n1 f(" ", 1)')
381 _ip.magic('timeit -r1 -n1 f(" ", 1)')
352 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
382 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
353 _ip.magic('timeit -r1 -n1 ("a " + "b")')
383 _ip.magic('timeit -r1 -n1 ("a " + "b")')
354 _ip.magic('timeit -r1 -n1 f("a " + "b")')
384 _ip.magic('timeit -r1 -n1 f("a " + "b")')
355 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
385 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
356
386
357
387
358 def test_timeit_arguments():
388 def test_timeit_arguments():
359 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
389 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
360 _ip.magic("timeit ('#')")
390 _ip.magic("timeit ('#')")
361
391
362 @dec.skipif(_ip.magic_prun == _ip.profile_missing_notice)
392 @dec.skipif(_ip.magic_prun == _ip.profile_missing_notice)
363 def test_prun_quotes():
393 def test_prun_quotes():
364 "Test that prun does not clobber string escapes (GH #1302)"
394 "Test that prun does not clobber string escapes (GH #1302)"
365 _ip.magic("prun -q x = '\t'")
395 _ip.magic("prun -q x = '\t'")
366 nt.assert_equal(_ip.user_ns['x'], '\t')
396 nt.assert_equal(_ip.user_ns['x'], '\t')
@@ -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