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

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

问题描述

我正在使用PyCharm进行Python项目,现在我需要生成相应的API文档。我正在使用 docstrings 记录代码方法和类。我读到了有关狮身人面像和Doxygen的信息,现在最推荐使用狮身人面像。我尝试配置Sphinx whitin PyCharm,但我没有运气。



这是项目结构





这是与命令 Sphinx的I / O交互快速入门

  C:\Python\Python36\Scripts\sphinx-quickstart.exe 
欢迎使用Sphinx 1.6.3快速入门实用程序。

请输入以下设置的值(如果在括号中给出一个值,则只需按Enter键即可接受
的默认值)。

输入文档的根路径。
>文档[。]的根路径:

您可以使用两个选项来放置Sphinx输出的构建目录。
要么在根路径中使用目录 _build,要么在根路径中分隔
source和 build目录。
>单独的源目录和构建目录(y / n)[n]:

在根目录中,将另外创建两个目录。 _templates
用于自定义HTML模板, _ static用于自定义样式表和其他静态
文件。您可以输入另一个前缀(例如。)来替换下划线。
>模板的名称前缀和静态目录[_] :。

项目名称将在生成的文档中的多个位置出现。
>项目名称:属性图分析器
>作者姓名:M.C& D.A.T.

Sphinx具有
软件的版本和发行的概念。每个版本可以有多个发行版。例如,对于
Python,版本是2.5或3.0,而发行版是
,例如2.5.1或3.0a1。如果您不需要这种双重结构,只需将
都设置为相同的值。
>项目版本[]:0.0.1
>项目发布[0.0.1]:

如果文档使用英语以外的其他语言书写,则
您可以在此处通过语言代码选择一种语言。然后,Sphinx将
生成的文本翻译成该语言。

有关受支持代码的列表,请参见
http://sphinx-doc.org/config.html#confval-language。
>项目语言[en]:

源文件的文件名后缀。通常,这是 .txt
或 .rst。仅将带有该后缀的文件视为文档。
>源文件后缀[.rst]:

一个文档的特殊之处在于它被视为
内容树的顶层节点,也就是说,它是层次结构的根
的文件。通常,这是索引,但是如果索引
文档是自定义模板,则还可以将其设置为另一个文件名。
>主文档的名称(不带后缀)[索引]:

Sphinx还可以为epub输出添加配置:
>您是否要使用epub构建器(y / n)[n]:

请指明是否要使用以下Sphinx扩展名之一:
> autodoc:自动从模块中插入文档字符串(y / n)[n]:y
> doctest:自动测试doctest块中的代码段(y / n)[n]:
> intersphinx:不同项目的Sphinx文档之间的链接(y / n)[n]:
> todo:写 todo条目,这些条目可以在构建时显示或隐藏(y / n)[n]:
> coverage:检查文档覆盖率(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? (y / n)[y]:
>创建Windows命令文件? (y / n)[y]:

创建文件.\conf.py。
创建文件.\index.rst。
创建文件.\Makefile。
创建文件.\make.bat。

完成:初始目录结构已创建。

现在,您应该填充主文件.\index.rst并创建其他文档
源文件。使用Makefile生成文档,如下所示:
make builder
其中 builder是受支持的构建器之一,例如html,乳胶或链接检查。


处理完成,退出代码为0

然后我移动了到 / docs 文件夹





,已编辑 conf.py 文件:

 # !/ usr / bin / env python3 
#-*-编码:utf-8-*-

#查询重写器文档构建配置文件,由
创建sphinx-quickstart于2017年9月21日星期四14:56:19。

#此文件为execfile()d,当前目录设置为包含目录的
#。

#请注意,此
#自动生成的文件中并不存在所有可能的配置值。

#所有配置值都有默认值;
#注释掉的值用于显示默认值。

#如果扩展名(或带有autodoc的模块)在另一个目录中,则
#在此处将这些目录添加到sys.path中。如果目录相对于
#文档根目录,请使用os.path.abspath使其成为绝对目录,如下所示。

import os
import sys
sys.path.append(os.path.abspath( ../../ query_rewriter))


#-常规配置--------------------------------------- ---------

#如果您的文档需要Sphinx的最低版本,请在此处进行说明。

#needs_sphinx ='1.0'

#在此处添加任何Sphinx扩展模块名称作为字符串。它们可以是Sphinx附带的
#扩展名(名为 sphinx.ext。*),也可以是您自定义的
#扩展名。
扩展名= ['sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode' ,
'sphinx.ext.githubpages']

#在此处添加相对于该目录的所有包含模板的路径。
templates_path = [’_templates']

#源文件名的后缀。
#您可以将多个后缀指定为字符串列表:

#source_suffix = ['.rst','.md']
source_suffix ='.rst'

#主toctree文档。
master_doc ='index'

#有关该项目的一般信息。
project =‘ Query Rewriter’
版权=’2017,M.C& D.A.T’
author =’M.C& D.A.T’

#您正在记录的项目的版本信息,可代替
#|版本|和| release |,在
#生成的文档中也用在其他各个地方。

#简短的X.Y版本。
版本=‘0.0.1’
#完整版本,包括alpha / beta / rc标签。
release =‘0.0.1’

#Sphinx自动生成的内容语言。有关支持的语言列表,请参阅文档
#。

#如果您通过gettext目录执行内容翻译,则也可以使用它。
#通常,在这种情况下,您可以从命令行设置语言。
语言= en

#相对于源目录的模式列表,这些模式匹配文件和
#在查找源文件时要忽略的目录。
#此模式还会影响html_static_path和html_extra_path
exclude_patterns = []

#使用的Pygments(语法突出显示)样式的名称。
pygments_style ='狮身人面像'

#如果为true,`todo`和`todoList`会产生输出,否则它们什么也不会产生。
todo_include_todos = False


#-HTML输出选项------------------------ ----------------------

#用于HTML和HTML帮助页面的主题。请参阅文档
#内置主题列表。

html_theme ='alabaster'

#主题选项特定于主题,并进一步自定义主题
#的外观。有关每个主题可用选项的列表,请参见
#文档。

#html_theme_options = {}

#在此处添加任何包含自定义静态文件(例如样式表)的路径,相对于该目录为
#。它们被复制到内置静态文件
#之后,因此名为 default.css的文件将覆盖内置 default.css。
html_static_path = [’_static']

#自定义边栏模板,必须是将文档名称
#映射到模板名称的字典。

#雪花石膏主题
#这是必需的#refs:http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**':[
'about.html',
'navigation.html',
'relations.html',#需要'show_related':的真实主题选项display
'searchbox.html',
'donate.html',
]
}


#-HTMLHelp输出的选项------------------------------------------

#输出HTML帮助构建器的文件基本名称。
htmlhelp_basename ='QueryRewriterdoc'


#-LaTeX输出选项---------------------- -----------------------

latex_elements = {
#纸张尺寸( letterpaper或 a4paper )。

#‘papersize':‘letterpaper’,

#字体大小( 10pt, 11pt或 12pt)。

#‘pointsize’:‘10pt’,

#LaTeX序言的其他内容。

#'preamble':'',

#乳胶图形(浮动)对齐

#'figure_align':'htbp',
}

#将文档树分组为LaTeX文件。元组列表
#(源开始文件,目标名称,标题,
#作者,文档类[howto,手册或本人类])。
latex_documents = [
(master_doc,'QueryRewriter.tex',' Query Rewriter Documentation',
'MC \\&DAT','manual'),
]


#-手动页面输出的选项-------------------------- -------------

#每本手册页一次。元组列表
#(源开始文件,名称,描述,作者,手册部分)。
man_pages = [
(master_doc,'queryrewriter',' Query Rewriter Documentation',
[author],1)
]


#-Texinfo输出的选项---------------------------------------- ---

#将文档树分为Texinfo文件。元组列表
#(源起始文件,目标名称,标题,作者,
#目录菜单项,描述,类别)
texinfo_documents = [
(master_doc, QueryRewriter ,查询重写器文档,
作者, QueryRewriter,项目的一行描述。,
其他),
]




#intersphinx的示例配置:请参见Python标准库。
intersphinx_mapping = {'https://docs.python.org/':无}

并运行以下命令:

  B:\_Python_Workspace\AttributedGraphProfiler\docs>使html 
正在运行Sphinx v1.6.3
正在建立输出目录...
正在加载腌制的环境...尚未创建
构建[mo]:0 po文件已过期
的目标建立[html]:1个过期
更新环境的源文件的目标:添加1个,更改0个,删除0个
读取源... [100%]索引
寻找现在已经过时的文件...没有发现
酸洗环境...完成
检查一致性...完成
准备文档...完成
写输出... [100 %]索引
生成索引... genindex
编写其他页面...搜索
复制静态文件...完成
复制多余文件...完成
倾销英文搜索代码(代码:en)...完成
倾销对象清单...完成
建立成功ed。

构建完成。 HTML页面位于.build\html中。

B:\_Python_Workspace\AttributedGraphProfiler\docs>

我以为我做完了,但是结果很糟糕,没有任何关于课程的文档和



index.html



genindex.html



Am我做错了吗?预先感谢您的宝贵时间。

解决方案

完全解决了同样的问题Juan。 不幸的是,狮身人面像不是由代码注释生成的全自动文档生成器,例如doxygen,jautodoc等。
如mzjn的


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



    命令显示文档类型。



    输入显示了我们的第一个文件路径。



    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.html py-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:\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

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_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>

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天全站免登陆