简体   繁体   English

如何从调用模块获取文档字符串?

[英]How do I get the docstring from a calling module?

Can I get the __doc__ string of the main script?我可以获得主脚本的__doc__字符串吗?

Here is the starting script, which would be run from command line: python a.py这是从命令行运行的启动脚本: python a.py

module a.py模块 a.py

import b
b.func()

module b.py模块 b.py

def func():
    ???.__doc__

How can I get the calling module, as an object?我怎样才能得到调用模块,作为一个对象?

I am not asking about how to get the file name as string.我不是在问如何将文件名作为字符串获取。 I know how to retrieve the file's name from stack trace.我知道如何从堆栈跟踪中检索文件名。 I don't want to retrieve the doc string by parsing manually.我不想通过手动解析来检索文档字符串。 Also, I don't think I can just import by m = __import__(a) because of circular import loop.另外,由于循环导入循环,我认为我不能仅通过m = __import__(a)导入。

a.py一个.py

"""
Foo bar
"""

import b
if __name__ == '__main__':
    b.show_your_docs()

b.py b.py

def show_your_docs():
    name = caller_name(1)
    print(__import__(name).__doc__)

Where caller_name is code from this gist其中 caller_name 是来自这个 要点的代码

The weakness of this approach though is it is getting a string representation of the module name and reimporting it, instead of getting a reference to the module (type).这种方法的弱点是它获取模块名称的字符串表示并重新导入它,而不是获取对模块(类型)的引用。

This is the full solution from @MatthewMartin 's accepted answer:这是@MatthewMartin 接受的答案的完整解决方案:

def show_your_docs():
    name = caller_name(1)
    print(__import__(name).__doc__)

def caller_docstring(level=1):
    name = caller_name(level)
    return __import__(name).__doc__

    def caller_name(skip=2):
        def stack_(frame):
            framelist = []
            while frame:
                framelist.append(frame)
                frame = frame.f_back
            return framelist

        stack = stack_(sys._getframe(1))
        start = 0 + skip
        if len(stack) < start + 1:
            return ''
        parentframe = stack[start]

        name = []
        module = inspect.getmodule(parentframe)
        if module:
            name.append(module.__name__)
        if 'self' in parentframe.f_locals:
            name.append(parentframe.f_locals['self'].__class__.__name__)
        codename = parentframe.f_code.co_name
        if codename != '<module>':  # top level usually
            name.append(codename)  # function or a method
        del parentframe
        return ".".join(name)
text = caller_docstring(2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM