Skip to content

Commit 52d84dd

Browse files
committed
module index script
1 parent cfe88c0 commit 52d84dd

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

module_index.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
from collections import defaultdict, Counter
2+
import glob
3+
import os
4+
import re
5+
6+
from stdlib import is_std_lib
7+
8+
index = defaultdict(set)
9+
10+
import_regex = re.compile('^(?:from|import)\s(?P<module>\w+).*')
11+
12+
dirname = os.getcwd()
13+
14+
15+
def get_dirs():
16+
for path in glob.glob('{}/[0-9]*'.format(dirname)):
17+
yield path
18+
19+
20+
def get_files(path):
21+
for fi in os.listdir(path):
22+
if fi.endswith('.py'):
23+
yield os.path.join(path, fi)
24+
25+
26+
def get_lines(src):
27+
with open(scr) as f:
28+
for line in f:
29+
yield line
30+
31+
32+
if __name__ == '__main__':
33+
for path in get_dirs():
34+
day = os.path.basename(path)
35+
for scr in get_files(path):
36+
for line in get_lines(scr):
37+
m = import_regex.match(line)
38+
if m:
39+
mod = m.groupdict()['module']
40+
index[mod].add(day)
41+
42+
cnt = Counter()
43+
44+
for mod, scripts in sorted(index.items()):
45+
if mod == 'common' or \
46+
any(glob.glob(os.path.join(dirname, day, mod + '.py'))
47+
for day in scripts):
48+
source = 'own'
49+
else:
50+
source = 'stdlib' if is_std_lib(mod) else 'pypi'
51+
cnt[source] += 1
52+
appeared_in = ', '.join(sorted(scripts))
53+
print(f'{mod:<12} | {source:<6}{appeared_in}')
54+
55+
total = sum(cnt.values())
56+
print()
57+
for source, count in cnt.most_common():
58+
print(f'{source:<10}: {count:>3} ({count/total*100:.1f}%)')
59+
print('-' * 30)
60+
print(f'Total: {total}')

stdlib.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''http://stackoverflow.com/questions/22195382/how-to-check-if-a-module-library-package-is-part-of-the-python-standard-library'''
2+
from __future__ import unicode_literals, print_function
3+
import sys
4+
from contextlib import contextmanager
5+
from importlib import import_module
6+
7+
8+
@contextmanager
9+
def ignore_site_packages_paths():
10+
paths = sys.path
11+
# remove all third-party paths
12+
# so that only stdlib imports will succeed
13+
sys.path = list(filter(
14+
None,
15+
filter(lambda i: 'site-packages' not in i, sys.path)
16+
))
17+
yield
18+
sys.path = paths
19+
20+
21+
def is_std_lib(module):
22+
if module in sys.builtin_module_names:
23+
return True
24+
25+
with ignore_site_packages_paths():
26+
imported_module = sys.modules.pop(module, None)
27+
try:
28+
import_module(module)
29+
except ImportError:
30+
return False
31+
else:
32+
return True
33+
finally:
34+
if imported_module:
35+
sys.modules[module] = imported_module

0 commit comments

Comments
 (0)