我正在尝试对来自 Python 源代码的函数调用进行注释。
我阅读了字符串中的源代码,然后尝试将一些正则表达式应用于评论方法调用。
这是一个简单的例子:
s = open(path, 'r').read()
# comment method calls
result = re.sub('(^[.\w]+\(.*\))', r'#\1', s, flags=re.MULTILINE)
如您所见,我在源代码的第一个缩进级别注释函数(__name__ == '__main__'、方法和类之外的代码)
但是,我怎样才能使这个正则表达式适用于多行调用?
例如,如果我将以下代码转换为字符串:
Builder.load_string('''
type: 'example'
callback: my_callback()
''')
如何评论此调用的每一行?
请您参考如下方法:
这将为您提供您需要评论的行号:
mod = "test1"
mod = importlib.import_module(mod)
p = ast.parse(inspect.getsource(mod))
for n in p.body:
if isinstance(n, ast.Expr):
for node in ast.walk(n):
if isinstance(node, ast.Call):
print(node.lineno)
对于这样的文件:
import math
class Foo:
def __init__(self):
self.foo = 4
def bar(self):
print("hello world")
def foo(self):
return self.bar()
def bar():
return 123
f = Foo()
f.bar()
bar()
它将输出16和18这两个调用。
这只是忽略这些行并编写新源代码或对更新内容做任何你想做的事情:
import inspect
import importlib
import ast
def get_call_lines(mod):
mod = importlib.import_module(mod)
p = ast.parse(inspect.getsource(mod))
for n in p.body:
if isinstance(n, ast.Expr):
for node in ast.walk(n):
if isinstance(node, ast.Call):
yield(node.lineno)
from StringIO import StringIO
new = StringIO()
with open("test1.py") as f:
st = set(get_call_lines("test1"))
for ind, line in enumerate(f, 1):
if ind not in st:
new.write(line)
new.seek(0)
print(new.read())
新的将包含:
import math
class Foo:
def __init__(self):
self.foo = 4
def bar(self):
print("hello world")
def foo(self):
return self.bar()
def bar():
return 123
f = Foo()
您可以在运行时使用 ast.NodeTransformer 更改代码,但删除节点并不是一项简单的任务,您想要的最简单方法是简单地忽略 Call 中的行正文
