【Python】ソースコードを解析して関数名だけ抽出する
作成したソースコード内に存在する関数名を抽出する。 astモジュールを使用。
下記の参考ページのコードから一部変更。
parsing - How to extract functions used in a python code file? - Stack Overflow
import ast class CallCollector(ast.NodeVisitor): def __init__(self): self.calls = [] self.current = None def visit_Call(self, node): # new call, trace the function expression self.current = '' self.visit(node.func) self.calls.append(self.current) def generic_visit(self, node): if self.current is not None: print("warning: {} node in function expression not supported".format( node.__class__.__name__)) super(CallCollector, self).generic_visit(node) # record the func expression def visit_Name(self, node): if self.current is None: return self.current += node.id def visit_Attribute(self, node): if self.current is None: self.generic_visit(node) self.visit(node.value) self.current += '.' + node.attr #ファイルを開く with open('./mysoure.py', encoding='utf-8') as f: tree = ast.parse(f.read()) cc = CallCollector() cc.visit(tree) #リスト形式で関数名を出力 print(cc.calls)
astモジュールはデザインパターンのvisitorパターンを使っていることに注意すれば対して難しくない。