该程序将帮助您解决问题的第一部分,即查找所有以以下开头的函数test_
。您也可以扩展它以查找您选择的变量定义,但这有点复杂。
基本思想是使用ast
包来解析你的Python源代码,并扫描结果中的函数定义。因此,您不会检测到误报,例如字符串或注释内的函数定义。例子:
# define strings for function test_foobar().
foobar="def test_foobar(): pass"
此输入包含两个错误匹配,如果没有,将使用正则表达式检测到very精心制作。使用ast
,这比您想象的要简单得多。工作示例:
#!/usr/bin/env python
import ast
import sys
def test_foobar():
pass
class FunctionNameFinder(ast.NodeVisitor):
def visit_FunctionDef(self, node):
if node.name.startswith("test_"):
print node.name, "on line", node.lineno
with open(sys.argv[1], 'rU') as f:
FunctionNameFinder().visit(ast.parse("".join(f.readlines())))
该程序可以自行运行以检测第 6 行的虚拟函数!
EDIT:以下扩展将检测一些变量分配,但不是全部。只是为了指明方向。
def visit_FunctionDef(self, node):
if node.name.startswith("test_"):
print node.name, "on line", node.lineno
self.generic_visit(node)
def visit_Subscript(self, node):
if isinstance(node.value, ast.Name) and \
isinstance(node.slice, ast.Index):
if isinstance(node.slice.value, ast.Str):
print '%s["%s"] on line %s' % (
str(node.value.id),
str(node.slice.value.s),
node.lineno)
elif isinstance(node.slice.value, ast.Num):
print '%s[%s] on line %s' % (
str(node.value.id),
str(node.slice.value.n),
node.lineno)
HTH.