-
Notifications
You must be signed in to change notification settings - Fork 0
/
whichmodule.py
executable file
·265 lines (208 loc) · 7.61 KB
/
whichmodule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python
# encoding: utf-8
""" Look up and return file location of a module. """
from __future__ import unicode_literals, print_function, absolute_import
import argparse
import fnmatch
import imp
import importlib
import inspect
import os
import re
import sys
__version__ = '1.3.1'
def iter_dict(d):
# PY2/3 compat
try:
return d.iteritems()
except AttributeError:
return d.items()
def get_suffix_data(filename):
""" Fetches suffix data from the `filename` suffix. """
for suffix in imp.get_suffixes():
if filename[-len(suffix[0]):] == suffix[0]:
return suffix
return None
def get_paths():
""" Gets a list of module paths, in search order. """
return filter(os.path.isdir,
map(os.path.normcase,
map(os.path.abspath, sys.path[:])))
def get_modules(path):
""" Gets a list of modules at a given path.
:param str path:
A directory to look up modules in.
:returns dict:
Returns a dictionary with modules in the given 'path'. The dictionary
will contain items (<module>, <filename>), i.e. where the keys are
module names from the path, and the values are the absolute path to the
module file.
"""
modules = {}
module_name_re = re.compile(r'^[a-z_]\w*$', re.I)
for basename in os.listdir(path):
filename = os.path.join(path, basename)
if os.path.isfile(filename):
module, ext = os.path.splitext(os.path.basename(filename))
suffix_data = get_suffix_data(filename)
if not suffix_data:
continue
if module_name_re.match(module):
# if suffix_data[2] == imp.C_EXTENSION:
# # check that this extension can be imported
# try:
# __import__(name)
# except ImportError:
# continue
modules[module] = filename
elif (os.path.isdir(filename) and
os.path.isfile(os.path.join(filename, "__init__.py"))):
package = os.path.basename(filename)
for module, fn in get_modules(filename).items():
if module == '__init__':
module = package
else:
module = package + '.' + module
modules[module] = fn
return modules
def expand_module_name(module_name):
""" Returns the module name, and the packages it comes from.
>>> expand_module_names('foo')
['foo']
>>> expand_module_names('foo.bar')
['foo', 'foo.bar']
"""
parts = module_name.split('.')
return ['.'.join(parts[:i]) for i in range(1, len(parts) + 1)]
def join_modules(*module_dicts):
""" Joins multiple module dicts that *may* contain conflicting names.
The argument order dictates which modules will be filtered out. If the
first dictionary contains a package or module 'foo', then no module 'foo'
or module from a package 'foo' from later dictionaries will be included in
the result.
>>> _join_modules({'foo': '...', }, {'foo.bar': '...', 'baz': '...'})
{'foo': '...', 'baz': '...'}
:param list module_dicts:
A list of dictionaries, each dictionary is a mapping of
module_name -> filename.
:return dict:
A dictonary that maps module_name -> filename, where all conflicting
modules have been removed.
"""
# Join modules from multiple paths
result = {}
# Modules from other module sets.
commited = set()
for dict_ in module_dicts:
# Modules from this set
dict_names = set()
for module in dict_.keys():
names = expand_module_name(module)
# If the module or the package it comes from has been seen
# previously, it won't be importable
if any(n in commited for n in names):
continue
dict_names.update(names)
result[module] = dict_[module]
commited.update(dict_names)
return result
def get_module_file(module_name):
""" Get the path to the source file for a given module. """
# We could use other parts of the import system here to avoid actually
# importing the file, but that's a bit messy to do for both PY2 and PY3.
#
# This solution is simple and gives us reasonally good support for python
# version.
module = importlib.import_module(module_name)
return inspect.getsourcefile(module)
def _list_modules():
module_dicts = []
# Built-ins
module_dicts.append(
{m: None for m in sys.builtin_module_names})
# Paths
for path in get_paths():
module_dicts.append(get_modules(path))
# Join
return join_modules(*module_dicts)
def _print_modules(modules, max_modules=0, max_depth=-1):
# If depth, filter by number of parent packages
if max_depth >= 0:
modules = {k: v for k, v in iter_dict(modules)
if len(k.split('.')) <= max_depth + 1}
# If no max_modules, include all modules
if max_modules <= 0:
max_modules = len(modules)
print("Modules: {:d}".format(len(modules)))
for m in sorted(modules.keys())[:max_modules]:
print(' {!s} ({!s})'.format(m, modules[m]))
if len(modules) > max_modules:
print('... and {:d} more'.format(len(modules) - max_modules))
class ListModulesAction(argparse.Action):
""" An action that lists available python modules and exits.
Usage:
parser.add_argument('-o', '--option', help="Help")
"""
default_help = """
List modules and exit. Only modules matching a glob-like pattern
'%(metavar)s' will be listed. The default pattern '%(const)s' will list
all modules."""
default_metavar = 'GLOB'
def __init__(self, option_strings, dest,
type=None,
help=default_help,
metavar=default_metavar):
super(ListModulesAction, self).__init__(
option_strings=option_strings,
dest=argparse.SUPPRESS,
nargs='?',
const='*',
default=argparse.SUPPRESS,
type=type,
help=help,
metavar=metavar)
def __call__(self, parser, ns, opt_value, option_string=None):
regex = re.compile(fnmatch.translate(opt_value))
modules = {k: v
for k, v in iter_dict(_list_modules())
if regex.match(k)}
print('Modules matching:', regex.pattern)
depth = 0
if opt_value != '*':
depth = -1
_print_modules(modules, max_depth=depth)
parser.exit()
def edit(filename):
""" Launch editor with file. """
import subprocess
editor = os.environ.get('EDITOR')
if not editor:
raise Exception(
"Could not edit %r: No EDITOR environment variable set" %
filename)
try:
subprocess.call([editor, filename])
except OSError as e:
raise Exception(
"Could not edit %r (editor: %r): %s" %
(filename, editor, e))
def main(inargs=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'module',
help="Name of a module to look up")
parser.add_argument(
'-e', '--edit',
action='store_true',
default=False,
help="Open the found module with $EDITOR")
parser.add_argument(
'-l', '--list',
action=ListModulesAction)
args = parser.parse_args(inargs)
filename = get_module_file(args.module)
print(filename)
if args.edit:
edit(filename)
if __name__ == '__main__':
main()