解析Python模块文档字符串
1 个回答
5
也许我理解错了问题,但你难道不能这样做吗(python 2.7.1)?
测试文件:
"""
DOC STRING!!
"""
def hello():
'doc string'
print 'hello'
hello()
交互式会话:
>>> M = ast.parse(''.join(open('test.py')))
>>> ast.get_docstring(M)
'DOC STRING!!'
你还可以遍历抽象语法树,寻找文档字符串应该在的位置。
>>> M._fields
('body',)
>>> M.body
[<_ast.Expr object at 0x10e5ac710>, <_ast.FunctionDef object at 0x10e5ac790>, <_ast.Expr object at 0x10e5ac910>]
>>> # doc would be in the first slot
>>> M.body[0]._fields
('value',)
>>> M.body[0].value
<_ast.Str object at 0x10e5ac750>
>>> # it contains a string object, so maybe it's the doc string
>>> M.body[0].value._fields
('s',)
>>> M.body[0].value.s
'\nDOC STRING!!\n'