Last active
September 2, 2020 06:46
-
-
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.
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
# 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