也许我没有理解这个问题,但你不能这样做(python 2.7.1)吗?
测试文件:
"""
DOC STRING!!
"""
def hello():
'doc string'
print 'hello'
hello()
Run Code Online (Sandbox Code Playgroud)
互动环节:
>>> M = ast.parse(''.join(open('test.py')))
>>> ast.get_docstring(M)
'DOC STRING!!'
Run Code Online (Sandbox Code Playgroud)
您还可以遍历 ast,寻找文档字符串所在的插槽。
>>> 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'
Run Code Online (Sandbox Code Playgroud)