【问题标题】:How to print module documentation in Python如何在 Python 中打印模块文档
【发布时间】:2012-10-24 17:56:08
【问题描述】:

我知道这个问题很简单,我知道它一定被问过很多次了,我在 SO 和 Google 上都进行了搜索,但我找不到答案,可能是因为我没有能力提出什么我寻找一个合适的句子。

我希望能够阅读我导入的文档。

例如,如果我通过“import x”导入 x,我想运行这个命令,并用 Python 或 ipython 打印它的文档。

这个命令函数是什么?

谢谢。

附言。我不是指 dir(),我指的是实际打印文档以供我查看和阅读此模块 x 具有哪些功能等的函数。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    可以使用函数模块的.__doc__属性:

    In [14]: import itertools
    
    In [15]: print itertools.__doc__
    Functional tools for creating and using iterators..........
    
    In [18]: print itertools.permutations.__doc__
    permutations(iterable[, r]) --> permutations object
    
    Return successive r-length permutations of elements in the iterable.
    
    permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
    

    help()__doc__ 在内置模块和我们自己的模块上都可以正常工作:

    文件:foo.py

    def myfunc():
        """
        this is some info on myfunc
    
        """
        foo=2
        bar=3
    
    
    In [4]: help(so27.myfunc)
    
    
    In [5]: import foo
    
    In [6]: print foo.myfunc.__doc__
    
         this is some info on func
    
    In [7]: help(foo.myfunc)
    
    
    Help on function myfunc in module foo:
    
    myfunc()
        this is some info on func
    

    【讨论】:

    • 阿什维尼,再次感谢。很好的解释。不过我有一个小问题。假设我在 ipython 客户端上运行帮助命令并打印文档,我该如何返回 ipython? ;-) 转义、退格、空格、回车.. 除了 ipython 终止之外,没有任何字符带我回去。
    【解决方案2】:

    pydoc foo.bar 来自命令行,help(foo.bar)help('foo.bar') 来自 Python。

    【讨论】:

    • 谢谢乔希!您的回答也很好地解决了我的问题,但为了将来供其他人参考,我选择另一个答案作为“the”答案,因为它包含更多像我这样的新手的信息。
    • @josh-lee +1 用于提及命令行选项。如果我想从模块的__main__ 函数中打印模块的文档怎么办?
    • 对此我感激不尽。我正在寻找一种简单的方法来转储模块帮助的文本。这正是我想要的。
    • 另外,如果文档太长在cmd中无法读取,我们可以使用pydoc foo.bar > foo.txt将文档输出到foo.txt
    【解决方案3】:

    您可以使用help() 函数来显示文档。或者你可以选择method.__doc__描述符。

    例如:help(input) 将提供有关 input() 方法的文档。

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 2021-12-25
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多