##// END OF EJS Templates
Fix tests for core
Thomas Kluyver -
Show More
@@ -1,338 +1,338 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 imp
20 import imp
21 import inspect
21 import inspect
22 import os
22 import os
23 import re
23 import re
24 import sys
24 import sys
25
25
26 # Third-party imports
26 # Third-party imports
27 from time import time
27 from time import time
28 from zipimport import zipimporter
28 from zipimport import zipimporter
29
29
30 # Our own imports
30 # Our own imports
31 from IPython.core.completer import expand_user, compress_user
31 from IPython.core.completer import expand_user, compress_user
32 from IPython.core.error import TryNext
32 from IPython.core.error import TryNext
33 from IPython.utils._process_common import arg_split
33 from IPython.utils._process_common import arg_split
34 from IPython.utils.py3compat import string_types
34 from IPython.utils.py3compat import string_types
35
35
36 # FIXME: this should be pulled in with the right call via the component system
36 # FIXME: this should be pulled in with the right call via the component system
37 from IPython import get_ipython
37 from IPython import get_ipython
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Globals and constants
40 # Globals and constants
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 # Time in seconds after which the rootmodules will be stored permanently in the
43 # Time in seconds after which the rootmodules will be stored permanently in the
44 # ipython ip.db database (kept in the user's .ipython dir).
44 # ipython ip.db database (kept in the user's .ipython dir).
45 TIMEOUT_STORAGE = 2
45 TIMEOUT_STORAGE = 2
46
46
47 # Time in seconds after which we give up
47 # Time in seconds after which we give up
48 TIMEOUT_GIVEUP = 20
48 TIMEOUT_GIVEUP = 20
49
49
50 # Regular expression for the python import statement
50 # Regular expression for the python import statement
51 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
51 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
52 r'(?P<package>[/\\]__init__)?'
52 r'(?P<package>[/\\]__init__)?'
53 r'(?P<suffix>%s)$' %
53 r'(?P<suffix>%s)$' %
54 r'|'.join(re.escape(s[0]) for s in imp.get_suffixes()))
54 r'|'.join(re.escape(s[0]) for s in imp.get_suffixes()))
55
55
56 # RE for the ipython %run command (python + ipython scripts)
56 # RE for the ipython %run command (python + ipython scripts)
57 magic_run_re = re.compile(r'.*(\.ipy|\.py[w]?)$')
57 magic_run_re = re.compile(r'.*(\.ipy|\.py[w]?)$')
58
58
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60 # Local utilities
60 # Local utilities
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62
62
63 def module_list(path):
63 def module_list(path):
64 """
64 """
65 Return the list containing the names of the modules available in the given
65 Return the list containing the names of the modules available in the given
66 folder.
66 folder.
67 """
67 """
68 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
68 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
69 if path == '':
69 if path == '':
70 path = '.'
70 path = '.'
71
71
72 # A few local constants to be used in loops below
72 # A few local constants to be used in loops below
73 pjoin = os.path.join
73 pjoin = os.path.join
74
74
75 if os.path.isdir(path):
75 if os.path.isdir(path):
76 # Build a list of all files in the directory and all files
76 # Build a list of all files in the directory and all files
77 # in its subdirectories. For performance reasons, do not
77 # in its subdirectories. For performance reasons, do not
78 # recurse more than one level into subdirectories.
78 # recurse more than one level into subdirectories.
79 files = []
79 files = []
80 for root, dirs, nondirs in os.walk(path):
80 for root, dirs, nondirs in os.walk(path):
81 subdir = root[len(path)+1:]
81 subdir = root[len(path)+1:]
82 if subdir:
82 if subdir:
83 files.extend(pjoin(subdir, f) for f in nondirs)
83 files.extend(pjoin(subdir, f) for f in nondirs)
84 dirs[:] = [] # Do not recurse into additional subdirectories.
84 dirs[:] = [] # Do not recurse into additional subdirectories.
85 else:
85 else:
86 files.extend(nondirs)
86 files.extend(nondirs)
87
87
88 else:
88 else:
89 try:
89 try:
90 files = list(zipimporter(path)._files.keys())
90 files = list(zipimporter(path)._files.keys())
91 except:
91 except:
92 files = []
92 files = []
93
93
94 # Build a list of modules which match the import_re regex.
94 # Build a list of modules which match the import_re regex.
95 modules = []
95 modules = []
96 for f in files:
96 for f in files:
97 m = import_re.match(f)
97 m = import_re.match(f)
98 if m:
98 if m:
99 modules.append(m.group('name'))
99 modules.append(m.group('name'))
100 return list(set(modules))
100 return list(set(modules))
101
101
102
102
103 def get_root_modules():
103 def get_root_modules():
104 """
104 """
105 Returns a list containing the names of all the modules available in the
105 Returns a list containing the names of all the modules available in the
106 folders of the pythonpath.
106 folders of the pythonpath.
107
107
108 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
108 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
109 """
109 """
110 ip = get_ipython()
110 ip = get_ipython()
111 rootmodules_cache = ip.db.get('rootmodules_cache', {})
111 rootmodules_cache = ip.db.get('rootmodules_cache', {})
112 rootmodules = list(sys.builtin_module_names)
112 rootmodules = list(sys.builtin_module_names)
113 start_time = time()
113 start_time = time()
114 store = False
114 store = False
115 for path in sys.path:
115 for path in sys.path:
116 try:
116 try:
117 modules = rootmodules_cache[path]
117 modules = rootmodules_cache[path]
118 except KeyError:
118 except KeyError:
119 modules = module_list(path)
119 modules = module_list(path)
120 try:
120 try:
121 modules.remove('__init__')
121 modules.remove('__init__')
122 except ValueError:
122 except ValueError:
123 pass
123 pass
124 if path not in ('', '.'): # cwd modules should not be cached
124 if path not in ('', '.'): # cwd modules should not be cached
125 rootmodules_cache[path] = modules
125 rootmodules_cache[path] = modules
126 if time() - start_time > TIMEOUT_STORAGE and not store:
126 if time() - start_time > TIMEOUT_STORAGE and not store:
127 store = True
127 store = True
128 print("\nCaching the list of root modules, please wait!")
128 print("\nCaching the list of root modules, please wait!")
129 print("(This will only be done once - type '%rehashx' to "
129 print("(This will only be done once - type '%rehashx' to "
130 "reset cache!)\n")
130 "reset cache!)\n")
131 sys.stdout.flush()
131 sys.stdout.flush()
132 if time() - start_time > TIMEOUT_GIVEUP:
132 if time() - start_time > TIMEOUT_GIVEUP:
133 print("This is taking too long, we give up.\n")
133 print("This is taking too long, we give up.\n")
134 return []
134 return []
135 rootmodules.extend(modules)
135 rootmodules.extend(modules)
136 if store:
136 if store:
137 ip.db['rootmodules_cache'] = rootmodules_cache
137 ip.db['rootmodules_cache'] = rootmodules_cache
138 rootmodules = list(set(rootmodules))
138 rootmodules = list(set(rootmodules))
139 return rootmodules
139 return rootmodules
140
140
141
141
142 def is_importable(module, attr, only_modules):
142 def is_importable(module, attr, only_modules):
143 if only_modules:
143 if only_modules:
144 return inspect.ismodule(getattr(module, attr))
144 return inspect.ismodule(getattr(module, attr))
145 else:
145 else:
146 return not(attr[:2] == '__' and attr[-2:] == '__')
146 return not(attr[:2] == '__' and attr[-2:] == '__')
147
147
148
148
149 def try_import(mod, only_modules=False):
149 def try_import(mod, only_modules=False):
150 try:
150 try:
151 m = __import__(mod)
151 m = __import__(mod)
152 except:
152 except:
153 return []
153 return []
154 mods = mod.split('.')
154 mods = mod.split('.')
155 for module in mods[1:]:
155 for module in mods[1:]:
156 m = getattr(m, module)
156 m = getattr(m, module)
157
157
158 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
158 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
159
159
160 completions = []
160 completions = []
161 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
161 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
162 completions.extend( [attr for attr in dir(m) if
162 completions.extend( [attr for attr in dir(m) if
163 is_importable(m, attr, only_modules)])
163 is_importable(m, attr, only_modules)])
164
164
165 completions.extend(getattr(m, '__all__', []))
165 completions.extend(getattr(m, '__all__', []))
166 if m_is_init:
166 if m_is_init:
167 completions.extend(module_list(os.path.dirname(m.__file__)))
167 completions.extend(module_list(os.path.dirname(m.__file__)))
168 completions = set(completions)
168 completions = set(completions)
169 if '__init__' in completions:
169 if '__init__' in completions:
170 completions.remove('__init__')
170 completions.remove('__init__')
171 return list(completions)
171 return list(completions)
172
172
173
173
174 #-----------------------------------------------------------------------------
174 #-----------------------------------------------------------------------------
175 # Completion-related functions.
175 # Completion-related functions.
176 #-----------------------------------------------------------------------------
176 #-----------------------------------------------------------------------------
177
177
178 def quick_completer(cmd, completions):
178 def quick_completer(cmd, completions):
179 """ Easily create a trivial completer for a command.
179 """ Easily create a trivial completer for a command.
180
180
181 Takes either a list of completions, or all completions in string (that will
181 Takes either a list of completions, or all completions in string (that will
182 be split on whitespace).
182 be split on whitespace).
183
183
184 Example::
184 Example::
185
185
186 [d:\ipython]|1> import ipy_completers
186 [d:\ipython]|1> import ipy_completers
187 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
187 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
188 [d:\ipython]|3> foo b<TAB>
188 [d:\ipython]|3> foo b<TAB>
189 bar baz
189 bar baz
190 [d:\ipython]|3> foo ba
190 [d:\ipython]|3> foo ba
191 """
191 """
192
192
193 if isinstance(completions, string_types):
193 if isinstance(completions, string_types):
194 completions = completions.split()
194 completions = completions.split()
195
195
196 def do_complete(self, event):
196 def do_complete(self, event):
197 return completions
197 return completions
198
198
199 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
199 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
200
200
201 def module_completion(line):
201 def module_completion(line):
202 """
202 """
203 Returns a list containing the completion possibilities for an import line.
203 Returns a list containing the completion possibilities for an import line.
204
204
205 The line looks like this :
205 The line looks like this :
206 'import xml.d'
206 'import xml.d'
207 'from xml.dom import'
207 'from xml.dom import'
208 """
208 """
209
209
210 words = line.split(' ')
210 words = line.split(' ')
211 nwords = len(words)
211 nwords = len(words)
212
212
213 # from whatever <tab> -> 'import '
213 # from whatever <tab> -> 'import '
214 if nwords == 3 and words[0] == 'from':
214 if nwords == 3 and words[0] == 'from':
215 return ['import ']
215 return ['import ']
216
216
217 # 'from xy<tab>' or 'import xy<tab>'
217 # 'from xy<tab>' or 'import xy<tab>'
218 if nwords < 3 and (words[0] in ['import','from']) :
218 if nwords < 3 and (words[0] in ['import','from']) :
219 if nwords == 1:
219 if nwords == 1:
220 return get_root_modules()
220 return get_root_modules()
221 mod = words[1].split('.')
221 mod = words[1].split('.')
222 if len(mod) < 2:
222 if len(mod) < 2:
223 return get_root_modules()
223 return get_root_modules()
224 completion_list = try_import('.'.join(mod[:-1]), True)
224 completion_list = try_import('.'.join(mod[:-1]), True)
225 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
225 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
226
226
227 # 'from xyz import abc<tab>'
227 # 'from xyz import abc<tab>'
228 if nwords >= 3 and words[0] == 'from':
228 if nwords >= 3 and words[0] == 'from':
229 mod = words[1]
229 mod = words[1]
230 return try_import(mod)
230 return try_import(mod)
231
231
232 #-----------------------------------------------------------------------------
232 #-----------------------------------------------------------------------------
233 # Completers
233 # Completers
234 #-----------------------------------------------------------------------------
234 #-----------------------------------------------------------------------------
235 # These all have the func(self, event) signature to be used as custom
235 # These all have the func(self, event) signature to be used as custom
236 # completers
236 # completers
237
237
238 def module_completer(self,event):
238 def module_completer(self,event):
239 """Give completions after user has typed 'import ...' or 'from ...'"""
239 """Give completions after user has typed 'import ...' or 'from ...'"""
240
240
241 # This works in all versions of python. While 2.5 has
241 # This works in all versions of python. While 2.5 has
242 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
242 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
243 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
243 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
244 # of possibly problematic side effects.
244 # of possibly problematic side effects.
245 # This search the folders in the sys.path for available modules.
245 # This search the folders in the sys.path for available modules.
246
246
247 return module_completion(event.line)
247 return module_completion(event.line)
248
248
249 # FIXME: there's a lot of logic common to the run, cd and builtin file
249 # FIXME: there's a lot of logic common to the run, cd and builtin file
250 # completers, that is currently reimplemented in each.
250 # completers, that is currently reimplemented in each.
251
251
252 def magic_run_completer(self, event):
252 def magic_run_completer(self, event):
253 """Complete files that end in .py or .ipy for the %run command.
253 """Complete files that end in .py or .ipy for the %run command.
254 """
254 """
255 comps = arg_split(event.line, strict=False)
255 comps = arg_split(event.line, strict=False)
256 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
256 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
257
257
258 #print("\nev=", event) # dbg
258 #print("\nev=", event) # dbg
259 #print("rp=", relpath) # dbg
259 #print("rp=", relpath) # dbg
260 #print('comps=', comps) # dbg
260 #print('comps=', comps) # dbg
261
261
262 lglob = glob.glob
262 lglob = glob.glob
263 isdir = os.path.isdir
263 isdir = os.path.isdir
264 relpath, tilde_expand, tilde_val = expand_user(relpath)
264 relpath, tilde_expand, tilde_val = expand_user(relpath)
265
265
266 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
266 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
267
267
268 # Find if the user has already typed the first filename, after which we
268 # Find if the user has already typed the first filename, after which we
269 # should complete on all files, since after the first one other files may
269 # should complete on all files, since after the first one other files may
270 # be arguments to the input script.
270 # be arguments to the input script.
271
271
272 if filter(magic_run_re.match, comps):
272 if any(magic_run_re.match(c) for c in comps):
273 pys = [f.replace('\\','/') for f in lglob('*')]
273 pys = [f.replace('\\','/') for f in lglob('*')]
274 else:
274 else:
275 pys = [f.replace('\\','/')
275 pys = [f.replace('\\','/')
276 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
276 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
277 lglob(relpath + '*.pyw')]
277 lglob(relpath + '*.pyw')]
278 #print('run comp:', dirs+pys) # dbg
278 #print('run comp:', dirs+pys) # dbg
279 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
279 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
280
280
281
281
282 def cd_completer(self, event):
282 def cd_completer(self, event):
283 """Completer function for cd, which only returns directories."""
283 """Completer function for cd, which only returns directories."""
284 ip = get_ipython()
284 ip = get_ipython()
285 relpath = event.symbol
285 relpath = event.symbol
286
286
287 #print(event) # dbg
287 #print(event) # dbg
288 if event.line.endswith('-b') or ' -b ' in event.line:
288 if event.line.endswith('-b') or ' -b ' in event.line:
289 # return only bookmark completions
289 # return only bookmark completions
290 bkms = self.db.get('bookmarks', None)
290 bkms = self.db.get('bookmarks', None)
291 if bkms:
291 if bkms:
292 return bkms.keys()
292 return bkms.keys()
293 else:
293 else:
294 return []
294 return []
295
295
296 if event.symbol == '-':
296 if event.symbol == '-':
297 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
297 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
298 # jump in directory history by number
298 # jump in directory history by number
299 fmt = '-%0' + width_dh +'d [%s]'
299 fmt = '-%0' + width_dh +'d [%s]'
300 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
300 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
301 if len(ents) > 1:
301 if len(ents) > 1:
302 return ents
302 return ents
303 return []
303 return []
304
304
305 if event.symbol.startswith('--'):
305 if event.symbol.startswith('--'):
306 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
306 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
307
307
308 # Expand ~ in path and normalize directory separators.
308 # Expand ~ in path and normalize directory separators.
309 relpath, tilde_expand, tilde_val = expand_user(relpath)
309 relpath, tilde_expand, tilde_val = expand_user(relpath)
310 relpath = relpath.replace('\\','/')
310 relpath = relpath.replace('\\','/')
311
311
312 found = []
312 found = []
313 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
313 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
314 if os.path.isdir(f)]:
314 if os.path.isdir(f)]:
315 if ' ' in d:
315 if ' ' in d:
316 # we don't want to deal with any of that, complex code
316 # we don't want to deal with any of that, complex code
317 # for this is elsewhere
317 # for this is elsewhere
318 raise TryNext
318 raise TryNext
319
319
320 found.append(d)
320 found.append(d)
321
321
322 if not found:
322 if not found:
323 if os.path.isdir(relpath):
323 if os.path.isdir(relpath):
324 return [compress_user(relpath, tilde_expand, tilde_val)]
324 return [compress_user(relpath, tilde_expand, tilde_val)]
325
325
326 # if no completions so far, try bookmarks
326 # if no completions so far, try bookmarks
327 bks = self.db.get('bookmarks',{})
327 bks = self.db.get('bookmarks',{})
328 bkmatches = [s for s in bks if s.startswith(event.symbol)]
328 bkmatches = [s for s in bks if s.startswith(event.symbol)]
329 if bkmatches:
329 if bkmatches:
330 return bkmatches
330 return bkmatches
331
331
332 raise TryNext
332 raise TryNext
333
333
334 return [compress_user(p, tilde_expand, tilde_val) for p in found]
334 return [compress_user(p, tilde_expand, tilde_val) for p in found]
335
335
336 def reset_completer(self, event):
336 def reset_completer(self, event):
337 "A completer for %reset magic"
337 "A completer for %reset magic"
338 return '-f -s in out array dhist'.split()
338 return '-f -s in out array dhist'.split()
@@ -1,584 +1,590 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27 from __future__ import print_function
27 from __future__ import print_function
28
28
29 import bdb
29 import bdb
30 import functools
30 import functools
31 import linecache
31 import linecache
32 import sys
32 import sys
33
33
34 from IPython import get_ipython
34 from IPython import get_ipython
35 from IPython.utils import PyColorize, ulinecache
35 from IPython.utils import PyColorize, ulinecache
36 from IPython.utils import coloransi, io, py3compat
36 from IPython.utils import coloransi, io, py3compat
37 from IPython.core.excolors import exception_colors
37 from IPython.core.excolors import exception_colors
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
39
39
40 # See if we can use pydb.
40 # See if we can use pydb.
41 has_pydb = False
41 has_pydb = False
42 prompt = 'ipdb> '
42 prompt = 'ipdb> '
43 #We have to check this directly from sys.argv, config struct not yet available
43 #We have to check this directly from sys.argv, config struct not yet available
44 if '--pydb' in sys.argv:
44 if '--pydb' in sys.argv:
45 try:
45 try:
46 import pydb
46 import pydb
47 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
47 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
48 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
48 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
49 # better protect against it.
49 # better protect against it.
50 has_pydb = True
50 has_pydb = True
51 except ImportError:
51 except ImportError:
52 print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available")
52 print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available")
53
53
54 if has_pydb:
54 if has_pydb:
55 from pydb import Pdb as OldPdb
55 from pydb import Pdb as OldPdb
56 #print "Using pydb for %run -d and post-mortem" #dbg
56 #print "Using pydb for %run -d and post-mortem" #dbg
57 prompt = 'ipydb> '
57 prompt = 'ipydb> '
58 else:
58 else:
59 from pdb import Pdb as OldPdb
59 from pdb import Pdb as OldPdb
60
60
61 # Allow the set_trace code to operate outside of an ipython instance, even if
61 # Allow the set_trace code to operate outside of an ipython instance, even if
62 # it does so with some limitations. The rest of this support is implemented in
62 # it does so with some limitations. The rest of this support is implemented in
63 # the Tracer constructor.
63 # the Tracer constructor.
64 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
64 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
65 """Exception hook which handles `BdbQuit` exceptions.
65 """Exception hook which handles `BdbQuit` exceptions.
66
66
67 All other exceptions are processed using the `excepthook`
67 All other exceptions are processed using the `excepthook`
68 parameter.
68 parameter.
69 """
69 """
70 if et==bdb.BdbQuit:
70 if et==bdb.BdbQuit:
71 print('Exiting Debugger.')
71 print('Exiting Debugger.')
72 elif excepthook is not None:
72 elif excepthook is not None:
73 excepthook(et, ev, tb)
73 excepthook(et, ev, tb)
74 else:
74 else:
75 # Backwards compatibility. Raise deprecation warning?
75 # Backwards compatibility. Raise deprecation warning?
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
77
77
78 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
78 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
79 print('Exiting Debugger.')
79 print('Exiting Debugger.')
80
80
81
81
82 class Tracer(object):
82 class Tracer(object):
83 """Class for local debugging, similar to pdb.set_trace.
83 """Class for local debugging, similar to pdb.set_trace.
84
84
85 Instances of this class, when called, behave like pdb.set_trace, but
85 Instances of this class, when called, behave like pdb.set_trace, but
86 providing IPython's enhanced capabilities.
86 providing IPython's enhanced capabilities.
87
87
88 This is implemented as a class which must be initialized in your own code
88 This is implemented as a class which must be initialized in your own code
89 and not as a standalone function because we need to detect at runtime
89 and not as a standalone function because we need to detect at runtime
90 whether IPython is already active or not. That detection is done in the
90 whether IPython is already active or not. That detection is done in the
91 constructor, ensuring that this code plays nicely with a running IPython,
91 constructor, ensuring that this code plays nicely with a running IPython,
92 while functioning acceptably (though with limitations) if outside of it.
92 while functioning acceptably (though with limitations) if outside of it.
93 """
93 """
94
94
95 @skip_doctest
95 @skip_doctest
96 def __init__(self,colors=None):
96 def __init__(self,colors=None):
97 """Create a local debugger instance.
97 """Create a local debugger instance.
98
98
99 Parameters
99 Parameters
100 ----------
100 ----------
101
101
102 colors : str, optional
102 colors : str, optional
103 The name of the color scheme to use, it must be one of IPython's
103 The name of the color scheme to use, it must be one of IPython's
104 valid color schemes. If not given, the function will default to
104 valid color schemes. If not given, the function will default to
105 the current IPython scheme when running inside IPython, and to
105 the current IPython scheme when running inside IPython, and to
106 'NoColor' otherwise.
106 'NoColor' otherwise.
107
107
108 Examples
108 Examples
109 --------
109 --------
110 ::
110 ::
111
111
112 from IPython.core.debugger import Tracer; debug_here = Tracer()
112 from IPython.core.debugger import Tracer; debug_here = Tracer()
113
113
114 Later in your code::
114 Later in your code::
115
115
116 debug_here() # -> will open up the debugger at that point.
116 debug_here() # -> will open up the debugger at that point.
117
117
118 Once the debugger activates, you can use all of its regular commands to
118 Once the debugger activates, you can use all of its regular commands to
119 step through code, set breakpoints, etc. See the pdb documentation
119 step through code, set breakpoints, etc. See the pdb documentation
120 from the Python standard library for usage details.
120 from the Python standard library for usage details.
121 """
121 """
122
122
123 ip = get_ipython()
123 ip = get_ipython()
124 if ip is None:
124 if ip is None:
125 # Outside of ipython, we set our own exception hook manually
125 # Outside of ipython, we set our own exception hook manually
126 sys.excepthook = functools.partial(BdbQuit_excepthook,
126 sys.excepthook = functools.partial(BdbQuit_excepthook,
127 excepthook=sys.excepthook)
127 excepthook=sys.excepthook)
128 def_colors = 'NoColor'
128 def_colors = 'NoColor'
129 try:
129 try:
130 # Limited tab completion support
130 # Limited tab completion support
131 import readline
131 import readline
132 readline.parse_and_bind('tab: complete')
132 readline.parse_and_bind('tab: complete')
133 except ImportError:
133 except ImportError:
134 pass
134 pass
135 else:
135 else:
136 # In ipython, we use its custom exception handler mechanism
136 # In ipython, we use its custom exception handler mechanism
137 def_colors = ip.colors
137 def_colors = ip.colors
138 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
138 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
139
139
140 if colors is None:
140 if colors is None:
141 colors = def_colors
141 colors = def_colors
142
142
143 # The stdlib debugger internally uses a modified repr from the `repr`
143 # The stdlib debugger internally uses a modified repr from the `repr`
144 # module, that limits the length of printed strings to a hardcoded
144 # module, that limits the length of printed strings to a hardcoded
145 # limit of 30 characters. That much trimming is too aggressive, let's
145 # limit of 30 characters. That much trimming is too aggressive, let's
146 # at least raise that limit to 80 chars, which should be enough for
146 # at least raise that limit to 80 chars, which should be enough for
147 # most interactive uses.
147 # most interactive uses.
148 try:
148 try:
149 from reprlib import aRepr
149 try:
150 from reprlib import aRepr # Py 3
151 except ImportError:
152 from repr import aRepr # Py 2
150 aRepr.maxstring = 80
153 aRepr.maxstring = 80
151 except:
154 except:
152 # This is only a user-facing convenience, so any error we encounter
155 # This is only a user-facing convenience, so any error we encounter
153 # here can be warned about but can be otherwise ignored. These
156 # here can be warned about but can be otherwise ignored. These
154 # printouts will tell us about problems if this API changes
157 # printouts will tell us about problems if this API changes
155 import traceback
158 import traceback
156 traceback.print_exc()
159 traceback.print_exc()
157
160
158 self.debugger = Pdb(colors)
161 self.debugger = Pdb(colors)
159
162
160 def __call__(self):
163 def __call__(self):
161 """Starts an interactive debugger at the point where called.
164 """Starts an interactive debugger at the point where called.
162
165
163 This is similar to the pdb.set_trace() function from the std lib, but
166 This is similar to the pdb.set_trace() function from the std lib, but
164 using IPython's enhanced debugger."""
167 using IPython's enhanced debugger."""
165
168
166 self.debugger.set_trace(sys._getframe().f_back)
169 self.debugger.set_trace(sys._getframe().f_back)
167
170
168
171
169 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
172 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
170 """Make new_fn have old_fn's doc string. This is particularly useful
173 """Make new_fn have old_fn's doc string. This is particularly useful
171 for the ``do_...`` commands that hook into the help system.
174 for the ``do_...`` commands that hook into the help system.
172 Adapted from from a comp.lang.python posting
175 Adapted from from a comp.lang.python posting
173 by Duncan Booth."""
176 by Duncan Booth."""
174 def wrapper(*args, **kw):
177 def wrapper(*args, **kw):
175 return new_fn(*args, **kw)
178 return new_fn(*args, **kw)
176 if old_fn.__doc__:
179 if old_fn.__doc__:
177 wrapper.__doc__ = old_fn.__doc__ + additional_text
180 wrapper.__doc__ = old_fn.__doc__ + additional_text
178 return wrapper
181 return wrapper
179
182
180
183
181 def _file_lines(fname):
184 def _file_lines(fname):
182 """Return the contents of a named file as a list of lines.
185 """Return the contents of a named file as a list of lines.
183
186
184 This function never raises an IOError exception: if the file can't be
187 This function never raises an IOError exception: if the file can't be
185 read, it simply returns an empty list."""
188 read, it simply returns an empty list."""
186
189
187 try:
190 try:
188 outfile = open(fname)
191 outfile = open(fname)
189 except IOError:
192 except IOError:
190 return []
193 return []
191 else:
194 else:
192 out = outfile.readlines()
195 out = outfile.readlines()
193 outfile.close()
196 outfile.close()
194 return out
197 return out
195
198
196
199
197 class Pdb(OldPdb):
200 class Pdb(OldPdb):
198 """Modified Pdb class, does not load readline."""
201 """Modified Pdb class, does not load readline."""
199
202
200 def __init__(self,color_scheme='NoColor',completekey=None,
203 def __init__(self,color_scheme='NoColor',completekey=None,
201 stdin=None, stdout=None):
204 stdin=None, stdout=None):
202
205
203 # Parent constructor:
206 # Parent constructor:
204 if has_pydb and completekey is None:
207 if has_pydb and completekey is None:
205 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
208 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
206 else:
209 else:
207 OldPdb.__init__(self,completekey,stdin,stdout)
210 OldPdb.__init__(self,completekey,stdin,stdout)
208
211
209 self.prompt = prompt # The default prompt is '(Pdb)'
212 self.prompt = prompt # The default prompt is '(Pdb)'
210
213
211 # IPython changes...
214 # IPython changes...
212 self.is_pydb = has_pydb
215 self.is_pydb = has_pydb
213
216
214 self.shell = get_ipython()
217 self.shell = get_ipython()
215
218
216 if self.shell is None:
219 if self.shell is None:
217 # No IPython instance running, we must create one
220 # No IPython instance running, we must create one
218 from IPython.terminal.interactiveshell import \
221 from IPython.terminal.interactiveshell import \
219 TerminalInteractiveShell
222 TerminalInteractiveShell
220 self.shell = TerminalInteractiveShell.instance()
223 self.shell = TerminalInteractiveShell.instance()
221
224
222 if self.is_pydb:
225 if self.is_pydb:
223
226
224 # interactiveshell.py's ipalias seems to want pdb's checkline
227 # interactiveshell.py's ipalias seems to want pdb's checkline
225 # which located in pydb.fn
228 # which located in pydb.fn
226 import pydb.fns
229 import pydb.fns
227 self.checkline = lambda filename, lineno: \
230 self.checkline = lambda filename, lineno: \
228 pydb.fns.checkline(self, filename, lineno)
231 pydb.fns.checkline(self, filename, lineno)
229
232
230 self.curframe = None
233 self.curframe = None
231 self.do_restart = self.new_do_restart
234 self.do_restart = self.new_do_restart
232
235
233 self.old_all_completions = self.shell.Completer.all_completions
236 self.old_all_completions = self.shell.Completer.all_completions
234 self.shell.Completer.all_completions=self.all_completions
237 self.shell.Completer.all_completions=self.all_completions
235
238
236 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
239 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
237 OldPdb.do_list)
240 OldPdb.do_list)
238 self.do_l = self.do_list
241 self.do_l = self.do_list
239 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
242 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
240 OldPdb.do_frame)
243 OldPdb.do_frame)
241
244
242 self.aliases = {}
245 self.aliases = {}
243
246
244 # Create color table: we copy the default one from the traceback
247 # Create color table: we copy the default one from the traceback
245 # module and add a few attributes needed for debugging
248 # module and add a few attributes needed for debugging
246 self.color_scheme_table = exception_colors()
249 self.color_scheme_table = exception_colors()
247
250
248 # shorthands
251 # shorthands
249 C = coloransi.TermColors
252 C = coloransi.TermColors
250 cst = self.color_scheme_table
253 cst = self.color_scheme_table
251
254
252 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
255 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
253 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
256 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
254
257
255 cst['Linux'].colors.breakpoint_enabled = C.LightRed
258 cst['Linux'].colors.breakpoint_enabled = C.LightRed
256 cst['Linux'].colors.breakpoint_disabled = C.Red
259 cst['Linux'].colors.breakpoint_disabled = C.Red
257
260
258 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
261 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
259 cst['LightBG'].colors.breakpoint_disabled = C.Red
262 cst['LightBG'].colors.breakpoint_disabled = C.Red
260
263
261 self.set_colors(color_scheme)
264 self.set_colors(color_scheme)
262
265
263 # Add a python parser so we can syntax highlight source while
266 # Add a python parser so we can syntax highlight source while
264 # debugging.
267 # debugging.
265 self.parser = PyColorize.Parser()
268 self.parser = PyColorize.Parser()
266
269
267 def set_colors(self, scheme):
270 def set_colors(self, scheme):
268 """Shorthand access to the color table scheme selector method."""
271 """Shorthand access to the color table scheme selector method."""
269 self.color_scheme_table.set_active_scheme(scheme)
272 self.color_scheme_table.set_active_scheme(scheme)
270
273
271 def interaction(self, frame, traceback):
274 def interaction(self, frame, traceback):
272 self.shell.set_completer_frame(frame)
275 self.shell.set_completer_frame(frame)
273 while True:
276 while True:
274 try:
277 try:
275 OldPdb.interaction(self, frame, traceback)
278 OldPdb.interaction(self, frame, traceback)
276 except KeyboardInterrupt:
279 except KeyboardInterrupt:
277 self.shell.write("\nKeyboardInterrupt\n")
280 self.shell.write("\nKeyboardInterrupt\n")
278 else:
281 else:
279 break
282 break
280
283
281 def new_do_up(self, arg):
284 def new_do_up(self, arg):
282 OldPdb.do_up(self, arg)
285 OldPdb.do_up(self, arg)
283 self.shell.set_completer_frame(self.curframe)
286 self.shell.set_completer_frame(self.curframe)
284 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
287 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
285
288
286 def new_do_down(self, arg):
289 def new_do_down(self, arg):
287 OldPdb.do_down(self, arg)
290 OldPdb.do_down(self, arg)
288 self.shell.set_completer_frame(self.curframe)
291 self.shell.set_completer_frame(self.curframe)
289
292
290 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
293 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
291
294
292 def new_do_frame(self, arg):
295 def new_do_frame(self, arg):
293 OldPdb.do_frame(self, arg)
296 OldPdb.do_frame(self, arg)
294 self.shell.set_completer_frame(self.curframe)
297 self.shell.set_completer_frame(self.curframe)
295
298
296 def new_do_quit(self, arg):
299 def new_do_quit(self, arg):
297
300
298 if hasattr(self, 'old_all_completions'):
301 if hasattr(self, 'old_all_completions'):
299 self.shell.Completer.all_completions=self.old_all_completions
302 self.shell.Completer.all_completions=self.old_all_completions
300
303
301
304
302 return OldPdb.do_quit(self, arg)
305 return OldPdb.do_quit(self, arg)
303
306
304 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
307 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
305
308
306 def new_do_restart(self, arg):
309 def new_do_restart(self, arg):
307 """Restart command. In the context of ipython this is exactly the same
310 """Restart command. In the context of ipython this is exactly the same
308 thing as 'quit'."""
311 thing as 'quit'."""
309 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
312 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
310 return self.do_quit(arg)
313 return self.do_quit(arg)
311
314
312 def postloop(self):
315 def postloop(self):
313 self.shell.set_completer_frame(None)
316 self.shell.set_completer_frame(None)
314
317
315 def print_stack_trace(self):
318 def print_stack_trace(self):
316 try:
319 try:
317 for frame_lineno in self.stack:
320 for frame_lineno in self.stack:
318 self.print_stack_entry(frame_lineno, context = 5)
321 self.print_stack_entry(frame_lineno, context = 5)
319 except KeyboardInterrupt:
322 except KeyboardInterrupt:
320 pass
323 pass
321
324
322 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
325 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
323 context = 3):
326 context = 3):
324 #frame, lineno = frame_lineno
327 #frame, lineno = frame_lineno
325 print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout)
328 print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout)
326
329
327 # vds: >>
330 # vds: >>
328 frame, lineno = frame_lineno
331 frame, lineno = frame_lineno
329 filename = frame.f_code.co_filename
332 filename = frame.f_code.co_filename
330 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
333 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
331 # vds: <<
334 # vds: <<
332
335
333 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
336 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
334 import reprlib
337 try:
338 import reprlib # Py 3
339 except ImportError:
340 import repr as reprlib # Py 2
335
341
336 ret = []
342 ret = []
337
343
338 Colors = self.color_scheme_table.active_colors
344 Colors = self.color_scheme_table.active_colors
339 ColorsNormal = Colors.Normal
345 ColorsNormal = Colors.Normal
340 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
346 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
341 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
347 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
342 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
348 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
343 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
349 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
344 ColorsNormal)
350 ColorsNormal)
345
351
346 frame, lineno = frame_lineno
352 frame, lineno = frame_lineno
347
353
348 return_value = ''
354 return_value = ''
349 if '__return__' in frame.f_locals:
355 if '__return__' in frame.f_locals:
350 rv = frame.f_locals['__return__']
356 rv = frame.f_locals['__return__']
351 #return_value += '->'
357 #return_value += '->'
352 return_value += reprlib.repr(rv) + '\n'
358 return_value += reprlib.repr(rv) + '\n'
353 ret.append(return_value)
359 ret.append(return_value)
354
360
355 #s = filename + '(' + `lineno` + ')'
361 #s = filename + '(' + `lineno` + ')'
356 filename = self.canonic(frame.f_code.co_filename)
362 filename = self.canonic(frame.f_code.co_filename)
357 link = tpl_link % py3compat.cast_unicode(filename)
363 link = tpl_link % py3compat.cast_unicode(filename)
358
364
359 if frame.f_code.co_name:
365 if frame.f_code.co_name:
360 func = frame.f_code.co_name
366 func = frame.f_code.co_name
361 else:
367 else:
362 func = "<lambda>"
368 func = "<lambda>"
363
369
364 call = ''
370 call = ''
365 if func != '?':
371 if func != '?':
366 if '__args__' in frame.f_locals:
372 if '__args__' in frame.f_locals:
367 args = reprlib.repr(frame.f_locals['__args__'])
373 args = reprlib.repr(frame.f_locals['__args__'])
368 else:
374 else:
369 args = '()'
375 args = '()'
370 call = tpl_call % (func, args)
376 call = tpl_call % (func, args)
371
377
372 # The level info should be generated in the same format pdb uses, to
378 # The level info should be generated in the same format pdb uses, to
373 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
379 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
374 if frame is self.curframe:
380 if frame is self.curframe:
375 ret.append('> ')
381 ret.append('> ')
376 else:
382 else:
377 ret.append(' ')
383 ret.append(' ')
378 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
384 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
379
385
380 start = lineno - 1 - context//2
386 start = lineno - 1 - context//2
381 lines = ulinecache.getlines(filename)
387 lines = ulinecache.getlines(filename)
382 start = min(start, len(lines) - context)
388 start = min(start, len(lines) - context)
383 start = max(start, 0)
389 start = max(start, 0)
384 lines = lines[start : start + context]
390 lines = lines[start : start + context]
385
391
386 for i,line in enumerate(lines):
392 for i,line in enumerate(lines):
387 show_arrow = (start + 1 + i == lineno)
393 show_arrow = (start + 1 + i == lineno)
388 linetpl = (frame is self.curframe or show_arrow) \
394 linetpl = (frame is self.curframe or show_arrow) \
389 and tpl_line_em \
395 and tpl_line_em \
390 or tpl_line
396 or tpl_line
391 ret.append(self.__format_line(linetpl, filename,
397 ret.append(self.__format_line(linetpl, filename,
392 start + 1 + i, line,
398 start + 1 + i, line,
393 arrow = show_arrow) )
399 arrow = show_arrow) )
394 return ''.join(ret)
400 return ''.join(ret)
395
401
396 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
402 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
397 bp_mark = ""
403 bp_mark = ""
398 bp_mark_color = ""
404 bp_mark_color = ""
399
405
400 scheme = self.color_scheme_table.active_scheme_name
406 scheme = self.color_scheme_table.active_scheme_name
401 new_line, err = self.parser.format2(line, 'str', scheme)
407 new_line, err = self.parser.format2(line, 'str', scheme)
402 if not err: line = new_line
408 if not err: line = new_line
403
409
404 bp = None
410 bp = None
405 if lineno in self.get_file_breaks(filename):
411 if lineno in self.get_file_breaks(filename):
406 bps = self.get_breaks(filename, lineno)
412 bps = self.get_breaks(filename, lineno)
407 bp = bps[-1]
413 bp = bps[-1]
408
414
409 if bp:
415 if bp:
410 Colors = self.color_scheme_table.active_colors
416 Colors = self.color_scheme_table.active_colors
411 bp_mark = str(bp.number)
417 bp_mark = str(bp.number)
412 bp_mark_color = Colors.breakpoint_enabled
418 bp_mark_color = Colors.breakpoint_enabled
413 if not bp.enabled:
419 if not bp.enabled:
414 bp_mark_color = Colors.breakpoint_disabled
420 bp_mark_color = Colors.breakpoint_disabled
415
421
416 numbers_width = 7
422 numbers_width = 7
417 if arrow:
423 if arrow:
418 # This is the line with the error
424 # This is the line with the error
419 pad = numbers_width - len(str(lineno)) - len(bp_mark)
425 pad = numbers_width - len(str(lineno)) - len(bp_mark)
420 if pad >= 3:
426 if pad >= 3:
421 marker = '-'*(pad-3) + '-> '
427 marker = '-'*(pad-3) + '-> '
422 elif pad == 2:
428 elif pad == 2:
423 marker = '> '
429 marker = '> '
424 elif pad == 1:
430 elif pad == 1:
425 marker = '>'
431 marker = '>'
426 else:
432 else:
427 marker = ''
433 marker = ''
428 num = '%s%s' % (marker, str(lineno))
434 num = '%s%s' % (marker, str(lineno))
429 line = tpl_line % (bp_mark_color + bp_mark, num, line)
435 line = tpl_line % (bp_mark_color + bp_mark, num, line)
430 else:
436 else:
431 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
437 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
432 line = tpl_line % (bp_mark_color + bp_mark, num, line)
438 line = tpl_line % (bp_mark_color + bp_mark, num, line)
433
439
434 return line
440 return line
435
441
436 def list_command_pydb(self, arg):
442 def list_command_pydb(self, arg):
437 """List command to use if we have a newer pydb installed"""
443 """List command to use if we have a newer pydb installed"""
438 filename, first, last = OldPdb.parse_list_cmd(self, arg)
444 filename, first, last = OldPdb.parse_list_cmd(self, arg)
439 if filename is not None:
445 if filename is not None:
440 self.print_list_lines(filename, first, last)
446 self.print_list_lines(filename, first, last)
441
447
442 def print_list_lines(self, filename, first, last):
448 def print_list_lines(self, filename, first, last):
443 """The printing (as opposed to the parsing part of a 'list'
449 """The printing (as opposed to the parsing part of a 'list'
444 command."""
450 command."""
445 try:
451 try:
446 Colors = self.color_scheme_table.active_colors
452 Colors = self.color_scheme_table.active_colors
447 ColorsNormal = Colors.Normal
453 ColorsNormal = Colors.Normal
448 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
454 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
449 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
455 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
450 src = []
456 src = []
451 if filename == "<string>" and hasattr(self, "_exec_filename"):
457 if filename == "<string>" and hasattr(self, "_exec_filename"):
452 filename = self._exec_filename
458 filename = self._exec_filename
453
459
454 for lineno in range(first, last+1):
460 for lineno in range(first, last+1):
455 line = ulinecache.getline(filename, lineno)
461 line = ulinecache.getline(filename, lineno)
456 if not line:
462 if not line:
457 break
463 break
458
464
459 if lineno == self.curframe.f_lineno:
465 if lineno == self.curframe.f_lineno:
460 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
466 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
461 else:
467 else:
462 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
468 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
463
469
464 src.append(line)
470 src.append(line)
465 self.lineno = lineno
471 self.lineno = lineno
466
472
467 print(''.join(src), file=io.stdout)
473 print(''.join(src), file=io.stdout)
468
474
469 except KeyboardInterrupt:
475 except KeyboardInterrupt:
470 pass
476 pass
471
477
472 def do_list(self, arg):
478 def do_list(self, arg):
473 self.lastcmd = 'list'
479 self.lastcmd = 'list'
474 last = None
480 last = None
475 if arg:
481 if arg:
476 try:
482 try:
477 x = eval(arg, {}, {})
483 x = eval(arg, {}, {})
478 if type(x) == type(()):
484 if type(x) == type(()):
479 first, last = x
485 first, last = x
480 first = int(first)
486 first = int(first)
481 last = int(last)
487 last = int(last)
482 if last < first:
488 if last < first:
483 # Assume it's a count
489 # Assume it's a count
484 last = first + last
490 last = first + last
485 else:
491 else:
486 first = max(1, int(x) - 5)
492 first = max(1, int(x) - 5)
487 except:
493 except:
488 print('*** Error in argument:', repr(arg))
494 print('*** Error in argument:', repr(arg))
489 return
495 return
490 elif self.lineno is None:
496 elif self.lineno is None:
491 first = max(1, self.curframe.f_lineno - 5)
497 first = max(1, self.curframe.f_lineno - 5)
492 else:
498 else:
493 first = self.lineno + 1
499 first = self.lineno + 1
494 if last is None:
500 if last is None:
495 last = first + 10
501 last = first + 10
496 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
502 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
497
503
498 # vds: >>
504 # vds: >>
499 lineno = first
505 lineno = first
500 filename = self.curframe.f_code.co_filename
506 filename = self.curframe.f_code.co_filename
501 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
507 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
502 # vds: <<
508 # vds: <<
503
509
504 do_l = do_list
510 do_l = do_list
505
511
506 def do_pdef(self, arg):
512 def do_pdef(self, arg):
507 """Print the call signature for any callable object.
513 """Print the call signature for any callable object.
508
514
509 The debugger interface to %pdef"""
515 The debugger interface to %pdef"""
510 namespaces = [('Locals', self.curframe.f_locals),
516 namespaces = [('Locals', self.curframe.f_locals),
511 ('Globals', self.curframe.f_globals)]
517 ('Globals', self.curframe.f_globals)]
512 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
518 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
513
519
514 def do_pdoc(self, arg):
520 def do_pdoc(self, arg):
515 """Print the docstring for an object.
521 """Print the docstring for an object.
516
522
517 The debugger interface to %pdoc."""
523 The debugger interface to %pdoc."""
518 namespaces = [('Locals', self.curframe.f_locals),
524 namespaces = [('Locals', self.curframe.f_locals),
519 ('Globals', self.curframe.f_globals)]
525 ('Globals', self.curframe.f_globals)]
520 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
526 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
521
527
522 def do_pfile(self, arg):
528 def do_pfile(self, arg):
523 """Print (or run through pager) the file where an object is defined.
529 """Print (or run through pager) the file where an object is defined.
524
530
525 The debugger interface to %pfile.
531 The debugger interface to %pfile.
526 """
532 """
527 namespaces = [('Locals', self.curframe.f_locals),
533 namespaces = [('Locals', self.curframe.f_locals),
528 ('Globals', self.curframe.f_globals)]
534 ('Globals', self.curframe.f_globals)]
529 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
535 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
530
536
531 def do_pinfo(self, arg):
537 def do_pinfo(self, arg):
532 """Provide detailed information about an object.
538 """Provide detailed information about an object.
533
539
534 The debugger interface to %pinfo, i.e., obj?."""
540 The debugger interface to %pinfo, i.e., obj?."""
535 namespaces = [('Locals', self.curframe.f_locals),
541 namespaces = [('Locals', self.curframe.f_locals),
536 ('Globals', self.curframe.f_globals)]
542 ('Globals', self.curframe.f_globals)]
537 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
543 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
538
544
539 def do_pinfo2(self, arg):
545 def do_pinfo2(self, arg):
540 """Provide extra detailed information about an object.
546 """Provide extra detailed information about an object.
541
547
542 The debugger interface to %pinfo2, i.e., obj??."""
548 The debugger interface to %pinfo2, i.e., obj??."""
543 namespaces = [('Locals', self.curframe.f_locals),
549 namespaces = [('Locals', self.curframe.f_locals),
544 ('Globals', self.curframe.f_globals)]
550 ('Globals', self.curframe.f_globals)]
545 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
551 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
546
552
547 def do_psource(self, arg):
553 def do_psource(self, arg):
548 """Print (or run through pager) the source code for an object."""
554 """Print (or run through pager) the source code for an object."""
549 namespaces = [('Locals', self.curframe.f_locals),
555 namespaces = [('Locals', self.curframe.f_locals),
550 ('Globals', self.curframe.f_globals)]
556 ('Globals', self.curframe.f_globals)]
551 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
557 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
552
558
553 def checkline(self, filename, lineno):
559 def checkline(self, filename, lineno):
554 """Check whether specified line seems to be executable.
560 """Check whether specified line seems to be executable.
555
561
556 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
562 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
557 line or EOF). Warning: testing is not comprehensive.
563 line or EOF). Warning: testing is not comprehensive.
558 """
564 """
559 #######################################################################
565 #######################################################################
560 # XXX Hack! Use python-2.5 compatible code for this call, because with
566 # XXX Hack! Use python-2.5 compatible code for this call, because with
561 # all of our changes, we've drifted from the pdb api in 2.6. For now,
567 # all of our changes, we've drifted from the pdb api in 2.6. For now,
562 # changing:
568 # changing:
563 #
569 #
564 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
570 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
565 # to:
571 # to:
566 #
572 #
567 line = linecache.getline(filename, lineno)
573 line = linecache.getline(filename, lineno)
568 #
574 #
569 # does the trick. But in reality, we need to fix this by reconciling
575 # does the trick. But in reality, we need to fix this by reconciling
570 # our updates with the new Pdb APIs in Python 2.6.
576 # our updates with the new Pdb APIs in Python 2.6.
571 #
577 #
572 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
578 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
573 #######################################################################
579 #######################################################################
574
580
575 if not line:
581 if not line:
576 print('End of file', file=self.stdout)
582 print('End of file', file=self.stdout)
577 return 0
583 return 0
578 line = line.strip()
584 line = line.strip()
579 # Don't allow setting breakpoint at a blank line
585 # Don't allow setting breakpoint at a blank line
580 if (not line or (line[0] == '#') or
586 if (not line or (line[0] == '#') or
581 (line[:3] == '"""') or line[:3] == "'''"):
587 (line[:3] == '"""') or line[:3] == "'''"):
582 print('*** Blank or comment', file=self.stdout)
588 print('*** Blank or comment', file=self.stdout)
583 return 0
589 return 0
584 return lineno
590 return lineno
@@ -1,706 +1,704 b''
1 """Implementation of namespace-related magic functions.
1 """Implementation of namespace-related magic functions.
2 """
2 """
3 from __future__ import print_function
3 from __future__ import print_function
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 # Stdlib
16 # Stdlib
17 import gc
17 import gc
18 import re
18 import re
19 import sys
19 import sys
20
20
21 # Our own packages
21 # Our own packages
22 from IPython.core import page
22 from IPython.core import page
23 from IPython.core.error import StdinNotImplementedError, UsageError
23 from IPython.core.error import StdinNotImplementedError, UsageError
24 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.core.magic import Magics, magics_class, line_magic
25 from IPython.testing.skipdoctest import skip_doctest
25 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.encoding import DEFAULT_ENCODING
27 from IPython.utils.openpy import read_py_file
27 from IPython.utils.openpy import read_py_file
28 from IPython.utils.path import get_py_filename
28 from IPython.utils.path import get_py_filename
29 from IPython.utils.py3compat import unicode_type
29 from IPython.utils.py3compat import unicode_type
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # Magic implementation classes
32 # Magic implementation classes
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 @magics_class
35 @magics_class
36 class NamespaceMagics(Magics):
36 class NamespaceMagics(Magics):
37 """Magics to manage various aspects of the user's namespace.
37 """Magics to manage various aspects of the user's namespace.
38
38
39 These include listing variables, introspecting into them, etc.
39 These include listing variables, introspecting into them, etc.
40 """
40 """
41
41
42 @line_magic
42 @line_magic
43 def pinfo(self, parameter_s='', namespaces=None):
43 def pinfo(self, parameter_s='', namespaces=None):
44 """Provide detailed information about an object.
44 """Provide detailed information about an object.
45
45
46 '%pinfo object' is just a synonym for object? or ?object."""
46 '%pinfo object' is just a synonym for object? or ?object."""
47
47
48 #print 'pinfo par: <%s>' % parameter_s # dbg
48 #print 'pinfo par: <%s>' % parameter_s # dbg
49 # detail_level: 0 -> obj? , 1 -> obj??
49 # detail_level: 0 -> obj? , 1 -> obj??
50 detail_level = 0
50 detail_level = 0
51 # We need to detect if we got called as 'pinfo pinfo foo', which can
51 # We need to detect if we got called as 'pinfo pinfo foo', which can
52 # happen if the user types 'pinfo foo?' at the cmd line.
52 # happen if the user types 'pinfo foo?' at the cmd line.
53 pinfo,qmark1,oname,qmark2 = \
53 pinfo,qmark1,oname,qmark2 = \
54 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
54 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
55 if pinfo or qmark1 or qmark2:
55 if pinfo or qmark1 or qmark2:
56 detail_level = 1
56 detail_level = 1
57 if "*" in oname:
57 if "*" in oname:
58 self.psearch(oname)
58 self.psearch(oname)
59 else:
59 else:
60 self.shell._inspect('pinfo', oname, detail_level=detail_level,
60 self.shell._inspect('pinfo', oname, detail_level=detail_level,
61 namespaces=namespaces)
61 namespaces=namespaces)
62
62
63 @line_magic
63 @line_magic
64 def pinfo2(self, parameter_s='', namespaces=None):
64 def pinfo2(self, parameter_s='', namespaces=None):
65 """Provide extra detailed information about an object.
65 """Provide extra detailed information about an object.
66
66
67 '%pinfo2 object' is just a synonym for object?? or ??object."""
67 '%pinfo2 object' is just a synonym for object?? or ??object."""
68 self.shell._inspect('pinfo', parameter_s, detail_level=1,
68 self.shell._inspect('pinfo', parameter_s, detail_level=1,
69 namespaces=namespaces)
69 namespaces=namespaces)
70
70
71 @skip_doctest
71 @skip_doctest
72 @line_magic
72 @line_magic
73 def pdef(self, parameter_s='', namespaces=None):
73 def pdef(self, parameter_s='', namespaces=None):
74 """Print the call signature for any callable object.
74 """Print the call signature for any callable object.
75
75
76 If the object is a class, print the constructor information.
76 If the object is a class, print the constructor information.
77
77
78 Examples
78 Examples
79 --------
79 --------
80 ::
80 ::
81
81
82 In [3]: %pdef urllib.urlopen
82 In [3]: %pdef urllib.urlopen
83 urllib.urlopen(url, data=None, proxies=None)
83 urllib.urlopen(url, data=None, proxies=None)
84 """
84 """
85 self.shell._inspect('pdef',parameter_s, namespaces)
85 self.shell._inspect('pdef',parameter_s, namespaces)
86
86
87 @line_magic
87 @line_magic
88 def pdoc(self, parameter_s='', namespaces=None):
88 def pdoc(self, parameter_s='', namespaces=None):
89 """Print the docstring for an object.
89 """Print the docstring for an object.
90
90
91 If the given object is a class, it will print both the class and the
91 If the given object is a class, it will print both the class and the
92 constructor docstrings."""
92 constructor docstrings."""
93 self.shell._inspect('pdoc',parameter_s, namespaces)
93 self.shell._inspect('pdoc',parameter_s, namespaces)
94
94
95 @line_magic
95 @line_magic
96 def psource(self, parameter_s='', namespaces=None):
96 def psource(self, parameter_s='', namespaces=None):
97 """Print (or run through pager) the source code for an object."""
97 """Print (or run through pager) the source code for an object."""
98 if not parameter_s:
98 if not parameter_s:
99 raise UsageError('Missing object name.')
99 raise UsageError('Missing object name.')
100 self.shell._inspect('psource',parameter_s, namespaces)
100 self.shell._inspect('psource',parameter_s, namespaces)
101
101
102 @line_magic
102 @line_magic
103 def pfile(self, parameter_s='', namespaces=None):
103 def pfile(self, parameter_s='', namespaces=None):
104 """Print (or run through pager) the file where an object is defined.
104 """Print (or run through pager) the file where an object is defined.
105
105
106 The file opens at the line where the object definition begins. IPython
106 The file opens at the line where the object definition begins. IPython
107 will honor the environment variable PAGER if set, and otherwise will
107 will honor the environment variable PAGER if set, and otherwise will
108 do its best to print the file in a convenient form.
108 do its best to print the file in a convenient form.
109
109
110 If the given argument is not an object currently defined, IPython will
110 If the given argument is not an object currently defined, IPython will
111 try to interpret it as a filename (automatically adding a .py extension
111 try to interpret it as a filename (automatically adding a .py extension
112 if needed). You can thus use %pfile as a syntax highlighting code
112 if needed). You can thus use %pfile as a syntax highlighting code
113 viewer."""
113 viewer."""
114
114
115 # first interpret argument as an object name
115 # first interpret argument as an object name
116 out = self.shell._inspect('pfile',parameter_s, namespaces)
116 out = self.shell._inspect('pfile',parameter_s, namespaces)
117 # if not, try the input as a filename
117 # if not, try the input as a filename
118 if out == 'not found':
118 if out == 'not found':
119 try:
119 try:
120 filename = get_py_filename(parameter_s)
120 filename = get_py_filename(parameter_s)
121 except IOError as msg:
121 except IOError as msg:
122 print(msg)
122 print(msg)
123 return
123 return
124 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
124 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
125
125
126 @line_magic
126 @line_magic
127 def psearch(self, parameter_s=''):
127 def psearch(self, parameter_s=''):
128 """Search for object in namespaces by wildcard.
128 """Search for object in namespaces by wildcard.
129
129
130 %psearch [options] PATTERN [OBJECT TYPE]
130 %psearch [options] PATTERN [OBJECT TYPE]
131
131
132 Note: ? can be used as a synonym for %psearch, at the beginning or at
132 Note: ? can be used as a synonym for %psearch, at the beginning or at
133 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
133 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
134 rest of the command line must be unchanged (options come first), so
134 rest of the command line must be unchanged (options come first), so
135 for example the following forms are equivalent
135 for example the following forms are equivalent
136
136
137 %psearch -i a* function
137 %psearch -i a* function
138 -i a* function?
138 -i a* function?
139 ?-i a* function
139 ?-i a* function
140
140
141 Arguments:
141 Arguments:
142
142
143 PATTERN
143 PATTERN
144
144
145 where PATTERN is a string containing * as a wildcard similar to its
145 where PATTERN is a string containing * as a wildcard similar to its
146 use in a shell. The pattern is matched in all namespaces on the
146 use in a shell. The pattern is matched in all namespaces on the
147 search path. By default objects starting with a single _ are not
147 search path. By default objects starting with a single _ are not
148 matched, many IPython generated objects have a single
148 matched, many IPython generated objects have a single
149 underscore. The default is case insensitive matching. Matching is
149 underscore. The default is case insensitive matching. Matching is
150 also done on the attributes of objects and not only on the objects
150 also done on the attributes of objects and not only on the objects
151 in a module.
151 in a module.
152
152
153 [OBJECT TYPE]
153 [OBJECT TYPE]
154
154
155 Is the name of a python type from the types module. The name is
155 Is the name of a python type from the types module. The name is
156 given in lowercase without the ending type, ex. StringType is
156 given in lowercase without the ending type, ex. StringType is
157 written string. By adding a type here only objects matching the
157 written string. By adding a type here only objects matching the
158 given type are matched. Using all here makes the pattern match all
158 given type are matched. Using all here makes the pattern match all
159 types (this is the default).
159 types (this is the default).
160
160
161 Options:
161 Options:
162
162
163 -a: makes the pattern match even objects whose names start with a
163 -a: makes the pattern match even objects whose names start with a
164 single underscore. These names are normally omitted from the
164 single underscore. These names are normally omitted from the
165 search.
165 search.
166
166
167 -i/-c: make the pattern case insensitive/sensitive. If neither of
167 -i/-c: make the pattern case insensitive/sensitive. If neither of
168 these options are given, the default is read from your configuration
168 these options are given, the default is read from your configuration
169 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
169 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
170 If this option is not specified in your configuration file, IPython's
170 If this option is not specified in your configuration file, IPython's
171 internal default is to do a case sensitive search.
171 internal default is to do a case sensitive search.
172
172
173 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
173 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
174 specify can be searched in any of the following namespaces:
174 specify can be searched in any of the following namespaces:
175 'builtin', 'user', 'user_global','internal', 'alias', where
175 'builtin', 'user', 'user_global','internal', 'alias', where
176 'builtin' and 'user' are the search defaults. Note that you should
176 'builtin' and 'user' are the search defaults. Note that you should
177 not use quotes when specifying namespaces.
177 not use quotes when specifying namespaces.
178
178
179 'Builtin' contains the python module builtin, 'user' contains all
179 'Builtin' contains the python module builtin, 'user' contains all
180 user data, 'alias' only contain the shell aliases and no python
180 user data, 'alias' only contain the shell aliases and no python
181 objects, 'internal' contains objects used by IPython. The
181 objects, 'internal' contains objects used by IPython. The
182 'user_global' namespace is only used by embedded IPython instances,
182 'user_global' namespace is only used by embedded IPython instances,
183 and it contains module-level globals. You can add namespaces to the
183 and it contains module-level globals. You can add namespaces to the
184 search with -s or exclude them with -e (these options can be given
184 search with -s or exclude them with -e (these options can be given
185 more than once).
185 more than once).
186
186
187 Examples
187 Examples
188 --------
188 --------
189 ::
189 ::
190
190
191 %psearch a* -> objects beginning with an a
191 %psearch a* -> objects beginning with an a
192 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
192 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
193 %psearch a* function -> all functions beginning with an a
193 %psearch a* function -> all functions beginning with an a
194 %psearch re.e* -> objects beginning with an e in module re
194 %psearch re.e* -> objects beginning with an e in module re
195 %psearch r*.e* -> objects that start with e in modules starting in r
195 %psearch r*.e* -> objects that start with e in modules starting in r
196 %psearch r*.* string -> all strings in modules beginning with r
196 %psearch r*.* string -> all strings in modules beginning with r
197
197
198 Case sensitive search::
198 Case sensitive search::
199
199
200 %psearch -c a* list all object beginning with lower case a
200 %psearch -c a* list all object beginning with lower case a
201
201
202 Show objects beginning with a single _::
202 Show objects beginning with a single _::
203
203
204 %psearch -a _* list objects beginning with a single underscore
204 %psearch -a _* list objects beginning with a single underscore
205 """
205 """
206 try:
206 try:
207 parameter_s.encode('ascii')
207 parameter_s.encode('ascii')
208 except UnicodeEncodeError:
208 except UnicodeEncodeError:
209 print('Python identifiers can only contain ascii characters.')
209 print('Python identifiers can only contain ascii characters.')
210 return
210 return
211
211
212 # default namespaces to be searched
212 # default namespaces to be searched
213 def_search = ['user_local', 'user_global', 'builtin']
213 def_search = ['user_local', 'user_global', 'builtin']
214
214
215 # Process options/args
215 # Process options/args
216 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
216 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
217 opt = opts.get
217 opt = opts.get
218 shell = self.shell
218 shell = self.shell
219 psearch = shell.inspector.psearch
219 psearch = shell.inspector.psearch
220
220
221 # select case options
221 # select case options
222 if 'i' in opts:
222 if 'i' in opts:
223 ignore_case = True
223 ignore_case = True
224 elif 'c' in opts:
224 elif 'c' in opts:
225 ignore_case = False
225 ignore_case = False
226 else:
226 else:
227 ignore_case = not shell.wildcards_case_sensitive
227 ignore_case = not shell.wildcards_case_sensitive
228
228
229 # Build list of namespaces to search from user options
229 # Build list of namespaces to search from user options
230 def_search.extend(opt('s',[]))
230 def_search.extend(opt('s',[]))
231 ns_exclude = ns_exclude=opt('e',[])
231 ns_exclude = ns_exclude=opt('e',[])
232 ns_search = [nm for nm in def_search if nm not in ns_exclude]
232 ns_search = [nm for nm in def_search if nm not in ns_exclude]
233
233
234 # Call the actual search
234 # Call the actual search
235 try:
235 try:
236 psearch(args,shell.ns_table,ns_search,
236 psearch(args,shell.ns_table,ns_search,
237 show_all=opt('a'),ignore_case=ignore_case)
237 show_all=opt('a'),ignore_case=ignore_case)
238 except:
238 except:
239 shell.showtraceback()
239 shell.showtraceback()
240
240
241 @skip_doctest
241 @skip_doctest
242 @line_magic
242 @line_magic
243 def who_ls(self, parameter_s=''):
243 def who_ls(self, parameter_s=''):
244 """Return a sorted list of all interactive variables.
244 """Return a sorted list of all interactive variables.
245
245
246 If arguments are given, only variables of types matching these
246 If arguments are given, only variables of types matching these
247 arguments are returned.
247 arguments are returned.
248
248
249 Examples
249 Examples
250 --------
250 --------
251
251
252 Define two variables and list them with who_ls::
252 Define two variables and list them with who_ls::
253
253
254 In [1]: alpha = 123
254 In [1]: alpha = 123
255
255
256 In [2]: beta = 'test'
256 In [2]: beta = 'test'
257
257
258 In [3]: %who_ls
258 In [3]: %who_ls
259 Out[3]: ['alpha', 'beta']
259 Out[3]: ['alpha', 'beta']
260
260
261 In [4]: %who_ls int
261 In [4]: %who_ls int
262 Out[4]: ['alpha']
262 Out[4]: ['alpha']
263
263
264 In [5]: %who_ls str
264 In [5]: %who_ls str
265 Out[5]: ['beta']
265 Out[5]: ['beta']
266 """
266 """
267
267
268 user_ns = self.shell.user_ns
268 user_ns = self.shell.user_ns
269 user_ns_hidden = self.shell.user_ns_hidden
269 user_ns_hidden = self.shell.user_ns_hidden
270 nonmatching = object() # This can never be in user_ns
270 nonmatching = object() # This can never be in user_ns
271 out = [ i for i in user_ns
271 out = [ i for i in user_ns
272 if not i.startswith('_') \
272 if not i.startswith('_') \
273 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
273 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
274
274
275 typelist = parameter_s.split()
275 typelist = parameter_s.split()
276 if typelist:
276 if typelist:
277 typeset = set(typelist)
277 typeset = set(typelist)
278 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
278 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
279
279
280 out.sort()
280 out.sort()
281 return out
281 return out
282
282
283 @skip_doctest
283 @skip_doctest
284 @line_magic
284 @line_magic
285 def who(self, parameter_s=''):
285 def who(self, parameter_s=''):
286 """Print all interactive variables, with some minimal formatting.
286 """Print all interactive variables, with some minimal formatting.
287
287
288 If any arguments are given, only variables whose type matches one of
288 If any arguments are given, only variables whose type matches one of
289 these are printed. For example::
289 these are printed. For example::
290
290
291 %who function str
291 %who function str
292
292
293 will only list functions and strings, excluding all other types of
293 will only list functions and strings, excluding all other types of
294 variables. To find the proper type names, simply use type(var) at a
294 variables. To find the proper type names, simply use type(var) at a
295 command line to see how python prints type names. For example:
295 command line to see how python prints type names. For example:
296
296
297 ::
297 ::
298
298
299 In [1]: type('hello')\\
299 In [1]: type('hello')\\
300 Out[1]: <type 'str'>
300 Out[1]: <type 'str'>
301
301
302 indicates that the type name for strings is 'str'.
302 indicates that the type name for strings is 'str'.
303
303
304 ``%who`` always excludes executed names loaded through your configuration
304 ``%who`` always excludes executed names loaded through your configuration
305 file and things which are internal to IPython.
305 file and things which are internal to IPython.
306
306
307 This is deliberate, as typically you may load many modules and the
307 This is deliberate, as typically you may load many modules and the
308 purpose of %who is to show you only what you've manually defined.
308 purpose of %who is to show you only what you've manually defined.
309
309
310 Examples
310 Examples
311 --------
311 --------
312
312
313 Define two variables and list them with who::
313 Define two variables and list them with who::
314
314
315 In [1]: alpha = 123
315 In [1]: alpha = 123
316
316
317 In [2]: beta = 'test'
317 In [2]: beta = 'test'
318
318
319 In [3]: %who
319 In [3]: %who
320 alpha beta
320 alpha beta
321
321
322 In [4]: %who int
322 In [4]: %who int
323 alpha
323 alpha
324
324
325 In [5]: %who str
325 In [5]: %who str
326 beta
326 beta
327 """
327 """
328
328
329 varlist = self.who_ls(parameter_s)
329 varlist = self.who_ls(parameter_s)
330 if not varlist:
330 if not varlist:
331 if parameter_s:
331 if parameter_s:
332 print('No variables match your requested type.')
332 print('No variables match your requested type.')
333 else:
333 else:
334 print('Interactive namespace is empty.')
334 print('Interactive namespace is empty.')
335 return
335 return
336
336
337 # if we have variables, move on...
337 # if we have variables, move on...
338 count = 0
338 count = 0
339 for i in varlist:
339 for i in varlist:
340 print(i+'\t', end=' ')
340 print(i+'\t', end=' ')
341 count += 1
341 count += 1
342 if count > 8:
342 if count > 8:
343 count = 0
343 count = 0
344 print()
344 print()
345 print()
345 print()
346
346
347 @skip_doctest
347 @skip_doctest
348 @line_magic
348 @line_magic
349 def whos(self, parameter_s=''):
349 def whos(self, parameter_s=''):
350 """Like %who, but gives some extra information about each variable.
350 """Like %who, but gives some extra information about each variable.
351
351
352 The same type filtering of %who can be applied here.
352 The same type filtering of %who can be applied here.
353
353
354 For all variables, the type is printed. Additionally it prints:
354 For all variables, the type is printed. Additionally it prints:
355
355
356 - For {},[],(): their length.
356 - For {},[],(): their length.
357
357
358 - For numpy arrays, a summary with shape, number of
358 - For numpy arrays, a summary with shape, number of
359 elements, typecode and size in memory.
359 elements, typecode and size in memory.
360
360
361 - Everything else: a string representation, snipping their middle if
361 - Everything else: a string representation, snipping their middle if
362 too long.
362 too long.
363
363
364 Examples
364 Examples
365 --------
365 --------
366
366
367 Define two variables and list them with whos::
367 Define two variables and list them with whos::
368
368
369 In [1]: alpha = 123
369 In [1]: alpha = 123
370
370
371 In [2]: beta = 'test'
371 In [2]: beta = 'test'
372
372
373 In [3]: %whos
373 In [3]: %whos
374 Variable Type Data/Info
374 Variable Type Data/Info
375 --------------------------------
375 --------------------------------
376 alpha int 123
376 alpha int 123
377 beta str test
377 beta str test
378 """
378 """
379
379
380 varnames = self.who_ls(parameter_s)
380 varnames = self.who_ls(parameter_s)
381 if not varnames:
381 if not varnames:
382 if parameter_s:
382 if parameter_s:
383 print('No variables match your requested type.')
383 print('No variables match your requested type.')
384 else:
384 else:
385 print('Interactive namespace is empty.')
385 print('Interactive namespace is empty.')
386 return
386 return
387
387
388 # if we have variables, move on...
388 # if we have variables, move on...
389
389
390 # for these types, show len() instead of data:
390 # for these types, show len() instead of data:
391 seq_types = ['dict', 'list', 'tuple']
391 seq_types = ['dict', 'list', 'tuple']
392
392
393 # for numpy arrays, display summary info
393 # for numpy arrays, display summary info
394 ndarray_type = None
394 ndarray_type = None
395 if 'numpy' in sys.modules:
395 if 'numpy' in sys.modules:
396 try:
396 try:
397 from numpy import ndarray
397 from numpy import ndarray
398 except ImportError:
398 except ImportError:
399 pass
399 pass
400 else:
400 else:
401 ndarray_type = ndarray.__name__
401 ndarray_type = ndarray.__name__
402
402
403 # Find all variable names and types so we can figure out column sizes
403 # Find all variable names and types so we can figure out column sizes
404 def get_vars(i):
405 return self.shell.user_ns[i]
406
404
407 # some types are well known and can be shorter
405 # some types are well known and can be shorter
408 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
406 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
409 def type_name(v):
407 def type_name(v):
410 tn = type(v).__name__
408 tn = type(v).__name__
411 return abbrevs.get(tn,tn)
409 return abbrevs.get(tn,tn)
412
410
413 varlist = map(get_vars,varnames)
411 varlist = [self.shell.user_ns[n] for n in varnames]
414
412
415 typelist = []
413 typelist = []
416 for vv in varlist:
414 for vv in varlist:
417 tt = type_name(vv)
415 tt = type_name(vv)
418
416
419 if tt=='instance':
417 if tt=='instance':
420 typelist.append( abbrevs.get(str(vv.__class__),
418 typelist.append( abbrevs.get(str(vv.__class__),
421 str(vv.__class__)))
419 str(vv.__class__)))
422 else:
420 else:
423 typelist.append(tt)
421 typelist.append(tt)
424
422
425 # column labels and # of spaces as separator
423 # column labels and # of spaces as separator
426 varlabel = 'Variable'
424 varlabel = 'Variable'
427 typelabel = 'Type'
425 typelabel = 'Type'
428 datalabel = 'Data/Info'
426 datalabel = 'Data/Info'
429 colsep = 3
427 colsep = 3
430 # variable format strings
428 # variable format strings
431 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
429 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
432 aformat = "%s: %s elems, type `%s`, %s bytes"
430 aformat = "%s: %s elems, type `%s`, %s bytes"
433 # find the size of the columns to format the output nicely
431 # find the size of the columns to format the output nicely
434 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
432 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
435 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
433 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
436 # table header
434 # table header
437 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
435 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
438 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
436 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
439 # and the table itself
437 # and the table itself
440 kb = 1024
438 kb = 1024
441 Mb = 1048576 # kb**2
439 Mb = 1048576 # kb**2
442 for vname,var,vtype in zip(varnames,varlist,typelist):
440 for vname,var,vtype in zip(varnames,varlist,typelist):
443 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
441 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
444 if vtype in seq_types:
442 if vtype in seq_types:
445 print("n="+str(len(var)))
443 print("n="+str(len(var)))
446 elif vtype == ndarray_type:
444 elif vtype == ndarray_type:
447 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
445 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
448 if vtype==ndarray_type:
446 if vtype==ndarray_type:
449 # numpy
447 # numpy
450 vsize = var.size
448 vsize = var.size
451 vbytes = vsize*var.itemsize
449 vbytes = vsize*var.itemsize
452 vdtype = var.dtype
450 vdtype = var.dtype
453
451
454 if vbytes < 100000:
452 if vbytes < 100000:
455 print(aformat % (vshape, vsize, vdtype, vbytes))
453 print(aformat % (vshape, vsize, vdtype, vbytes))
456 else:
454 else:
457 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
455 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
458 if vbytes < Mb:
456 if vbytes < Mb:
459 print('(%s kb)' % (vbytes/kb,))
457 print('(%s kb)' % (vbytes/kb,))
460 else:
458 else:
461 print('(%s Mb)' % (vbytes/Mb,))
459 print('(%s Mb)' % (vbytes/Mb,))
462 else:
460 else:
463 try:
461 try:
464 vstr = str(var)
462 vstr = str(var)
465 except UnicodeEncodeError:
463 except UnicodeEncodeError:
466 vstr = unicode_type(var).encode(DEFAULT_ENCODING,
464 vstr = unicode_type(var).encode(DEFAULT_ENCODING,
467 'backslashreplace')
465 'backslashreplace')
468 except:
466 except:
469 vstr = "<object with id %d (str() failed)>" % id(var)
467 vstr = "<object with id %d (str() failed)>" % id(var)
470 vstr = vstr.replace('\n', '\\n')
468 vstr = vstr.replace('\n', '\\n')
471 if len(vstr) < 50:
469 if len(vstr) < 50:
472 print(vstr)
470 print(vstr)
473 else:
471 else:
474 print(vstr[:25] + "<...>" + vstr[-25:])
472 print(vstr[:25] + "<...>" + vstr[-25:])
475
473
476 @line_magic
474 @line_magic
477 def reset(self, parameter_s=''):
475 def reset(self, parameter_s=''):
478 """Resets the namespace by removing all names defined by the user, if
476 """Resets the namespace by removing all names defined by the user, if
479 called without arguments, or by removing some types of objects, such
477 called without arguments, or by removing some types of objects, such
480 as everything currently in IPython's In[] and Out[] containers (see
478 as everything currently in IPython's In[] and Out[] containers (see
481 the parameters for details).
479 the parameters for details).
482
480
483 Parameters
481 Parameters
484 ----------
482 ----------
485 -f : force reset without asking for confirmation.
483 -f : force reset without asking for confirmation.
486
484
487 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
485 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
488 References to objects may be kept. By default (without this option),
486 References to objects may be kept. By default (without this option),
489 we do a 'hard' reset, giving you a new session and removing all
487 we do a 'hard' reset, giving you a new session and removing all
490 references to objects from the current session.
488 references to objects from the current session.
491
489
492 in : reset input history
490 in : reset input history
493
491
494 out : reset output history
492 out : reset output history
495
493
496 dhist : reset directory history
494 dhist : reset directory history
497
495
498 array : reset only variables that are NumPy arrays
496 array : reset only variables that are NumPy arrays
499
497
500 See Also
498 See Also
501 --------
499 --------
502 magic_reset_selective : invoked as ``%reset_selective``
500 magic_reset_selective : invoked as ``%reset_selective``
503
501
504 Examples
502 Examples
505 --------
503 --------
506 ::
504 ::
507
505
508 In [6]: a = 1
506 In [6]: a = 1
509
507
510 In [7]: a
508 In [7]: a
511 Out[7]: 1
509 Out[7]: 1
512
510
513 In [8]: 'a' in _ip.user_ns
511 In [8]: 'a' in _ip.user_ns
514 Out[8]: True
512 Out[8]: True
515
513
516 In [9]: %reset -f
514 In [9]: %reset -f
517
515
518 In [1]: 'a' in _ip.user_ns
516 In [1]: 'a' in _ip.user_ns
519 Out[1]: False
517 Out[1]: False
520
518
521 In [2]: %reset -f in
519 In [2]: %reset -f in
522 Flushing input history
520 Flushing input history
523
521
524 In [3]: %reset -f dhist in
522 In [3]: %reset -f dhist in
525 Flushing directory history
523 Flushing directory history
526 Flushing input history
524 Flushing input history
527
525
528 Notes
526 Notes
529 -----
527 -----
530 Calling this magic from clients that do not implement standard input,
528 Calling this magic from clients that do not implement standard input,
531 such as the ipython notebook interface, will reset the namespace
529 such as the ipython notebook interface, will reset the namespace
532 without confirmation.
530 without confirmation.
533 """
531 """
534 opts, args = self.parse_options(parameter_s,'sf', mode='list')
532 opts, args = self.parse_options(parameter_s,'sf', mode='list')
535 if 'f' in opts:
533 if 'f' in opts:
536 ans = True
534 ans = True
537 else:
535 else:
538 try:
536 try:
539 ans = self.shell.ask_yes_no(
537 ans = self.shell.ask_yes_no(
540 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
538 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
541 default='n')
539 default='n')
542 except StdinNotImplementedError:
540 except StdinNotImplementedError:
543 ans = True
541 ans = True
544 if not ans:
542 if not ans:
545 print('Nothing done.')
543 print('Nothing done.')
546 return
544 return
547
545
548 if 's' in opts: # Soft reset
546 if 's' in opts: # Soft reset
549 user_ns = self.shell.user_ns
547 user_ns = self.shell.user_ns
550 for i in self.who_ls():
548 for i in self.who_ls():
551 del(user_ns[i])
549 del(user_ns[i])
552 elif len(args) == 0: # Hard reset
550 elif len(args) == 0: # Hard reset
553 self.shell.reset(new_session = False)
551 self.shell.reset(new_session = False)
554
552
555 # reset in/out/dhist/array: previously extensinions/clearcmd.py
553 # reset in/out/dhist/array: previously extensinions/clearcmd.py
556 ip = self.shell
554 ip = self.shell
557 user_ns = self.shell.user_ns # local lookup, heavily used
555 user_ns = self.shell.user_ns # local lookup, heavily used
558
556
559 for target in args:
557 for target in args:
560 target = target.lower() # make matches case insensitive
558 target = target.lower() # make matches case insensitive
561 if target == 'out':
559 if target == 'out':
562 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
560 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
563 self.shell.displayhook.flush()
561 self.shell.displayhook.flush()
564
562
565 elif target == 'in':
563 elif target == 'in':
566 print("Flushing input history")
564 print("Flushing input history")
567 pc = self.shell.displayhook.prompt_count + 1
565 pc = self.shell.displayhook.prompt_count + 1
568 for n in range(1, pc):
566 for n in range(1, pc):
569 key = '_i'+repr(n)
567 key = '_i'+repr(n)
570 user_ns.pop(key,None)
568 user_ns.pop(key,None)
571 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
569 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
572 hm = ip.history_manager
570 hm = ip.history_manager
573 # don't delete these, as %save and %macro depending on the
571 # don't delete these, as %save and %macro depending on the
574 # length of these lists to be preserved
572 # length of these lists to be preserved
575 hm.input_hist_parsed[:] = [''] * pc
573 hm.input_hist_parsed[:] = [''] * pc
576 hm.input_hist_raw[:] = [''] * pc
574 hm.input_hist_raw[:] = [''] * pc
577 # hm has internal machinery for _i,_ii,_iii, clear it out
575 # hm has internal machinery for _i,_ii,_iii, clear it out
578 hm._i = hm._ii = hm._iii = hm._i00 = u''
576 hm._i = hm._ii = hm._iii = hm._i00 = u''
579
577
580 elif target == 'array':
578 elif target == 'array':
581 # Support cleaning up numpy arrays
579 # Support cleaning up numpy arrays
582 try:
580 try:
583 from numpy import ndarray
581 from numpy import ndarray
584 # This must be done with items and not iteritems because
582 # This must be done with items and not iteritems because
585 # we're going to modify the dict in-place.
583 # we're going to modify the dict in-place.
586 for x,val in user_ns.items():
584 for x,val in list(user_ns.items()):
587 if isinstance(val,ndarray):
585 if isinstance(val,ndarray):
588 del user_ns[x]
586 del user_ns[x]
589 except ImportError:
587 except ImportError:
590 print("reset array only works if Numpy is available.")
588 print("reset array only works if Numpy is available.")
591
589
592 elif target == 'dhist':
590 elif target == 'dhist':
593 print("Flushing directory history")
591 print("Flushing directory history")
594 del user_ns['_dh'][:]
592 del user_ns['_dh'][:]
595
593
596 else:
594 else:
597 print("Don't know how to reset ", end=' ')
595 print("Don't know how to reset ", end=' ')
598 print(target + ", please run `%reset?` for details")
596 print(target + ", please run `%reset?` for details")
599
597
600 gc.collect()
598 gc.collect()
601
599
602 @line_magic
600 @line_magic
603 def reset_selective(self, parameter_s=''):
601 def reset_selective(self, parameter_s=''):
604 """Resets the namespace by removing names defined by the user.
602 """Resets the namespace by removing names defined by the user.
605
603
606 Input/Output history are left around in case you need them.
604 Input/Output history are left around in case you need them.
607
605
608 %reset_selective [-f] regex
606 %reset_selective [-f] regex
609
607
610 No action is taken if regex is not included
608 No action is taken if regex is not included
611
609
612 Options
610 Options
613 -f : force reset without asking for confirmation.
611 -f : force reset without asking for confirmation.
614
612
615 See Also
613 See Also
616 --------
614 --------
617 magic_reset : invoked as ``%reset``
615 magic_reset : invoked as ``%reset``
618
616
619 Examples
617 Examples
620 --------
618 --------
621
619
622 We first fully reset the namespace so your output looks identical to
620 We first fully reset the namespace so your output looks identical to
623 this example for pedagogical reasons; in practice you do not need a
621 this example for pedagogical reasons; in practice you do not need a
624 full reset::
622 full reset::
625
623
626 In [1]: %reset -f
624 In [1]: %reset -f
627
625
628 Now, with a clean namespace we can make a few variables and use
626 Now, with a clean namespace we can make a few variables and use
629 ``%reset_selective`` to only delete names that match our regexp::
627 ``%reset_selective`` to only delete names that match our regexp::
630
628
631 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
629 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
632
630
633 In [3]: who_ls
631 In [3]: who_ls
634 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
632 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
635
633
636 In [4]: %reset_selective -f b[2-3]m
634 In [4]: %reset_selective -f b[2-3]m
637
635
638 In [5]: who_ls
636 In [5]: who_ls
639 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
637 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
640
638
641 In [6]: %reset_selective -f d
639 In [6]: %reset_selective -f d
642
640
643 In [7]: who_ls
641 In [7]: who_ls
644 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
642 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
645
643
646 In [8]: %reset_selective -f c
644 In [8]: %reset_selective -f c
647
645
648 In [9]: who_ls
646 In [9]: who_ls
649 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
647 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
650
648
651 In [10]: %reset_selective -f b
649 In [10]: %reset_selective -f b
652
650
653 In [11]: who_ls
651 In [11]: who_ls
654 Out[11]: ['a']
652 Out[11]: ['a']
655
653
656 Notes
654 Notes
657 -----
655 -----
658 Calling this magic from clients that do not implement standard input,
656 Calling this magic from clients that do not implement standard input,
659 such as the ipython notebook interface, will reset the namespace
657 such as the ipython notebook interface, will reset the namespace
660 without confirmation.
658 without confirmation.
661 """
659 """
662
660
663 opts, regex = self.parse_options(parameter_s,'f')
661 opts, regex = self.parse_options(parameter_s,'f')
664
662
665 if 'f' in opts:
663 if 'f' in opts:
666 ans = True
664 ans = True
667 else:
665 else:
668 try:
666 try:
669 ans = self.shell.ask_yes_no(
667 ans = self.shell.ask_yes_no(
670 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
668 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
671 default='n')
669 default='n')
672 except StdinNotImplementedError:
670 except StdinNotImplementedError:
673 ans = True
671 ans = True
674 if not ans:
672 if not ans:
675 print('Nothing done.')
673 print('Nothing done.')
676 return
674 return
677 user_ns = self.shell.user_ns
675 user_ns = self.shell.user_ns
678 if not regex:
676 if not regex:
679 print('No regex pattern specified. Nothing done.')
677 print('No regex pattern specified. Nothing done.')
680 return
678 return
681 else:
679 else:
682 try:
680 try:
683 m = re.compile(regex)
681 m = re.compile(regex)
684 except TypeError:
682 except TypeError:
685 raise TypeError('regex must be a string or compiled pattern')
683 raise TypeError('regex must be a string or compiled pattern')
686 for i in self.who_ls():
684 for i in self.who_ls():
687 if m.search(i):
685 if m.search(i):
688 del(user_ns[i])
686 del(user_ns[i])
689
687
690 @line_magic
688 @line_magic
691 def xdel(self, parameter_s=''):
689 def xdel(self, parameter_s=''):
692 """Delete a variable, trying to clear it from anywhere that
690 """Delete a variable, trying to clear it from anywhere that
693 IPython's machinery has references to it. By default, this uses
691 IPython's machinery has references to it. By default, this uses
694 the identity of the named object in the user namespace to remove
692 the identity of the named object in the user namespace to remove
695 references held under other names. The object is also removed
693 references held under other names. The object is also removed
696 from the output history.
694 from the output history.
697
695
698 Options
696 Options
699 -n : Delete the specified name from all namespaces, without
697 -n : Delete the specified name from all namespaces, without
700 checking their identity.
698 checking their identity.
701 """
699 """
702 opts, varname = self.parse_options(parameter_s,'n')
700 opts, varname = self.parse_options(parameter_s,'n')
703 try:
701 try:
704 self.shell.del_var(varname, ('n' in opts))
702 self.shell.del_var(varname, ('n' in opts))
705 except (NameError, ValueError) as e:
703 except (NameError, ValueError) as e:
706 print(type(e).__name__ +": "+ str(e))
704 print(type(e).__name__ +": "+ str(e))
@@ -1,393 +1,393 b''
1 """Tests for the IPython tab-completion machinery.
1 """Tests for the IPython tab-completion machinery.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import sys
9 import sys
10 import unittest
10 import unittest
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.config.loader import Config
16 from IPython.config.loader import Config
17 from IPython.core import completer
17 from IPython.core import completer
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21 from IPython.utils.py3compat import string_types, unicode_type
21 from IPython.utils.py3compat import string_types, unicode_type
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions
24 # Test functions
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 def test_protect_filename():
26 def test_protect_filename():
27 pairs = [ ('abc','abc'),
27 pairs = [ ('abc','abc'),
28 (' abc',r'\ abc'),
28 (' abc',r'\ abc'),
29 ('a bc',r'a\ bc'),
29 ('a bc',r'a\ bc'),
30 ('a bc',r'a\ \ bc'),
30 ('a bc',r'a\ \ bc'),
31 (' bc',r'\ \ bc'),
31 (' bc',r'\ \ bc'),
32 ]
32 ]
33 # On posix, we also protect parens and other special characters
33 # On posix, we also protect parens and other special characters
34 if sys.platform != 'win32':
34 if sys.platform != 'win32':
35 pairs.extend( [('a(bc',r'a\(bc'),
35 pairs.extend( [('a(bc',r'a\(bc'),
36 ('a)bc',r'a\)bc'),
36 ('a)bc',r'a\)bc'),
37 ('a( )bc',r'a\(\ \)bc'),
37 ('a( )bc',r'a\(\ \)bc'),
38 ('a[1]bc', r'a\[1\]bc'),
38 ('a[1]bc', r'a\[1\]bc'),
39 ('a{1}bc', r'a\{1\}bc'),
39 ('a{1}bc', r'a\{1\}bc'),
40 ('a#bc', r'a\#bc'),
40 ('a#bc', r'a\#bc'),
41 ('a?bc', r'a\?bc'),
41 ('a?bc', r'a\?bc'),
42 ('a=bc', r'a\=bc'),
42 ('a=bc', r'a\=bc'),
43 ('a\\bc', r'a\\bc'),
43 ('a\\bc', r'a\\bc'),
44 ('a|bc', r'a\|bc'),
44 ('a|bc', r'a\|bc'),
45 ('a;bc', r'a\;bc'),
45 ('a;bc', r'a\;bc'),
46 ('a:bc', r'a\:bc'),
46 ('a:bc', r'a\:bc'),
47 ("a'bc", r"a\'bc"),
47 ("a'bc", r"a\'bc"),
48 ('a*bc', r'a\*bc'),
48 ('a*bc', r'a\*bc'),
49 ('a"bc', r'a\"bc'),
49 ('a"bc', r'a\"bc'),
50 ('a^bc', r'a\^bc'),
50 ('a^bc', r'a\^bc'),
51 ('a&bc', r'a\&bc'),
51 ('a&bc', r'a\&bc'),
52 ] )
52 ] )
53 # run the actual tests
53 # run the actual tests
54 for s1, s2 in pairs:
54 for s1, s2 in pairs:
55 s1p = completer.protect_filename(s1)
55 s1p = completer.protect_filename(s1)
56 nt.assert_equal(s1p, s2)
56 nt.assert_equal(s1p, s2)
57
57
58
58
59 def check_line_split(splitter, test_specs):
59 def check_line_split(splitter, test_specs):
60 for part1, part2, split in test_specs:
60 for part1, part2, split in test_specs:
61 cursor_pos = len(part1)
61 cursor_pos = len(part1)
62 line = part1+part2
62 line = part1+part2
63 out = splitter.split_line(line, cursor_pos)
63 out = splitter.split_line(line, cursor_pos)
64 nt.assert_equal(out, split)
64 nt.assert_equal(out, split)
65
65
66
66
67 def test_line_split():
67 def test_line_split():
68 """Basice line splitter test with default specs."""
68 """Basic line splitter test with default specs."""
69 sp = completer.CompletionSplitter()
69 sp = completer.CompletionSplitter()
70 # The format of the test specs is: part1, part2, expected answer. Parts 1
70 # The format of the test specs is: part1, part2, expected answer. Parts 1
71 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
71 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
72 # was at the end of part1. So an empty part2 represents someone hitting
72 # was at the end of part1. So an empty part2 represents someone hitting
73 # tab at the end of the line, the most common case.
73 # tab at the end of the line, the most common case.
74 t = [('run some/scrip', '', 'some/scrip'),
74 t = [('run some/scrip', '', 'some/scrip'),
75 ('run scripts/er', 'ror.py foo', 'scripts/er'),
75 ('run scripts/er', 'ror.py foo', 'scripts/er'),
76 ('echo $HOM', '', 'HOM'),
76 ('echo $HOM', '', 'HOM'),
77 ('print sys.pa', '', 'sys.pa'),
77 ('print sys.pa', '', 'sys.pa'),
78 ('print(sys.pa', '', 'sys.pa'),
78 ('print(sys.pa', '', 'sys.pa'),
79 ("execfile('scripts/er", '', 'scripts/er'),
79 ("execfile('scripts/er", '', 'scripts/er'),
80 ('a[x.', '', 'x.'),
80 ('a[x.', '', 'x.'),
81 ('a[x.', 'y', 'x.'),
81 ('a[x.', 'y', 'x.'),
82 ('cd "some_file/', '', 'some_file/'),
82 ('cd "some_file/', '', 'some_file/'),
83 ]
83 ]
84 check_line_split(sp, t)
84 check_line_split(sp, t)
85 # Ensure splitting works OK with unicode by re-running the tests with
85 # Ensure splitting works OK with unicode by re-running the tests with
86 # all inputs turned into unicode
86 # all inputs turned into unicode
87 check_line_split(sp, [ map(unicode_type, p) for p in t] )
87 check_line_split(sp, [ map(unicode_type, p) for p in t] )
88
88
89
89
90 def test_custom_completion_error():
90 def test_custom_completion_error():
91 """Test that errors from custom attribute completers are silenced."""
91 """Test that errors from custom attribute completers are silenced."""
92 ip = get_ipython()
92 ip = get_ipython()
93 class A(object): pass
93 class A(object): pass
94 ip.user_ns['a'] = A()
94 ip.user_ns['a'] = A()
95
95
96 @complete_object.when_type(A)
96 @complete_object.when_type(A)
97 def complete_A(a, existing_completions):
97 def complete_A(a, existing_completions):
98 raise TypeError("this should be silenced")
98 raise TypeError("this should be silenced")
99
99
100 ip.complete("a.")
100 ip.complete("a.")
101
101
102
102
103 def test_unicode_completions():
103 def test_unicode_completions():
104 ip = get_ipython()
104 ip = get_ipython()
105 # Some strings that trigger different types of completion. Check them both
105 # Some strings that trigger different types of completion. Check them both
106 # in str and unicode forms
106 # in str and unicode forms
107 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
108 for t in s + map(unicode_type, s):
108 for t in s + list(map(unicode_type, s)):
109 # We don't need to check exact completion values (they may change
109 # We don't need to check exact completion values (they may change
110 # depending on the state of the namespace, but at least no exceptions
110 # depending on the state of the namespace, but at least no exceptions
111 # should be thrown and the return value should be a pair of text, list
111 # should be thrown and the return value should be a pair of text, list
112 # values.
112 # values.
113 text, matches = ip.complete(t)
113 text, matches = ip.complete(t)
114 nt.assert_true(isinstance(text, string_types))
114 nt.assert_true(isinstance(text, string_types))
115 nt.assert_true(isinstance(matches, list))
115 nt.assert_true(isinstance(matches, list))
116
116
117
117
118 class CompletionSplitterTestCase(unittest.TestCase):
118 class CompletionSplitterTestCase(unittest.TestCase):
119 def setUp(self):
119 def setUp(self):
120 self.sp = completer.CompletionSplitter()
120 self.sp = completer.CompletionSplitter()
121
121
122 def test_delim_setting(self):
122 def test_delim_setting(self):
123 self.sp.delims = ' '
123 self.sp.delims = ' '
124 nt.assert_equal(self.sp.delims, ' ')
124 nt.assert_equal(self.sp.delims, ' ')
125 nt.assert_equal(self.sp._delim_expr, '[\ ]')
125 nt.assert_equal(self.sp._delim_expr, '[\ ]')
126
126
127 def test_spaces(self):
127 def test_spaces(self):
128 """Test with only spaces as split chars."""
128 """Test with only spaces as split chars."""
129 self.sp.delims = ' '
129 self.sp.delims = ' '
130 t = [('foo', '', 'foo'),
130 t = [('foo', '', 'foo'),
131 ('run foo', '', 'foo'),
131 ('run foo', '', 'foo'),
132 ('run foo', 'bar', 'foo'),
132 ('run foo', 'bar', 'foo'),
133 ]
133 ]
134 check_line_split(self.sp, t)
134 check_line_split(self.sp, t)
135
135
136
136
137 def test_has_open_quotes1():
137 def test_has_open_quotes1():
138 for s in ["'", "'''", "'hi' '"]:
138 for s in ["'", "'''", "'hi' '"]:
139 nt.assert_equal(completer.has_open_quotes(s), "'")
139 nt.assert_equal(completer.has_open_quotes(s), "'")
140
140
141
141
142 def test_has_open_quotes2():
142 def test_has_open_quotes2():
143 for s in ['"', '"""', '"hi" "']:
143 for s in ['"', '"""', '"hi" "']:
144 nt.assert_equal(completer.has_open_quotes(s), '"')
144 nt.assert_equal(completer.has_open_quotes(s), '"')
145
145
146
146
147 def test_has_open_quotes3():
147 def test_has_open_quotes3():
148 for s in ["''", "''' '''", "'hi' 'ipython'"]:
148 for s in ["''", "''' '''", "'hi' 'ipython'"]:
149 nt.assert_false(completer.has_open_quotes(s))
149 nt.assert_false(completer.has_open_quotes(s))
150
150
151
151
152 def test_has_open_quotes4():
152 def test_has_open_quotes4():
153 for s in ['""', '""" """', '"hi" "ipython"']:
153 for s in ['""', '""" """', '"hi" "ipython"']:
154 nt.assert_false(completer.has_open_quotes(s))
154 nt.assert_false(completer.has_open_quotes(s))
155
155
156
156
157 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
157 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
158 def test_abspath_file_completions():
158 def test_abspath_file_completions():
159 ip = get_ipython()
159 ip = get_ipython()
160 with TemporaryDirectory() as tmpdir:
160 with TemporaryDirectory() as tmpdir:
161 prefix = os.path.join(tmpdir, 'foo')
161 prefix = os.path.join(tmpdir, 'foo')
162 suffixes = map(str, [1,2])
162 suffixes = ['1', '2']
163 names = [prefix+s for s in suffixes]
163 names = [prefix+s for s in suffixes]
164 for n in names:
164 for n in names:
165 open(n, 'w').close()
165 open(n, 'w').close()
166
166
167 # Check simple completion
167 # Check simple completion
168 c = ip.complete(prefix)[1]
168 c = ip.complete(prefix)[1]
169 nt.assert_equal(c, names)
169 nt.assert_equal(c, names)
170
170
171 # Now check with a function call
171 # Now check with a function call
172 cmd = 'a = f("%s' % prefix
172 cmd = 'a = f("%s' % prefix
173 c = ip.complete(prefix, cmd)[1]
173 c = ip.complete(prefix, cmd)[1]
174 comp = [prefix+s for s in suffixes]
174 comp = [prefix+s for s in suffixes]
175 nt.assert_equal(c, comp)
175 nt.assert_equal(c, comp)
176
176
177
177
178 def test_local_file_completions():
178 def test_local_file_completions():
179 ip = get_ipython()
179 ip = get_ipython()
180 cwd = os.getcwdu()
180 cwd = os.getcwdu()
181 try:
181 try:
182 with TemporaryDirectory() as tmpdir:
182 with TemporaryDirectory() as tmpdir:
183 os.chdir(tmpdir)
183 os.chdir(tmpdir)
184 prefix = './foo'
184 prefix = './foo'
185 suffixes = map(str, [1,2])
185 suffixes = ['1', '2']
186 names = [prefix+s for s in suffixes]
186 names = [prefix+s for s in suffixes]
187 for n in names:
187 for n in names:
188 open(n, 'w').close()
188 open(n, 'w').close()
189
189
190 # Check simple completion
190 # Check simple completion
191 c = ip.complete(prefix)[1]
191 c = ip.complete(prefix)[1]
192 nt.assert_equal(c, names)
192 nt.assert_equal(c, names)
193
193
194 # Now check with a function call
194 # Now check with a function call
195 cmd = 'a = f("%s' % prefix
195 cmd = 'a = f("%s' % prefix
196 c = ip.complete(prefix, cmd)[1]
196 c = ip.complete(prefix, cmd)[1]
197 comp = [prefix+s for s in suffixes]
197 comp = [prefix+s for s in suffixes]
198 nt.assert_equal(c, comp)
198 nt.assert_equal(c, comp)
199 finally:
199 finally:
200 # prevent failures from making chdir stick
200 # prevent failures from making chdir stick
201 os.chdir(cwd)
201 os.chdir(cwd)
202
202
203
203
204 def test_greedy_completions():
204 def test_greedy_completions():
205 ip = get_ipython()
205 ip = get_ipython()
206 greedy_original = ip.Completer.greedy
206 greedy_original = ip.Completer.greedy
207 try:
207 try:
208 ip.Completer.greedy = False
208 ip.Completer.greedy = False
209 ip.ex('a=range(5)')
209 ip.ex('a=list(range(5))')
210 _,c = ip.complete('.',line='a[0].')
210 _,c = ip.complete('.',line='a[0].')
211 nt.assert_false('a[0].real' in c,
211 nt.assert_false('a[0].real' in c,
212 "Shouldn't have completed on a[0]: %s"%c)
212 "Shouldn't have completed on a[0]: %s"%c)
213 ip.Completer.greedy = True
213 ip.Completer.greedy = True
214 _,c = ip.complete('.',line='a[0].')
214 _,c = ip.complete('.',line='a[0].')
215 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
215 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
216 finally:
216 finally:
217 ip.Completer.greedy = greedy_original
217 ip.Completer.greedy = greedy_original
218
218
219
219
220 def test_omit__names():
220 def test_omit__names():
221 # also happens to test IPCompleter as a configurable
221 # also happens to test IPCompleter as a configurable
222 ip = get_ipython()
222 ip = get_ipython()
223 ip._hidden_attr = 1
223 ip._hidden_attr = 1
224 c = ip.Completer
224 c = ip.Completer
225 ip.ex('ip=get_ipython()')
225 ip.ex('ip=get_ipython()')
226 cfg = Config()
226 cfg = Config()
227 cfg.IPCompleter.omit__names = 0
227 cfg.IPCompleter.omit__names = 0
228 c.update_config(cfg)
228 c.update_config(cfg)
229 s,matches = c.complete('ip.')
229 s,matches = c.complete('ip.')
230 nt.assert_true('ip.__str__' in matches)
230 nt.assert_in('ip.__str__', matches)
231 nt.assert_true('ip._hidden_attr' in matches)
231 nt.assert_in('ip._hidden_attr', matches)
232 cfg.IPCompleter.omit__names = 1
232 cfg.IPCompleter.omit__names = 1
233 c.update_config(cfg)
233 c.update_config(cfg)
234 s,matches = c.complete('ip.')
234 s,matches = c.complete('ip.')
235 nt.assert_false('ip.__str__' in matches)
235 nt.assert_not_in('ip.__str__', matches)
236 nt.assert_true('ip._hidden_attr' in matches)
236 nt.assert_in('ip._hidden_attr', matches)
237 cfg.IPCompleter.omit__names = 2
237 cfg.IPCompleter.omit__names = 2
238 c.update_config(cfg)
238 c.update_config(cfg)
239 s,matches = c.complete('ip.')
239 s,matches = c.complete('ip.')
240 nt.assert_false('ip.__str__' in matches)
240 nt.assert_not_in('ip.__str__', matches)
241 nt.assert_false('ip._hidden_attr' in matches)
241 nt.assert_not_in('ip._hidden_attr', matches)
242 del ip._hidden_attr
242 del ip._hidden_attr
243
243
244
244
245 def test_limit_to__all__False_ok():
245 def test_limit_to__all__False_ok():
246 ip = get_ipython()
246 ip = get_ipython()
247 c = ip.Completer
247 c = ip.Completer
248 ip.ex('class D: x=24')
248 ip.ex('class D: x=24')
249 ip.ex('d=D()')
249 ip.ex('d=D()')
250 cfg = Config()
250 cfg = Config()
251 cfg.IPCompleter.limit_to__all__ = False
251 cfg.IPCompleter.limit_to__all__ = False
252 c.update_config(cfg)
252 c.update_config(cfg)
253 s, matches = c.complete('d.')
253 s, matches = c.complete('d.')
254 nt.assert_true('d.x' in matches)
254 nt.assert_in('d.x', matches)
255
255
256
256
257 def test_limit_to__all__True_ok():
257 def test_limit_to__all__True_ok():
258 ip = get_ipython()
258 ip = get_ipython()
259 c = ip.Completer
259 c = ip.Completer
260 ip.ex('class D: x=24')
260 ip.ex('class D: x=24')
261 ip.ex('d=D()')
261 ip.ex('d=D()')
262 ip.ex("d.__all__=['z']")
262 ip.ex("d.__all__=['z']")
263 cfg = Config()
263 cfg = Config()
264 cfg.IPCompleter.limit_to__all__ = True
264 cfg.IPCompleter.limit_to__all__ = True
265 c.update_config(cfg)
265 c.update_config(cfg)
266 s, matches = c.complete('d.')
266 s, matches = c.complete('d.')
267 nt.assert_true('d.z' in matches)
267 nt.assert_in('d.z', matches)
268 nt.assert_false('d.x' in matches)
268 nt.assert_not_in('d.x', matches)
269
269
270
270
271 def test_get__all__entries_ok():
271 def test_get__all__entries_ok():
272 class A(object):
272 class A(object):
273 __all__ = ['x', 1]
273 __all__ = ['x', 1]
274 words = completer.get__all__entries(A())
274 words = completer.get__all__entries(A())
275 nt.assert_equal(words, ['x'])
275 nt.assert_equal(words, ['x'])
276
276
277
277
278 def test_get__all__entries_no__all__ok():
278 def test_get__all__entries_no__all__ok():
279 class A(object):
279 class A(object):
280 pass
280 pass
281 words = completer.get__all__entries(A())
281 words = completer.get__all__entries(A())
282 nt.assert_equal(words, [])
282 nt.assert_equal(words, [])
283
283
284
284
285 def test_func_kw_completions():
285 def test_func_kw_completions():
286 ip = get_ipython()
286 ip = get_ipython()
287 c = ip.Completer
287 c = ip.Completer
288 ip.ex('def myfunc(a=1,b=2): return a+b')
288 ip.ex('def myfunc(a=1,b=2): return a+b')
289 s, matches = c.complete(None, 'myfunc(1,b')
289 s, matches = c.complete(None, 'myfunc(1,b')
290 nt.assert_in('b=', matches)
290 nt.assert_in('b=', matches)
291 # Simulate completing with cursor right after b (pos==10):
291 # Simulate completing with cursor right after b (pos==10):
292 s, matches = c.complete(None, 'myfunc(1,b)', 10)
292 s, matches = c.complete(None, 'myfunc(1,b)', 10)
293 nt.assert_in('b=', matches)
293 nt.assert_in('b=', matches)
294 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
294 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
295 nt.assert_in('b=', matches)
295 nt.assert_in('b=', matches)
296 #builtin function
296 #builtin function
297 s, matches = c.complete(None, 'min(k, k')
297 s, matches = c.complete(None, 'min(k, k')
298 nt.assert_in('key=', matches)
298 nt.assert_in('key=', matches)
299
299
300
300
301 def test_default_arguments_from_docstring():
301 def test_default_arguments_from_docstring():
302 doc = min.__doc__
302 doc = min.__doc__
303 ip = get_ipython()
303 ip = get_ipython()
304 c = ip.Completer
304 c = ip.Completer
305 kwd = c._default_arguments_from_docstring(
305 kwd = c._default_arguments_from_docstring(
306 'min(iterable[, key=func]) -> value')
306 'min(iterable[, key=func]) -> value')
307 nt.assert_equal(kwd, ['key'])
307 nt.assert_equal(kwd, ['key'])
308 #with cython type etc
308 #with cython type etc
309 kwd = c._default_arguments_from_docstring(
309 kwd = c._default_arguments_from_docstring(
310 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
310 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
311 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
311 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
312 #white spaces
312 #white spaces
313 kwd = c._default_arguments_from_docstring(
313 kwd = c._default_arguments_from_docstring(
314 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
314 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
315 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
315 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
316
316
317 def test_line_magics():
317 def test_line_magics():
318 ip = get_ipython()
318 ip = get_ipython()
319 c = ip.Completer
319 c = ip.Completer
320 s, matches = c.complete(None, 'lsmag')
320 s, matches = c.complete(None, 'lsmag')
321 nt.assert_in('%lsmagic', matches)
321 nt.assert_in('%lsmagic', matches)
322 s, matches = c.complete(None, '%lsmag')
322 s, matches = c.complete(None, '%lsmag')
323 nt.assert_in('%lsmagic', matches)
323 nt.assert_in('%lsmagic', matches)
324
324
325
325
326 def test_cell_magics():
326 def test_cell_magics():
327 from IPython.core.magic import register_cell_magic
327 from IPython.core.magic import register_cell_magic
328
328
329 @register_cell_magic
329 @register_cell_magic
330 def _foo_cellm(line, cell):
330 def _foo_cellm(line, cell):
331 pass
331 pass
332
332
333 ip = get_ipython()
333 ip = get_ipython()
334 c = ip.Completer
334 c = ip.Completer
335
335
336 s, matches = c.complete(None, '_foo_ce')
336 s, matches = c.complete(None, '_foo_ce')
337 nt.assert_in('%%_foo_cellm', matches)
337 nt.assert_in('%%_foo_cellm', matches)
338 s, matches = c.complete(None, '%%_foo_ce')
338 s, matches = c.complete(None, '%%_foo_ce')
339 nt.assert_in('%%_foo_cellm', matches)
339 nt.assert_in('%%_foo_cellm', matches)
340
340
341
341
342 def test_line_cell_magics():
342 def test_line_cell_magics():
343 from IPython.core.magic import register_line_cell_magic
343 from IPython.core.magic import register_line_cell_magic
344
344
345 @register_line_cell_magic
345 @register_line_cell_magic
346 def _bar_cellm(line, cell):
346 def _bar_cellm(line, cell):
347 pass
347 pass
348
348
349 ip = get_ipython()
349 ip = get_ipython()
350 c = ip.Completer
350 c = ip.Completer
351
351
352 # The policy here is trickier, see comments in completion code. The
352 # The policy here is trickier, see comments in completion code. The
353 # returned values depend on whether the user passes %% or not explicitly,
353 # returned values depend on whether the user passes %% or not explicitly,
354 # and this will show a difference if the same name is both a line and cell
354 # and this will show a difference if the same name is both a line and cell
355 # magic.
355 # magic.
356 s, matches = c.complete(None, '_bar_ce')
356 s, matches = c.complete(None, '_bar_ce')
357 nt.assert_in('%_bar_cellm', matches)
357 nt.assert_in('%_bar_cellm', matches)
358 nt.assert_in('%%_bar_cellm', matches)
358 nt.assert_in('%%_bar_cellm', matches)
359 s, matches = c.complete(None, '%_bar_ce')
359 s, matches = c.complete(None, '%_bar_ce')
360 nt.assert_in('%_bar_cellm', matches)
360 nt.assert_in('%_bar_cellm', matches)
361 nt.assert_in('%%_bar_cellm', matches)
361 nt.assert_in('%%_bar_cellm', matches)
362 s, matches = c.complete(None, '%%_bar_ce')
362 s, matches = c.complete(None, '%%_bar_ce')
363 nt.assert_not_in('%_bar_cellm', matches)
363 nt.assert_not_in('%_bar_cellm', matches)
364 nt.assert_in('%%_bar_cellm', matches)
364 nt.assert_in('%%_bar_cellm', matches)
365
365
366
366
367 def test_magic_completion_order():
367 def test_magic_completion_order():
368
368
369 ip = get_ipython()
369 ip = get_ipython()
370 c = ip.Completer
370 c = ip.Completer
371
371
372 # Test ordering of magics and non-magics with the same name
372 # Test ordering of magics and non-magics with the same name
373 # We want the non-magic first
373 # We want the non-magic first
374
374
375 # Before importing matplotlib, there should only be one option:
375 # Before importing matplotlib, there should only be one option:
376
376
377 text, matches = c.complete('mat')
377 text, matches = c.complete('mat')
378 nt.assert_equal(matches, ["%matplotlib"])
378 nt.assert_equal(matches, ["%matplotlib"])
379
379
380
380
381 ip.run_cell("matplotlib = 1") # introduce name into namespace
381 ip.run_cell("matplotlib = 1") # introduce name into namespace
382
382
383 # After the import, there should be two options, ordered like this:
383 # After the import, there should be two options, ordered like this:
384 text, matches = c.complete('mat')
384 text, matches = c.complete('mat')
385 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
385 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
386
386
387
387
388 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
388 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
389
389
390 # Order of user variable and line and cell magics with same name:
390 # Order of user variable and line and cell magics with same name:
391 text, matches = c.complete('timeit')
391 text, matches = c.complete('timeit')
392 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
392 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
393
393
@@ -1,154 +1,157 b''
1 """Tests for debugging machinery.
1 """Tests for debugging machinery.
2 """
2 """
3 from __future__ import print_function
3 from __future__ import print_function
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012, The IPython Development Team.
5 # Copyright (c) 2012, The IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import sys
16 import sys
17
17
18 # third-party
18 # third-party
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 # Our own
21 # Our own
22 from IPython.core import debugger
22 from IPython.core import debugger
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Helper classes, from CPython's Pdb test suite
25 # Helper classes, from CPython's Pdb test suite
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 class _FakeInput(object):
28 class _FakeInput(object):
29 """
29 """
30 A fake input stream for pdb's interactive debugger. Whenever a
30 A fake input stream for pdb's interactive debugger. Whenever a
31 line is read, print it (to simulate the user typing it), and then
31 line is read, print it (to simulate the user typing it), and then
32 return it. The set of lines to return is specified in the
32 return it. The set of lines to return is specified in the
33 constructor; they should not have trailing newlines.
33 constructor; they should not have trailing newlines.
34 """
34 """
35 def __init__(self, lines):
35 def __init__(self, lines):
36 self.lines = iter(lines)
36 self.lines = iter(lines)
37
37
38 def readline(self):
38 def readline(self):
39 line = next(self.lines)
39 line = next(self.lines)
40 print(line)
40 print(line)
41 return line+'\n'
41 return line+'\n'
42
42
43 class PdbTestInput(object):
43 class PdbTestInput(object):
44 """Context manager that makes testing Pdb in doctests easier."""
44 """Context manager that makes testing Pdb in doctests easier."""
45
45
46 def __init__(self, input):
46 def __init__(self, input):
47 self.input = input
47 self.input = input
48
48
49 def __enter__(self):
49 def __enter__(self):
50 self.real_stdin = sys.stdin
50 self.real_stdin = sys.stdin
51 sys.stdin = _FakeInput(self.input)
51 sys.stdin = _FakeInput(self.input)
52
52
53 def __exit__(self, *exc):
53 def __exit__(self, *exc):
54 sys.stdin = self.real_stdin
54 sys.stdin = self.real_stdin
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 # Tests
57 # Tests
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59
59
60 def test_longer_repr():
60 def test_longer_repr():
61 from reprlib import repr as trepr
61 try:
62 from reprlib import repr as trepr # Py 3
63 except ImportError:
64 from repr import repr as trepr # Py 2
62
65
63 a = '1234567890'* 7
66 a = '1234567890'* 7
64 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
67 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
65 a_trunc = "'123456789012...8901234567890'"
68 a_trunc = "'123456789012...8901234567890'"
66 nt.assert_equal(trepr(a), a_trunc)
69 nt.assert_equal(trepr(a), a_trunc)
67 # The creation of our tracer modifies the repr module's repr function
70 # The creation of our tracer modifies the repr module's repr function
68 # in-place, since that global is used directly by the stdlib's pdb module.
71 # in-place, since that global is used directly by the stdlib's pdb module.
69 t = debugger.Tracer()
72 t = debugger.Tracer()
70 nt.assert_equal(trepr(a), ar)
73 nt.assert_equal(trepr(a), ar)
71
74
72 def test_ipdb_magics():
75 def test_ipdb_magics():
73 '''Test calling some IPython magics from ipdb.
76 '''Test calling some IPython magics from ipdb.
74
77
75 First, set up some test functions and classes which we can inspect.
78 First, set up some test functions and classes which we can inspect.
76
79
77 >>> class ExampleClass(object):
80 >>> class ExampleClass(object):
78 ... """Docstring for ExampleClass."""
81 ... """Docstring for ExampleClass."""
79 ... def __init__(self):
82 ... def __init__(self):
80 ... """Docstring for ExampleClass.__init__"""
83 ... """Docstring for ExampleClass.__init__"""
81 ... pass
84 ... pass
82 ... def __str__(self):
85 ... def __str__(self):
83 ... return "ExampleClass()"
86 ... return "ExampleClass()"
84
87
85 >>> def example_function(x, y, z="hello"):
88 >>> def example_function(x, y, z="hello"):
86 ... """Docstring for example_function."""
89 ... """Docstring for example_function."""
87 ... pass
90 ... pass
88
91
89 >>> old_trace = sys.gettrace()
92 >>> old_trace = sys.gettrace()
90
93
91 Create a function which triggers ipdb.
94 Create a function which triggers ipdb.
92
95
93 >>> def trigger_ipdb():
96 >>> def trigger_ipdb():
94 ... a = ExampleClass()
97 ... a = ExampleClass()
95 ... debugger.Pdb().set_trace()
98 ... debugger.Pdb().set_trace()
96
99
97 >>> with PdbTestInput([
100 >>> with PdbTestInput([
98 ... 'pdef example_function',
101 ... 'pdef example_function',
99 ... 'pdoc ExampleClass',
102 ... 'pdoc ExampleClass',
100 ... 'pinfo a',
103 ... 'pinfo a',
101 ... 'continue',
104 ... 'continue',
102 ... ]):
105 ... ]):
103 ... trigger_ipdb()
106 ... trigger_ipdb()
104 --Return--
107 --Return--
105 None
108 None
106 > <doctest ...>(3)trigger_ipdb()
109 > <doctest ...>(3)trigger_ipdb()
107 1 def trigger_ipdb():
110 1 def trigger_ipdb():
108 2 a = ExampleClass()
111 2 a = ExampleClass()
109 ----> 3 debugger.Pdb().set_trace()
112 ----> 3 debugger.Pdb().set_trace()
110 <BLANKLINE>
113 <BLANKLINE>
111 ipdb> pdef example_function
114 ipdb> pdef example_function
112 example_function(x, y, z='hello')
115 example_function(x, y, z='hello')
113 ipdb> pdoc ExampleClass
116 ipdb> pdoc ExampleClass
114 Class Docstring:
117 Class Docstring:
115 Docstring for ExampleClass.
118 Docstring for ExampleClass.
116 Constructor Docstring:
119 Constructor Docstring:
117 Docstring for ExampleClass.__init__
120 Docstring for ExampleClass.__init__
118 ipdb> pinfo a
121 ipdb> pinfo a
119 Type: ExampleClass
122 Type: ExampleClass
120 String Form:ExampleClass()
123 String Form:ExampleClass()
121 Namespace: Local...
124 Namespace: Local...
122 Docstring: Docstring for ExampleClass.
125 Docstring: Docstring for ExampleClass.
123 Constructor Docstring:Docstring for ExampleClass.__init__
126 Constructor Docstring:Docstring for ExampleClass.__init__
124 ipdb> continue
127 ipdb> continue
125
128
126 Restore previous trace function, e.g. for coverage.py
129 Restore previous trace function, e.g. for coverage.py
127
130
128 >>> sys.settrace(old_trace)
131 >>> sys.settrace(old_trace)
129 '''
132 '''
130
133
131 def test_ipdb_magics2():
134 def test_ipdb_magics2():
132 '''Test ipdb with a very short function.
135 '''Test ipdb with a very short function.
133
136
134 >>> old_trace = sys.gettrace()
137 >>> old_trace = sys.gettrace()
135
138
136 >>> def bar():
139 >>> def bar():
137 ... pass
140 ... pass
138
141
139 Run ipdb.
142 Run ipdb.
140
143
141 >>> with PdbTestInput([
144 >>> with PdbTestInput([
142 ... 'continue',
145 ... 'continue',
143 ... ]):
146 ... ]):
144 ... debugger.Pdb().runcall(bar)
147 ... debugger.Pdb().runcall(bar)
145 > <doctest ...>(2)bar()
148 > <doctest ...>(2)bar()
146 1 def bar():
149 1 def bar():
147 ----> 2 pass
150 ----> 2 pass
148 <BLANKLINE>
151 <BLANKLINE>
149 ipdb> continue
152 ipdb> continue
150
153
151 Restore previous trace function, e.g. for coverage.py
154 Restore previous trace function, e.g. for coverage.py
152
155
153 >>> sys.settrace(old_trace)
156 >>> sys.settrace(old_trace)
154 '''
157 '''
@@ -1,205 +1,210 b''
1 """Tests for various magic functions specific to the terminal frontend.
1 """Tests for various magic functions specific to the terminal frontend.
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 sys
11 import sys
12 from io import StringIO
13 from unittest import TestCase
12 from unittest import TestCase
14
13
15 import nose.tools as nt
14 import nose.tools as nt
16
15
17 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils.py3compat import PY3
18
19 if PY3:
20 from io import StringIO
21 else:
22 from StringIO import StringIO
18
23
19 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
20 # Globals
25 # Globals
21 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
22 ip = get_ipython()
27 ip = get_ipython()
23
28
24 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
25 # Test functions begin
30 # Test functions begin
26 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
27
32
28 def check_cpaste(code, should_fail=False):
33 def check_cpaste(code, should_fail=False):
29 """Execute code via 'cpaste' and ensure it was executed, unless
34 """Execute code via 'cpaste' and ensure it was executed, unless
30 should_fail is set.
35 should_fail is set.
31 """
36 """
32 ip.user_ns['code_ran'] = False
37 ip.user_ns['code_ran'] = False
33
38
34 src = StringIO()
39 src = StringIO()
35 if not hasattr(src, 'encoding'):
40 if not hasattr(src, 'encoding'):
36 # IPython expects stdin to have an encoding attribute
41 # IPython expects stdin to have an encoding attribute
37 src.encoding = None
42 src.encoding = None
38 src.write(code)
43 src.write(code)
39 src.write('\n--\n')
44 src.write('\n--\n')
40 src.seek(0)
45 src.seek(0)
41
46
42 stdin_save = sys.stdin
47 stdin_save = sys.stdin
43 sys.stdin = src
48 sys.stdin = src
44
49
45 try:
50 try:
46 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
51 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
47 with context("Traceback (most recent call last)"):
52 with context("Traceback (most recent call last)"):
48 ip.magic('cpaste')
53 ip.magic('cpaste')
49
54
50 if not should_fail:
55 if not should_fail:
51 assert ip.user_ns['code_ran'], "%r failed" % code
56 assert ip.user_ns['code_ran'], "%r failed" % code
52 finally:
57 finally:
53 sys.stdin = stdin_save
58 sys.stdin = stdin_save
54
59
55 PY31 = sys.version_info[:2] == (3,1)
60 PY31 = sys.version_info[:2] == (3,1)
56
61
57 def test_cpaste():
62 def test_cpaste():
58 """Test cpaste magic"""
63 """Test cpaste magic"""
59
64
60 def runf():
65 def runf():
61 """Marker function: sets a flag when executed.
66 """Marker function: sets a flag when executed.
62 """
67 """
63 ip.user_ns['code_ran'] = True
68 ip.user_ns['code_ran'] = True
64 return 'runf' # return string so '+ runf()' doesn't result in success
69 return 'runf' # return string so '+ runf()' doesn't result in success
65
70
66 tests = {'pass': ["runf()",
71 tests = {'pass': ["runf()",
67 "In [1]: runf()",
72 "In [1]: runf()",
68 "In [1]: if 1:\n ...: runf()",
73 "In [1]: if 1:\n ...: runf()",
69 "> > > runf()",
74 "> > > runf()",
70 ">>> runf()",
75 ">>> runf()",
71 " >>> runf()",
76 " >>> runf()",
72 ],
77 ],
73
78
74 'fail': ["1 + runf()",
79 'fail': ["1 + runf()",
75 ]}
80 ]}
76
81
77 # I don't know why this is failing specifically on Python 3.1. I've
82 # I don't know why this is failing specifically on Python 3.1. I've
78 # checked it manually interactively, but we don't care enough about 3.1
83 # checked it manually interactively, but we don't care enough about 3.1
79 # to spend time fiddling with the tests, so we just skip it.
84 # to spend time fiddling with the tests, so we just skip it.
80 if not PY31:
85 if not PY31:
81 tests['fail'].append("++ runf()")
86 tests['fail'].append("++ runf()")
82
87
83 ip.user_ns['runf'] = runf
88 ip.user_ns['runf'] = runf
84
89
85 for code in tests['pass']:
90 for code in tests['pass']:
86 check_cpaste(code)
91 check_cpaste(code)
87
92
88 for code in tests['fail']:
93 for code in tests['fail']:
89 check_cpaste(code, should_fail=True)
94 check_cpaste(code, should_fail=True)
90
95
91
96
92 class PasteTestCase(TestCase):
97 class PasteTestCase(TestCase):
93 """Multiple tests for clipboard pasting"""
98 """Multiple tests for clipboard pasting"""
94
99
95 def paste(self, txt, flags='-q'):
100 def paste(self, txt, flags='-q'):
96 """Paste input text, by default in quiet mode"""
101 """Paste input text, by default in quiet mode"""
97 ip.hooks.clipboard_get = lambda : txt
102 ip.hooks.clipboard_get = lambda : txt
98 ip.magic('paste '+flags)
103 ip.magic('paste '+flags)
99
104
100 def setUp(self):
105 def setUp(self):
101 # Inject fake clipboard hook but save original so we can restore it later
106 # Inject fake clipboard hook but save original so we can restore it later
102 self.original_clip = ip.hooks.clipboard_get
107 self.original_clip = ip.hooks.clipboard_get
103
108
104 def tearDown(self):
109 def tearDown(self):
105 # Restore original hook
110 # Restore original hook
106 ip.hooks.clipboard_get = self.original_clip
111 ip.hooks.clipboard_get = self.original_clip
107
112
108 def test_paste(self):
113 def test_paste(self):
109 ip.user_ns.pop('x', None)
114 ip.user_ns.pop('x', None)
110 self.paste('x = 1')
115 self.paste('x = 1')
111 nt.assert_equal(ip.user_ns['x'], 1)
116 nt.assert_equal(ip.user_ns['x'], 1)
112 ip.user_ns.pop('x')
117 ip.user_ns.pop('x')
113
118
114 def test_paste_pyprompt(self):
119 def test_paste_pyprompt(self):
115 ip.user_ns.pop('x', None)
120 ip.user_ns.pop('x', None)
116 self.paste('>>> x=2')
121 self.paste('>>> x=2')
117 nt.assert_equal(ip.user_ns['x'], 2)
122 nt.assert_equal(ip.user_ns['x'], 2)
118 ip.user_ns.pop('x')
123 ip.user_ns.pop('x')
119
124
120 def test_paste_py_multi(self):
125 def test_paste_py_multi(self):
121 self.paste("""
126 self.paste("""
122 >>> x = [1,2,3]
127 >>> x = [1,2,3]
123 >>> y = []
128 >>> y = []
124 >>> for i in x:
129 >>> for i in x:
125 ... y.append(i**2)
130 ... y.append(i**2)
126 ...
131 ...
127 """)
132 """)
128 nt.assert_equal(ip.user_ns['x'], [1,2,3])
133 nt.assert_equal(ip.user_ns['x'], [1,2,3])
129 nt.assert_equal(ip.user_ns['y'], [1,4,9])
134 nt.assert_equal(ip.user_ns['y'], [1,4,9])
130
135
131 def test_paste_py_multi_r(self):
136 def test_paste_py_multi_r(self):
132 "Now, test that self.paste -r works"
137 "Now, test that self.paste -r works"
133 self.test_paste_py_multi()
138 self.test_paste_py_multi()
134 nt.assert_equal(ip.user_ns.pop('x'), [1,2,3])
139 nt.assert_equal(ip.user_ns.pop('x'), [1,2,3])
135 nt.assert_equal(ip.user_ns.pop('y'), [1,4,9])
140 nt.assert_equal(ip.user_ns.pop('y'), [1,4,9])
136 nt.assert_false('x' in ip.user_ns)
141 nt.assert_false('x' in ip.user_ns)
137 ip.magic('paste -r')
142 ip.magic('paste -r')
138 nt.assert_equal(ip.user_ns['x'], [1,2,3])
143 nt.assert_equal(ip.user_ns['x'], [1,2,3])
139 nt.assert_equal(ip.user_ns['y'], [1,4,9])
144 nt.assert_equal(ip.user_ns['y'], [1,4,9])
140
145
141 def test_paste_email(self):
146 def test_paste_email(self):
142 "Test pasting of email-quoted contents"
147 "Test pasting of email-quoted contents"
143 self.paste("""\
148 self.paste("""\
144 >> def foo(x):
149 >> def foo(x):
145 >> return x + 1
150 >> return x + 1
146 >> xx = foo(1.1)""")
151 >> xx = foo(1.1)""")
147 nt.assert_equal(ip.user_ns['xx'], 2.1)
152 nt.assert_equal(ip.user_ns['xx'], 2.1)
148
153
149 def test_paste_email2(self):
154 def test_paste_email2(self):
150 "Email again; some programs add a space also at each quoting level"
155 "Email again; some programs add a space also at each quoting level"
151 self.paste("""\
156 self.paste("""\
152 > > def foo(x):
157 > > def foo(x):
153 > > return x + 1
158 > > return x + 1
154 > > yy = foo(2.1) """)
159 > > yy = foo(2.1) """)
155 nt.assert_equal(ip.user_ns['yy'], 3.1)
160 nt.assert_equal(ip.user_ns['yy'], 3.1)
156
161
157 def test_paste_email_py(self):
162 def test_paste_email_py(self):
158 "Email quoting of interactive input"
163 "Email quoting of interactive input"
159 self.paste("""\
164 self.paste("""\
160 >> >>> def f(x):
165 >> >>> def f(x):
161 >> ... return x+1
166 >> ... return x+1
162 >> ...
167 >> ...
163 >> >>> zz = f(2.5) """)
168 >> >>> zz = f(2.5) """)
164 nt.assert_equal(ip.user_ns['zz'], 3.5)
169 nt.assert_equal(ip.user_ns['zz'], 3.5)
165
170
166 def test_paste_echo(self):
171 def test_paste_echo(self):
167 "Also test self.paste echoing, by temporarily faking the writer"
172 "Also test self.paste echoing, by temporarily faking the writer"
168 w = StringIO()
173 w = StringIO()
169 writer = ip.write
174 writer = ip.write
170 ip.write = w.write
175 ip.write = w.write
171 code = """
176 code = """
172 a = 100
177 a = 100
173 b = 200"""
178 b = 200"""
174 try:
179 try:
175 self.paste(code,'')
180 self.paste(code,'')
176 out = w.getvalue()
181 out = w.getvalue()
177 finally:
182 finally:
178 ip.write = writer
183 ip.write = writer
179 nt.assert_equal(ip.user_ns['a'], 100)
184 nt.assert_equal(ip.user_ns['a'], 100)
180 nt.assert_equal(ip.user_ns['b'], 200)
185 nt.assert_equal(ip.user_ns['b'], 200)
181 nt.assert_equal(out, code+"\n## -- End pasted text --\n")
186 nt.assert_equal(out, code+"\n## -- End pasted text --\n")
182
187
183 def test_paste_leading_commas(self):
188 def test_paste_leading_commas(self):
184 "Test multiline strings with leading commas"
189 "Test multiline strings with leading commas"
185 tm = ip.magics_manager.registry['TerminalMagics']
190 tm = ip.magics_manager.registry['TerminalMagics']
186 s = '''\
191 s = '''\
187 a = """
192 a = """
188 ,1,2,3
193 ,1,2,3
189 """'''
194 """'''
190 ip.user_ns.pop('foo', None)
195 ip.user_ns.pop('foo', None)
191 tm.store_or_execute(s, 'foo')
196 tm.store_or_execute(s, 'foo')
192 nt.assert_in('foo', ip.user_ns)
197 nt.assert_in('foo', ip.user_ns)
193
198
194
199
195 def test_paste_trailing_question(self):
200 def test_paste_trailing_question(self):
196 "Test pasting sources with trailing question marks"
201 "Test pasting sources with trailing question marks"
197 tm = ip.magics_manager.registry['TerminalMagics']
202 tm = ip.magics_manager.registry['TerminalMagics']
198 s = '''\
203 s = '''\
199 def funcfoo():
204 def funcfoo():
200 if True: #am i true?
205 if True: #am i true?
201 return 'fooresult'
206 return 'fooresult'
202 '''
207 '''
203 ip.user_ns.pop('funcfoo', None)
208 ip.user_ns.pop('funcfoo', None)
204 self.paste(s)
209 self.paste(s)
205 nt.assert_equal(ip.user_ns['funcfoo'](), 'fooresult')
210 nt.assert_equal(ip.user_ns['funcfoo'](), 'fooresult')
General Comments 0
You need to be logged in to leave comments. Login now