Skip to content

Instantly share code, notes, and snippets.

@htv2012
Last active August 29, 2015 14:23
Show Gist options
  • Save htv2012/168b436da4e103982a0e to your computer and use it in GitHub Desktop.
Save htv2012/168b436da4e103982a0e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script takes in a single parameter representing a directory
and traverse that directory to list the exceptions that are ignored.
"""
from __future__ import print_function
import ast
import os
import sys
def find_ignored_exceptions(filename):
# Ironically, we want to ignore code that contains errors
try:
with open(filename) as f:
code = f.read()
tree = ast.parse(code)
except (SyntaxError, IndentationError):
return
for node in ast.walk(tree):
if not isinstance(node, ast.ExceptHandler):
continue
nodes = list(ast.walk(node))
if isinstance(nodes[1], ast.Pass):
# "except:"
yield 'Exception'
elif (isinstance(nodes[1], ast.Name)
and isinstance(nodes[2], ast.Pass)):
# "except ErrorName:"
yield nodes[1].id
elif isinstance(nodes[1], ast.Tuple) and isinstance(nodes[2], ast.Pass):
# "except (A, B, C):"
for node in ast.walk(nodes[1]):
if isinstance(node, ast.Name):
yield node.id
elif (isinstance(nodes[1], ast.Name)
and isinstance(nodes[2], ast.Name)
and isinstance(nodes[3], ast.Pass)):
# "except ValueError as e"
yield nodes[1].id
if __name__ == '__main__':
sys.argv.append('.')
root = sys.argv[1]
print('File Name,Exception Name')
for dirpath, dirnames, filenames in os.walk(root):
for filename in filenames:
if not filename.endswith('.py'):
continue
full_path = os.path.abspath(os.path.join(dirpath, filename))
for exception_name in find_ignored_exceptions(full_path):
# print([filename, exception_name])
print('{},{}'.format(filename, exception_name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment