我怎么会打印python文档字符串?

baa*_*ezx 6 python docstring

我有一个python文件,其原始字符串作为docstrings.

def a():
    '\n\tthis\n\tis\n\tthe docstring.\n\t'
    print 'hello world'
Run Code Online (Sandbox Code Playgroud)

我如何重写docstring看起来像

def a():
    """
    this
    is
    the docstring.
    """
    print 'hello world'
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 2

inspect.getsoucelines这是使用和 一些正则表达式的示例:

import inspect
import re

def update_doc(func, indent='    '):
    sourcelines = inspect.getsourcelines(func)[0]
    doc = func.__doc__
    if doc is not None:
        ind = [line.decode('string_escape').strip()[1:-1] 
                                                 for line in sourcelines].index(doc)
        sourcelines[ind] = '{}"""{}"""\n'.format(indent, 
                                           re.sub(r'\n([ \t]+)', r'\n'+indent, doc))
    return ''.join(sourcelines)
Run Code Online (Sandbox Code Playgroud)

演示:

def a():
    '\n\tthis\n\tis\n\tthe docstring.\n\t'
    print 'hello world'
print update_doc(a)

def b():
    '\n    This is\n    not so lengthy\n    docstring\n    '
    print 'hmm...'
print update_doc(b)
Run Code Online (Sandbox Code Playgroud)

输出:

def a():
    """
    this
    is
    the docstring.
    """
    print 'hello world'

def b():
    """
    This is
    not so lengthy
    docstring
    """
    print 'hmm...'
Run Code Online (Sandbox Code Playgroud)

PS:我还没有彻底测试它,但这应该可以帮助你开始。