Skip to content

Instantly share code, notes, and snippets.

@akihironitta
Last active September 2, 2020 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akihironitta/4223c1b32404b36c1b349d70c4c93b4d to your computer and use it in GitHub Desktop.
Save akihironitta/4223c1b32404b36c1b349d70c4c93b4d to your computer and use it in GitHub Desktop.
This Python script prints line numbers of raise in except clause in Python language.
# usage:
#
# To find raises, simply run:
# $ python search_raise_in_except.py target.py
#
# In case you want to find raises in multiple files in current directory, run:
# $ for i in $(find . -type f -name "*.py"); do; python search_raise_in_except.py $i; done`
import _ast
import ast
import sys
def walk(node, in_except=False, filename=""):
if isinstance(node, _ast.ExceptHandler):
for child in ast.iter_child_nodes(node):
walk(child, True, filename)
elif isinstance(node, _ast.Raise) and in_except:
print(f"{filename}#L{node.lineno}")
# No more digging if `raise` is found in `except` clause,
# so don't call walk(child, in_except, filename) here.
else:
for child in ast.iter_child_nodes(node):
walk(child, in_except, filename)
def main():
filename = sys.argv[1]
with open(filename, "r") as f:
code = f.read()
root_node = ast.parse(code, filename)
walk(root_node, filename=filename)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment