如何为一个包含函数的文件进行文档化?

10

我有一个Python文件(lib.py),里面有一些没有类的函数。每个函数都具有以下风格:

def fnc1(a,b,c):
    '''
    This fonction does something.

    :param a: lalala
    :type a: str
    :param b: hahaha
    :type b: int
    :param c: hohoho
    :type c: int

    :rtype: int

    '''

    print a
    d = b + c

    return d
我只想用Sphinx文档每个函数(输入和输出)。 在执行sphinx-quickstart之后,我使用我的lib.py在conf.py中定义了路径。 但是生成的HTML文件(欢迎页)是空的。 如果我在index.rst中自己编写:
.. function:: func1(a,b,c)
    This fonction does something.

    :param a: lalala
    :type a: str
    :param b: hahaha
    :type b: int
    :param c: hohoho
    :type c: int
    :rtype: int

可以,它会在HTML文件中显示输入和输出。 但如何自动完成呢?

通常来说,我认为需要在执行 sphinx-apidoc -o 后在 lib.rst 中进行操作, 但是在 lib.rst 中只有:

lib module
==================

.. automodule:: lib
    :members:
    :undoc-members:
    :show-inheritance:

有人能逐步解释一下我必须做什么吗?

1个回答

17

首先,当你运行 sphinx-quickstart 时,请确保选择 autodoc

autodoc: automatically insert docstrings from modules (y/N) [n]: y

然后,在生成的index.rst文件中,我通常会添加modules来自动包含所有模块(注意缩进)。

.. toctree::
   :maxdepth: 4

   modules

进行此操作后,sphinx-apidoc -o 为我生成了文档。

我撰写了一份使用Sphinx为嵌入式系统中的Python代码生成文档的指南,但指南的前几步对您也可能有用:

如何为在嵌入式系统中运行的Python代码生成sphinx文档

[编辑]

以下是逐步说明:

  1. 创建 lib.py 文件
  2. 创建文档文件夹: mkdir doc

    ├── doc/
    └── lib.py
    
  3. 进���doc/目录: cd doc
  4. 执行sphinx-quickstart(确保选择autodoc: y, Makefile: y)
  5. 编辑conf.py文件并指定sys.path: sys.path.insert(0, os.path.abspath('..'))
  6. 编辑index.rst文件并在toctree中指定modules:

  7. .. toctree::
        :maxdepth: 2
    
        modules
    
  8. 执行 sphinx-apidoc -o . ..
  9. 生成HTML输出:make html
  10. 查看文档:firefox _build/html/index.html

谢谢您的回复!是的,我已经选择了“是”来使用autodoc。如果我在index.rst中没有添加_modules_,则执行_sphinx-apidoc -o_会创建lib.rstmodules.rst,但它们是空的。如果我在index.rst中添加_modules_,然后再执行_sphinx-apidoc -o_:它会创建与第一种情况相同的lib.rst,但在尝试创建modules.rst时会出现IOError:[Errno 5]输入/输出错误。 - natalia
是的,我已经看过你的Sphinx指南了,而且我几乎做了同样的事情。 - natalia
我重现了你的场景并添加了一份逐步列表,请检查是否有效。 - jcarballo
2
好的! 它有效了!非常感谢 @jcarballo!实际上,如果我们在index.rst中添加了_modules_, 它需要明确所有rst文件必须与index.rst位于同一位置。因此最好直接在与index.rst相同的目录(在我的情况下是source目录)中执行_sphinx-apidoc -o_。 - natalia
太好了,它起作用了!感谢你提醒我关于.rst文件的放置位置,我之前并不知道。 - jcarballo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接