如何使用 Python-Sphinx 生成 HTML 文档? [英] How to generate HTML Documentation with Python-Sphinx?

查看:25
本文介绍了如何使用 Python-Sphinx 生成 HTML 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PyCharm 开发一个 Python 项目,现在我需要生成相应的 API 文档.我正在使用 docstrings 记录代码方法和类.我读过关于 Sphinx 和 Doxygen 的文章,其中 Sphinx 是目前最推荐的.我尝试配置 Sphinx whitin PyCharm,但没有成功.

这是项目结构:

这是与命令 Sphinx Quickstart

的 I/O 交互

C:PythonPython36Scriptssphinx-quickstart.exe欢迎使用 Sphinx 1.6.3 快速入门实用程序.请输入以下设置的值(只需按 Enter 即可接受默认值,如果在括号中给出).输入文档的根路径.>文档的根路径 [.]:您有两个选项可用于放置 Sphinx 输出的构建目录.要么,您使用根路径中的目录_build",要么分开根路径中的source"和build"目录.>单独的源目录和构建目录 (y/n) [n]:在根目录中,将创建另外两个目录;_模板"用于自定义 HTML 模板,_static"用于自定义样式表和其他静态文件.您可以输入另一个前缀(例如.")来替换下划线.>模板和静态目录 [_]: 的名称前缀.项目名称将出现在构建文档中的多个位置.>项目名称:属性图分析器>作者姓名:M.C &D.A.T.Sphinx 具有版本"和发布"的概念软件.每个版本可以有多个版本.例如,对于Python 的版本类似于 2.5 或 3.0,而版本是2.5.1 或 3.0a1 之类的东西.如果你不需要这种双重结构,只需将两者设置为相同的值.>项目版本[]:0.0.1>项目发布 [0.0.1]:如果文件要用英语以外的其他语言编写,您可以在此处通过语言代码选择一种语言.然后狮身人面像将它生成的文本翻译成该语言.有关支持的代码列表,请参阅http://sphinx-doc.org/config.html#confval-language.>项目语言 [en]:源文件的文件名后缀.通常,这是.txt"或.rst".只有带有此后缀的文件才被视为文档.>源文件后缀[.rst]:一个文档的特殊之处在于它被认为是内容树",即层次结构的根的文件.通常,这是索引",但如果您的索引"document 是一个自定义模板,您也可以将其设置为另一个文件名.>您的主文档的名称(无后缀)[索引]:Sphinx 还可以为 epub 输出添加配置:>你想使用 epub builder (y/n) [n]:请说明您是否要使用以下 Sphinx 扩展之一:>autodoc: 自动从模块中插入文档字符串 (y/n) [n]: y>doctest: 自动测试 doctest 块中的代码片段 (y/n) [n]:>intersphinx:不同项目的 Sphinx 文档之间的链接 (y/n) [n]:>待办事项:编写可以在构建时显示或隐藏的待办事项"条目(y/n)[n]:>覆盖率:检查文档覆盖率 (y/n) [n]:>imgmath:包括数学,呈现为 PNG 或 SVG 图像(y/n)[n]:>mathjax:包括数学,由 MathJax (y/n) [n] 在浏览器中呈现:>ifconfig:根据配置值有条件地包含内容(y/n)[n]:>viewcode: 包括到文档化 Python 对象源代码的链接 (y/n) [n]: y>githubpages:创建 .nojekyll 文件以在 GitHub 页面上发布文档 (y/n) [n]: y可以为您生成一个 Makefile 和一个 Windows 命令文件,以便您只需要运行,例如`make html' 而不是调用 sphinx-build直接地.>创建 Makefile?(是/否)[是]:>创建 Windows 命令文件?(是/否)[是]:创建文件 .conf.py.创建文件 .index.rst.创建文件 .Makefile.创建文件 .make.bat.完成:已创建初始目录结构.您现在应该填充您的主文件 .index.rst 并创建其他文档源文件.使用 Makefile 构建文档,如下所示:制作建设者其中builder"是受支持的构建器之一,例如html、乳胶或链接检查.进程以退出代码 0 结束

然后我移动到 /docs 文件夹

,编辑 conf.py 文件:

#!/usr/bin/env python3# -*- 编码:utf-8 -*-## "Query Rewriter" 文档构建配置文件,由创建# sphinx-quickstart 于 2017 年 9 月 21 日星期四 14:56:19.## 这个文件是 execfile()d,当前目录设置为其# 包含目录.## 请注意,并非所有可能的配置值都存在于此# 自动生成的文件.## 所有配置值都有一个默认值;被注释掉的值# 服务显示默认值.# 如果扩展(或用 autodoc 记录的模块)在另一个目录中,# 在此处将这些目录添加到 sys.path.如果目录是相对于# 文档根目录,使用 os.path.abspath 使其成为绝对路径,如此处所示.#导入操作系统导入系统sys.path.append(os.path.abspath("../../query_rewriter"))# -- 通用配置 ------------------------------------------------------------# 如果您的文档需要最小的 Sphinx 版本,请在此处说明.## 需要_sphinx = '1.0'# 在此处添加任何 Sphinx 扩展模块名称,作为字符串.他们可以# Sphinx 附带的扩展(名为sphinx.ext.*")或您的自定义# 那些.扩展 = ['sphinx.ext.autodoc','sphinx.ext.intersphinx','sphinx.ext.ifconfig','sphinx.ext.viewcode','sphinx.ext.githubpages']# 在此处添加任何包含模板的路径,相对于该目录.模板路径 = ['_模板']# 源文件名的后缀.# 您可以指定多个后缀作为字符串列表:## source_suffix = ['.rst', '.md']source_suffix = '.rst'# 主目录树文档.master_doc = '索引'# 关于项目的一般信息.project = '"查询重写器"'版权 = '2017, M.C &D.A.T'作者 = 'M.C &D.A.T'# 你正在记录的项目的版本信息,作为替代# |版本|和 |release|,也用于整个其他地方# 构建文档.## 短 X.Y 版本.版本 = '0.0.1'# 完整版,包括 alpha/beta/rc 标签.发布 = '0.0.1'# Sphinx 自动生成的内容的语言.参考文档# 获取支持的语言列表.## 如果您通过 gettext 目录进行内容翻译,也会使用此选项.# 通常你从命令行为这些情况设置语言".语言 = "en"# 模式列表,相对于源目录,匹配文件和# 查找源文件时要忽略的目录.# 这种模式也会影响 html_static_path 和 html_extra_path排除模式 = []# 要使用的 Pygments(语法高亮)样式的名称.pygments_style = '狮身人面像'# 如果为真,`todo` 和 `todoList` 产生输出,否则它们什么也不产生.todo_include_todos = 假# -- HTML 输出选项 ----------------------------------------------# 用于 HTML 和 HTML 帮助页面的主题.请参阅文档# 内置主题列表.#html_theme = '雪花石膏'# 主题选项是特定于主题的,可以自定义主题的外观和感觉# 更远.有关每个主题的可用选项列表,请参阅# 文档.## html_theme_options = {}# 在此处添加任何包含自定义静态文件(如样式表)的路径,# 相对于这个目录.它们在内置静态文件之后被复制,# 所以名为default.css"的文件将覆盖内置的default.css".html_static_path = ['_static']# 自定义侧边栏模板,必须是映射文档名称的字典# 到模板名称.## 这是雪花石膏主题所必需的# 参考:http://alabaster.readthedocs.io/en/latest/installation.html#sidebarshtml_sidebars = {'**': ['about.html','navigation.html','relations.html', # 需要'show_related':真正的主题选项来显示'searchbox.html','donate.html',]}# -- HTMLHelp 输出选项 ------------------------------------------# HTML 帮助生成器的输出文件基本名称.htmlhelp_basename = 'QueryRewriterdoc'# -- LaTeX 输出的选项 ---------------------------------乳胶元素 = {# 纸张尺寸('letterpaper' 或 'a4paper').## 'papersize': '信纸',# 字体大小('10pt'、'11pt' 或 '12pt').## 'pointsize': '10pt',# LaTeX 序言的附加内容.## '序言': '',# Latex 图形(浮点数)对齐## 'figure_align': 'htbp',}# 将文档树分组到 LaTeX 文件中.元组列表#(源开始文件,目标名称,标题,# author, documentclass [howto, manual, or own class]).latex_documents = [(master_doc, 'QueryRewriter.tex', '"查询重写器" 文档','MC \&D.A.T', '手册'),]# -- 手册页输出选项 ---------------------------# 每个手册页一个条目.元组列表#(源开始文件、名称、描述、作者、手册部分).man_pages = [(master_doc, 'queryrewriter', '"查询重写器" 文档',[作者], 1)]# -- Texinfo 输出选项 -------------------------------# 将文档树分组到 Texinfo 文件中.元组列表# (源起始文件、目标名称、标题、作者、# dir 菜单项、描述、类别)texinfo_documents = [(master_doc, 'QueryRewriter', '"Query Rewriter" 文档',author, 'QueryRewriter', '项目的一行描述.','各种各样的'),]# intersphinx 的示例配置:参考 Python 标准库.intersphinx_mapping = {'https://docs.python.org/': 无}

并运行以下命令:

B:\_Python_WorkspaceAttributedGraphProfilerdocs>制作 html运行狮身人面像 v1.6.3制作输出目录...加载腌制环境...尚未创建构建 [mo]: 0 个过期的 po 文件的目标构建 [html]: 1 个已过期源文件的目标更新环境:添加 1 个,更改 0 个,删除 0 个阅读来源... [100%] 索引正在寻找现在过时的文件...没有找到酸洗环境...完成检查一致性...完成准备文件...完成写入输出... [100%] 索引生成索引... genindex写额外的页面...搜索复制静态文件...完成复制额外的文件...完成转储英文搜索索引(代码:en)...完成倾销对象库存...完成构建成功.搭建完成.HTML 页面位于 .buildhtml 中.B:\_Python_WorkspaceAttributedGraphProfilerdocs>

我以为我已经完成了,但这是我得到的糟糕结果,没有任何类和模块的文档.

index.html

genindex.html

我做错了吗?提前感谢您的宝贵时间.

解决方案

刚刚解决了同样的问题Juan.不幸的是,Sphinx 并不是一个完全自动化的文档生成器,它来自代码注释,例如 doxygen、jautodoc 等.正如 mzjn 的

  1. 在 PyCharm 的 Run/Edit-Configurations... 中创建一个 Python Docs 任务,如下所示.

    command 显示文档类型.

    Input 显示我们的第一个文件路径.

    output 显示了我们的文档输出目录.(最后:))

  1. 尽情奔跑吧……

更新 2:

如果您与 Readthedocs 集成:(注册和 github 授权后)

  1. 您必须将模块路径添加到 sys.path.Readthedocs 调用 sphinx-build 所以它应该知道 py 文件的路径.基本上取消注释 conf.py 中的行

    sys.path.insert(0, os.path.abspath('..//..//'))(如果工作目录是pyfiles/Docs/source)

  2. 始终检查 readthedocs 上的构建结果,只需单击以下行:您将查看是否有错误或警告.
  3. 如果你没有做 1 &2 可能你不会有一个有效的索引和表格"部分.genindex.htmlpy-modindex.html 将分别是一个空模板和一个不存在的页面.

I'm working on a Python project using PyCharm and now I need to generate the corresponding API documentation. I'm documenting the code methods and classes using docstrings. I read about Sphinx and Doxygen, with Sphinx being the most recommended right now. I tried to configure Sphinx whitin PyCharm but I had no luck in getting it working.

This is the project structure:

and this was the I/O interaction with the command Sphinx Quickstart

C:PythonPython36Scriptssphinx-quickstart.exe
Welcome to the Sphinx 1.6.3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]: 

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: 

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]: .

The project name will occur in several places in the built documentation.
> Project name: Attributed Graph Profiler
> Author name(s): M.C & D.A.T.

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version []: 0.0.1
> Project release [0.0.1]: 

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]: 

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]: 

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]: 

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]: 

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: 
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: 
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: 
> coverage: checks for documentation coverage (y/n) [n]: 
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]: 
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: 
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: 
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: y

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]: 
> Create Windows command file? (y/n) [y]: 

Creating file .conf.py.
Creating file .index.rst.
Creating file .Makefile.
Creating file .make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file .index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.


Process finished with exit code 0

Then I moved to the /docs folder

, edited the conf.py file:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# "Query Rewriter" documentation build configuration file, created by
# sphinx-quickstart on Thu Sep 21 14:56:19 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.append(os.path.abspath("../../query_rewriter"))


# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
    'sphinx.ext.intersphinx',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',
    'sphinx.ext.githubpages']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = '"Query Rewriter"'
copyright = '2017, M.C & D.A.T'
author = 'M.C & D.A.T'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False


# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
    '**': [
        'about.html',
        'navigation.html',
        'relations.html',  # needs 'show_related': True theme option to display
        'searchbox.html',
        'donate.html',
    ]
}


# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'QueryRewriterdoc'


# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'QueryRewriter.tex', '"Query Rewriter" Documentation',
     'M.C \& D.A.T', 'manual'),
]


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'queryrewriter', '"Query Rewriter" Documentation',
     [author], 1)
]


# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'QueryRewriter', '"Query Rewriter" Documentation',
     author, 'QueryRewriter', 'One line description of project.',
     'Miscellaneous'),
]




# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}

and ran the following command:

B:\_Python_WorkspaceAttributedGraphProfilerdocs>make html
Running Sphinx v1.6.3
making output directory...
loading pickled environment... not yet created
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index
generating indices... genindex
writing additional pages... search
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded.

Build finished. The HTML pages are in .buildhtml.

B:\_Python_WorkspaceAttributedGraphProfilerdocs>

I thought I was done, but this is the poor result I got, without any documentation for classes and modules.

index.html

genindex.html

Am I doing something wrong? Thanks in advance for your time.

解决方案

Just solved excatly the same problem Juan. Sphinx unfortunately is not a fully automated doc generator from code comments like doxygen, jautodoc etc. As in the link mentioned in mzjn's comment some steps are necessary for a proper work.

As I see you are working on Pycharm, so I will touch on Pycharm-Sphinx integration. I hope you will not have to change anything manually like conf.py.

  1. In PyCharm "File/setting/tools/python integrated tools" define the sphinx-working-directory to codebase/Docs. (Just for clearness, choose where ever you want)

    So your sphinx scripts will run at this path.


  1. Run "Tools/Sphinx Quickstart" in PyCharm

    Like you wrote above select the proper options. But "autodoc" is a must (y) and "Separate source and build directories" is recommended (y) to understand what is going on. This script will generate the skeleton of the sphinx project.


  1. Create a python task in Run/Edit-Configurations... in PyCharm like below.

    Be careful with the python interpreter and your script (If you use python environment like me). This script will generate the rst files for your modules.

    source/ shows Docs/Source directory created by 1.step. It has the .rst files for our modules.

    ../ shows our modules' py files.

UPDATE 1:

A-) Run this task to generate the rst files.

B-) Add "modules" term to index.rst file, like;

bla bla
.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules
bla bla

There is no need to run and add "modules" term again in every doc creation. Step A is necessary only when new modules are introduced in the project.

  1. Create a Python Docs task in Run/Edit-Configurations... in PyCharm like below.

    command shows the documentation type.

    Input shows our rst files path.

    output shows our document output directory. (FINALLY :))

  1. Run and enjoy...

UPDATE 2:

If you integrate with the Readthedocs: (After sign up and github authorization)

  1. You have to add modules path to sys.path. Readthedocs calls sphinx-build so it should know the path of the py files. Basically uncomment the line in conf.py

    sys.path.insert(0, os.path.abspath('..//..//')) (if working directory is pyfiles/Docs/source)

  2. Always check the build results on readthedocs, siply click on lines like these: You will see if there is an error or a warning.
  3. If you didn't do 1 & 2 probably you will not have a working "Indices and tables" section. genindex.html and py-modindex.html will be respectively an empty template and a non existing page.

这篇关于如何使用 Python-Sphinx 生成 HTML 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆