如何使用 Python-Sphinx 生成 HTML 文档?
How to generate HTML Documentation with Python-Sphinx?
我正在使用 PyCharm 开发一个 Python 项目,现在我需要生成相应的 API 文档。我正在使用 docstrings
记录代码方法和 类。我阅读了有关 Sphinx 和 Doxygen 的信息,目前最推荐使用 Sphinx。我尝试配置 Sphinx whitin PyCharm,但我没有成功。
这是项目结构:
这是 I/O 与命令 Sphinx Quickstart
的交互
C:\Python\Python36\Scripts\sphinx-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
然后我移动到/docs
文件夹
,编辑了 conf.py 文件:
#!/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}
和运行以下命令:
B:\_Python_Workspace\AttributedGraphProfiler\docs>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 .build\html.
B:\_Python_Workspace\AttributedGraphProfiler\docs>
我以为我已经完成了,但这是我得到的糟糕结果,没有任何 类 和模块的文档。
index.html
genindex.html
我是不是做错了什么?预先感谢您的宝贵时间。
在 make html
之前,您应该阅读代码中的 apidoc 注释并创建 .rst 文件。
你应该 运行 从你的项目根文件夹中这样的东西:
sphinx-apidoc . -o ./docs -f tests
这将重写 docs
文件夹中的 .rst 文件(因此 -f
)并忽略 tests
包中的 apidoc 读取。
有关 sphinx-apidoc
的更多信息,您可以找到 here。
之后是 make html
命令。
Juan 刚刚解决了同样的问题。 不幸的是,Sphinx 不是来自代码注释的全自动文档生成器,例如 doxygen、jautodoc 等。
正如在 mzjn 的 comment 中提到的 link 一样,一些步骤对于正常工作是必要的。
我看到你正在研究 Pycharm,所以我将谈谈 Pycharm-Sphinx 集成。我希望您不必像 conf.py.
那样手动更改任何内容
在 PyCharm "File/setting/tools/python integrated tools" 中将 sphinx-working-directory 定义为 codebase/Docs。 (为了清楚起见,选择你想要的地方)
因此您的 sphinx 脚本将 运行 位于此路径。
运行 "Tools/Sphinx Quickstart" 在 PyCharm
就像你上面写的 select 正确的选项。但是 "autodoc" 是必须的 (y) 并且建议 "Separate source and build directories" (y) 以了解发生了什么。 此脚本将生成 sphinx 项目的骨架。
在 Run/Edit-Configurations 中创建一个 python 任务...在 PyCharm 中,如下所示。
小心 python 解释器和你的脚本(如果你像我一样使用 python 环境)。 此脚本将为您的模块生成第一个文件。
source/
显示由 1.step 创建的 Docs/Source 目录。它有我们模块的 .rst 文件。
../
显示我们模块的 py 文件。
更新 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
无需在每个文档创建中再次 运行 和添加 "modules" 术语。只有在项目中引入新模块时才需要步骤A。
在 Run/Edit-Configurations 中创建一个 Python 文档任务...在 PyCharm 中,如下所示。
command
显示文档类型。
Input
显示我们的第一个文件路径。
output
显示我们的文档输出目录。 (最后 :))
- 运行 享受...
更新 2:
如果您与 Readthedocs 集成:(在注册和 github 授权之后)
您必须将模块路径添加到 sys.path。 Readthedocs 调用 sphinx-build 所以它应该知道 py 文件的路径。基本上取消注释 conf.py
中的行
sys.path.insert(0, os.path.abspath('..//..//'))
(如果工作目录是 pyfiles/Docs/source)
- 始终在 readthedocs 上检查构建结果,只需单击如下行:您将看到是否有错误或警告。
- 如果您没有执行 1 和 2,您可能不会有有效的 "Indices and tables" 部分。 genindex.html 和 py-modindex.html 将分别是一个 空模板 和不存在的页面。
我正在使用 PyCharm 开发一个 Python 项目,现在我需要生成相应的 API 文档。我正在使用 docstrings
记录代码方法和 类。我阅读了有关 Sphinx 和 Doxygen 的信息,目前最推荐使用 Sphinx。我尝试配置 Sphinx whitin PyCharm,但我没有成功。
这是项目结构:
这是 I/O 与命令 Sphinx Quickstart
的交互C:\Python\Python36\Scripts\sphinx-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
然后我移动到/docs
文件夹
,编辑了 conf.py 文件:
#!/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}
和运行以下命令:
B:\_Python_Workspace\AttributedGraphProfiler\docs>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 .build\html.
B:\_Python_Workspace\AttributedGraphProfiler\docs>
我以为我已经完成了,但这是我得到的糟糕结果,没有任何 类 和模块的文档。
index.html
genindex.html
我是不是做错了什么?预先感谢您的宝贵时间。
在 make html
之前,您应该阅读代码中的 apidoc 注释并创建 .rst 文件。
你应该 运行 从你的项目根文件夹中这样的东西:
sphinx-apidoc . -o ./docs -f tests
这将重写 docs
文件夹中的 .rst 文件(因此 -f
)并忽略 tests
包中的 apidoc 读取。
有关 sphinx-apidoc
的更多信息,您可以找到 here。
之后是 make html
命令。
Juan 刚刚解决了同样的问题。 不幸的是,Sphinx 不是来自代码注释的全自动文档生成器,例如 doxygen、jautodoc 等。 正如在 mzjn 的 comment 中提到的 link 一样,一些步骤对于正常工作是必要的。
我看到你正在研究 Pycharm,所以我将谈谈 Pycharm-Sphinx 集成。我希望您不必像 conf.py.
那样手动更改任何内容在 PyCharm "File/setting/tools/python integrated tools" 中将 sphinx-working-directory 定义为 codebase/Docs。 (为了清楚起见,选择你想要的地方)
因此您的 sphinx 脚本将 运行 位于此路径。
运行 "Tools/Sphinx Quickstart" 在 PyCharm
就像你上面写的 select 正确的选项。但是 "autodoc" 是必须的 (y) 并且建议 "Separate source and build directories" (y) 以了解发生了什么。 此脚本将生成 sphinx 项目的骨架。
在 Run/Edit-Configurations 中创建一个 python 任务...在 PyCharm 中,如下所示。
小心 python 解释器和你的脚本(如果你像我一样使用 python 环境)。 此脚本将为您的模块生成第一个文件。
source/
显示由 1.step 创建的 Docs/Source 目录。它有我们模块的 .rst 文件。../
显示我们模块的 py 文件。
更新 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
无需在每个文档创建中再次 运行 和添加 "modules" 术语。只有在项目中引入新模块时才需要步骤A。
在 Run/Edit-Configurations 中创建一个 Python 文档任务...在 PyCharm 中,如下所示。
command
显示文档类型。Input
显示我们的第一个文件路径。output
显示我们的文档输出目录。 (最后 :))
- 运行 享受...
更新 2:
如果您与 Readthedocs 集成:(在注册和 github 授权之后)
您必须将模块路径添加到 sys.path。 Readthedocs 调用 sphinx-build 所以它应该知道 py 文件的路径。基本上取消注释 conf.py
中的行sys.path.insert(0, os.path.abspath('..//..//'))
(如果工作目录是 pyfiles/Docs/source)- 始终在 readthedocs 上检查构建结果,只需单击如下行:您将看到是否有错误或警告。
- 如果您没有执行 1 和 2,您可能不会有有效的 "Indices and tables" 部分。 genindex.html 和 py-modindex.html 将分别是一个 空模板 和不存在的页面。