Created
April 7, 2015 11:41
-
-
Save SpotlightKid/ad0f739726ef65f3d6c9 to your computer and use it in GitHub Desktop.
List names of all imports in all Python files given on command line.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""List names of all imports in all Python files given on command line.""" | |
import sys | |
import ast | |
NODE_TYPES = (ast.Import, ast.ImportFrom) | |
def get_imports(source): | |
tree = ast.parse(source) | |
for node in ast.walk(tree): | |
if isinstance(node, NODE_TYPES): | |
lineno = getattr(node, 'lineno', None) | |
if isinstance(node, ast.Import): | |
mods = [a.name for a in node.names] | |
else: | |
mods = [node.module] | |
yield (lineno, node, mods) | |
if __name__ == '__main__': | |
for fn in sys.argv[1:]: | |
with open(fn) as fp: | |
try: | |
for lineno, node, mods in get_imports(fp.read()): | |
print("{}:{}:{}".format(fn, lineno, ", ".join(mods))) | |
except: | |
print("Could not parse '{}'.".format(fn)) | |
import traceback | |
traceback.print_exc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment