##// END OF EJS Templates
use importlib.machinery when available...
MinRK -
Show More
@@ -1,338 +1,345 b''
1 1 """Implementations for various useful completers.
2 2
3 3 These are all loaded by default by IPython.
4 4 """
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2010-2011 The IPython Development Team.
7 7 #
8 8 # Distributed under the terms of the BSD License.
9 9 #
10 10 # The full license is in the file COPYING.txt, distributed with this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Stdlib imports
19 19 import glob
20 import imp
21 20 import inspect
22 21 import os
23 22 import re
24 23 import sys
25 24
25 try:
26 # Python 3
27 from importlib.machinery import all_suffixes
28 _suffixes = all_suffixes()
29 except ImportError:
30 from imp import get_suffixes
31 _suffixes = [ s[0] for s in get_suffixes() ]
32
26 33 # Third-party imports
27 34 from time import time
28 35 from zipimport import zipimporter
29 36
30 37 # Our own imports
31 38 from IPython.core.completer import expand_user, compress_user
32 39 from IPython.core.error import TryNext
33 40 from IPython.utils._process_common import arg_split
34 41 from IPython.utils.py3compat import string_types
35 42
36 43 # FIXME: this should be pulled in with the right call via the component system
37 44 from IPython import get_ipython
38 45
39 46 #-----------------------------------------------------------------------------
40 47 # Globals and constants
41 48 #-----------------------------------------------------------------------------
42 49
43 50 # Time in seconds after which the rootmodules will be stored permanently in the
44 51 # ipython ip.db database (kept in the user's .ipython dir).
45 52 TIMEOUT_STORAGE = 2
46 53
47 54 # Time in seconds after which we give up
48 55 TIMEOUT_GIVEUP = 20
49 56
50 57 # Regular expression for the python import statement
51 58 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
52 59 r'(?P<package>[/\\]__init__)?'
53 60 r'(?P<suffix>%s)$' %
54 r'|'.join(re.escape(s[0]) for s in imp.get_suffixes()))
61 r'|'.join(re.escape(s) for s in _suffixes))
55 62
56 63 # RE for the ipython %run command (python + ipython scripts)
57 64 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
58 65
59 66 #-----------------------------------------------------------------------------
60 67 # Local utilities
61 68 #-----------------------------------------------------------------------------
62 69
63 70 def module_list(path):
64 71 """
65 72 Return the list containing the names of the modules available in the given
66 73 folder.
67 74 """
68 75 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
69 76 if path == '':
70 77 path = '.'
71 78
72 79 # A few local constants to be used in loops below
73 80 pjoin = os.path.join
74 81
75 82 if os.path.isdir(path):
76 83 # Build a list of all files in the directory and all files
77 84 # in its subdirectories. For performance reasons, do not
78 85 # recurse more than one level into subdirectories.
79 86 files = []
80 87 for root, dirs, nondirs in os.walk(path):
81 88 subdir = root[len(path)+1:]
82 89 if subdir:
83 90 files.extend(pjoin(subdir, f) for f in nondirs)
84 91 dirs[:] = [] # Do not recurse into additional subdirectories.
85 92 else:
86 93 files.extend(nondirs)
87 94
88 95 else:
89 96 try:
90 97 files = list(zipimporter(path)._files.keys())
91 98 except:
92 99 files = []
93 100
94 101 # Build a list of modules which match the import_re regex.
95 102 modules = []
96 103 for f in files:
97 104 m = import_re.match(f)
98 105 if m:
99 106 modules.append(m.group('name'))
100 107 return list(set(modules))
101 108
102 109
103 110 def get_root_modules():
104 111 """
105 112 Returns a list containing the names of all the modules available in the
106 113 folders of the pythonpath.
107 114
108 115 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
109 116 """
110 117 ip = get_ipython()
111 118 rootmodules_cache = ip.db.get('rootmodules_cache', {})
112 119 rootmodules = list(sys.builtin_module_names)
113 120 start_time = time()
114 121 store = False
115 122 for path in sys.path:
116 123 try:
117 124 modules = rootmodules_cache[path]
118 125 except KeyError:
119 126 modules = module_list(path)
120 127 try:
121 128 modules.remove('__init__')
122 129 except ValueError:
123 130 pass
124 131 if path not in ('', '.'): # cwd modules should not be cached
125 132 rootmodules_cache[path] = modules
126 133 if time() - start_time > TIMEOUT_STORAGE and not store:
127 134 store = True
128 135 print("\nCaching the list of root modules, please wait!")
129 136 print("(This will only be done once - type '%rehashx' to "
130 137 "reset cache!)\n")
131 138 sys.stdout.flush()
132 139 if time() - start_time > TIMEOUT_GIVEUP:
133 140 print("This is taking too long, we give up.\n")
134 141 return []
135 142 rootmodules.extend(modules)
136 143 if store:
137 144 ip.db['rootmodules_cache'] = rootmodules_cache
138 145 rootmodules = list(set(rootmodules))
139 146 return rootmodules
140 147
141 148
142 149 def is_importable(module, attr, only_modules):
143 150 if only_modules:
144 151 return inspect.ismodule(getattr(module, attr))
145 152 else:
146 153 return not(attr[:2] == '__' and attr[-2:] == '__')
147 154
148 155
149 156 def try_import(mod, only_modules=False):
150 157 try:
151 158 m = __import__(mod)
152 159 except:
153 160 return []
154 161 mods = mod.split('.')
155 162 for module in mods[1:]:
156 163 m = getattr(m, module)
157 164
158 165 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
159 166
160 167 completions = []
161 168 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
162 169 completions.extend( [attr for attr in dir(m) if
163 170 is_importable(m, attr, only_modules)])
164 171
165 172 completions.extend(getattr(m, '__all__', []))
166 173 if m_is_init:
167 174 completions.extend(module_list(os.path.dirname(m.__file__)))
168 175 completions = set(completions)
169 176 if '__init__' in completions:
170 177 completions.remove('__init__')
171 178 return list(completions)
172 179
173 180
174 181 #-----------------------------------------------------------------------------
175 182 # Completion-related functions.
176 183 #-----------------------------------------------------------------------------
177 184
178 185 def quick_completer(cmd, completions):
179 186 """ Easily create a trivial completer for a command.
180 187
181 188 Takes either a list of completions, or all completions in string (that will
182 189 be split on whitespace).
183 190
184 191 Example::
185 192
186 193 [d:\ipython]|1> import ipy_completers
187 194 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
188 195 [d:\ipython]|3> foo b<TAB>
189 196 bar baz
190 197 [d:\ipython]|3> foo ba
191 198 """
192 199
193 200 if isinstance(completions, string_types):
194 201 completions = completions.split()
195 202
196 203 def do_complete(self, event):
197 204 return completions
198 205
199 206 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
200 207
201 208 def module_completion(line):
202 209 """
203 210 Returns a list containing the completion possibilities for an import line.
204 211
205 212 The line looks like this :
206 213 'import xml.d'
207 214 'from xml.dom import'
208 215 """
209 216
210 217 words = line.split(' ')
211 218 nwords = len(words)
212 219
213 220 # from whatever <tab> -> 'import '
214 221 if nwords == 3 and words[0] == 'from':
215 222 return ['import ']
216 223
217 224 # 'from xy<tab>' or 'import xy<tab>'
218 225 if nwords < 3 and (words[0] in ['import','from']) :
219 226 if nwords == 1:
220 227 return get_root_modules()
221 228 mod = words[1].split('.')
222 229 if len(mod) < 2:
223 230 return get_root_modules()
224 231 completion_list = try_import('.'.join(mod[:-1]), True)
225 232 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
226 233
227 234 # 'from xyz import abc<tab>'
228 235 if nwords >= 3 and words[0] == 'from':
229 236 mod = words[1]
230 237 return try_import(mod)
231 238
232 239 #-----------------------------------------------------------------------------
233 240 # Completers
234 241 #-----------------------------------------------------------------------------
235 242 # These all have the func(self, event) signature to be used as custom
236 243 # completers
237 244
238 245 def module_completer(self,event):
239 246 """Give completions after user has typed 'import ...' or 'from ...'"""
240 247
241 248 # This works in all versions of python. While 2.5 has
242 249 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
243 250 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
244 251 # of possibly problematic side effects.
245 252 # This search the folders in the sys.path for available modules.
246 253
247 254 return module_completion(event.line)
248 255
249 256 # FIXME: there's a lot of logic common to the run, cd and builtin file
250 257 # completers, that is currently reimplemented in each.
251 258
252 259 def magic_run_completer(self, event):
253 260 """Complete files that end in .py or .ipy or .ipynb for the %run command.
254 261 """
255 262 comps = arg_split(event.line, strict=False)
256 263 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
257 264
258 265 #print("\nev=", event) # dbg
259 266 #print("rp=", relpath) # dbg
260 267 #print('comps=', comps) # dbg
261 268
262 269 lglob = glob.glob
263 270 isdir = os.path.isdir
264 271 relpath, tilde_expand, tilde_val = expand_user(relpath)
265 272
266 273 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
267 274
268 275 # Find if the user has already typed the first filename, after which we
269 276 # should complete on all files, since after the first one other files may
270 277 # be arguments to the input script.
271 278
272 279 if any(magic_run_re.match(c) for c in comps):
273 280 pys = [f.replace('\\','/') for f in lglob('*')]
274 281 else:
275 282 pys = [f.replace('\\','/')
276 283 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
277 284 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
278 285 #print('run comp:', dirs+pys) # dbg
279 286 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
280 287
281 288
282 289 def cd_completer(self, event):
283 290 """Completer function for cd, which only returns directories."""
284 291 ip = get_ipython()
285 292 relpath = event.symbol
286 293
287 294 #print(event) # dbg
288 295 if event.line.endswith('-b') or ' -b ' in event.line:
289 296 # return only bookmark completions
290 297 bkms = self.db.get('bookmarks', None)
291 298 if bkms:
292 299 return bkms.keys()
293 300 else:
294 301 return []
295 302
296 303 if event.symbol == '-':
297 304 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
298 305 # jump in directory history by number
299 306 fmt = '-%0' + width_dh +'d [%s]'
300 307 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
301 308 if len(ents) > 1:
302 309 return ents
303 310 return []
304 311
305 312 if event.symbol.startswith('--'):
306 313 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
307 314
308 315 # Expand ~ in path and normalize directory separators.
309 316 relpath, tilde_expand, tilde_val = expand_user(relpath)
310 317 relpath = relpath.replace('\\','/')
311 318
312 319 found = []
313 320 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
314 321 if os.path.isdir(f)]:
315 322 if ' ' in d:
316 323 # we don't want to deal with any of that, complex code
317 324 # for this is elsewhere
318 325 raise TryNext
319 326
320 327 found.append(d)
321 328
322 329 if not found:
323 330 if os.path.isdir(relpath):
324 331 return [compress_user(relpath, tilde_expand, tilde_val)]
325 332
326 333 # if no completions so far, try bookmarks
327 334 bks = self.db.get('bookmarks',{})
328 335 bkmatches = [s for s in bks if s.startswith(event.symbol)]
329 336 if bkmatches:
330 337 return bkmatches
331 338
332 339 raise TryNext
333 340
334 341 return [compress_user(p, tilde_expand, tilde_val) for p in found]
335 342
336 343 def reset_completer(self, event):
337 344 "A completer for %reset magic"
338 345 return '-f -s in out array dhist'.split()
General Comments 0
You need to be logged in to leave comments. Login now