Sphinx:如何使用Sphinx生成文档

时间:2017-07-05 01:45:17

标签: python bash python-sphinx

当我们输入命令 sphinx-quickstart 时,我们必须多次输入值。
例如:

> Root path for the documentation [.]:
> Separate source and build directories (y/n) [n]: 
> Name prefix for templates and static dir [_]:
> Project name: 
> Author name(s):
> Project version []: 
> Project release []:
> Project language [en]: 
> Source file suffix [.rst]: 
> Name of your master document (without suffix) [index]:
> Do you want to use the epub builder (y/n) [n]:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> 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]: 
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:
> Create Makefile? (y/n) [y]: 
> Create Windows command file? (y/n) [y]:

我们有什么方法可以解决这个繁琐的工作吗? 例如任何bash脚本或python脚本?

相关论点是:

> Project name: My Project
> Author name(s): My Name
> Project version []: 1
> autodoc: automatically insert docstrings from modules (y/n) [n]: y 
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y

所有其余的只是空字符串。

我的尝试

printf '\n\n\nMyProject\nBhishan Poudel\n1\n\n\n\n\n\ny\ny\n\n\n\n\n\n\ny\n\n\n\n' | sphinx-quickstart

尝试2

# run_sphinx_quickstart.py
#!/usr/bin/env python3
import subprocess

sphinx_args = {
'Root_path'        : '',
'Separate_source'  : '',
'Name_prefix'      : '',
'Project_name'     : 'My Project',
'Author_name'      : 'Bhishan Poudel',
'Project_version'  : '1',
'Project_release'  : '',
'Project_language' : 'en',
'Source_file'      : '.rst',
'master_document'  : 'index',
'epub'             : '',
'autodoc'          : 'y',
'doctest'          : 'y',
'intersphinx'      : 'n',
'todo'             : 'n',
'coverage'         : 'n',
'imgmath'          : 'n',
'mathjax'          : 'n',
'ifconfig'         : 'n',
'viewcode'         : 'y',
'githubpages'      : 'n',
'Makefile'         : 'y',
'Windows_Makefile ': 'n' }

for k,v in sphinx_args.items():
    print(k,'\t\t:', v)


subprocess.call('sphink-quickstart', shell=True)

# I don't know how to caputre the outputs of shell commands!!

将非常感谢帮助。

相关链接:

2 个答案:

答案 0 :(得分:2)

您可以使用自己喜欢的选项调用sphinx-quickstart -q

答案 1 :(得分:0)

文档链接为Invocation of sphinx-quickstart

如何使用Sphinx生成文档?

必填文件:

  • 〜/ .bash_profile中
  • 〜/应用/ edit_sphinx_conf.py
  • 〜/应用/ custom.css
  • 〜/应用/标识/ logo.jpg
  • 〜/的.config / geany / snippets.conf
  • 〜/的.config / geany / filedefs / filetypes.restructuredtext

.bash_profile

##==============================================================================
# Sphinx documentation
##==============================================================================
alias sprm='rm -rf  docs/build docs/html docs/Makefile docs/rst docs/source docs/pdf'
alias spo='open docs/html/index.html'



# Documentation using sphinx
# Usage: spallf FOLDER
# Final output: docs/html/index.html
function spallf () {

    #1. Create folders
    mkdir -p docs/html docs/rst docs/rst/_static

    #2. Copy custom.css file to rst/_static
    cp ~/Applications/custom.css docs/rst/_static/

    #3. Quickstart 
    # Outputs: docs
    # docs has three things: Makefile source build
    sphinx-quickstart -q -p "Research" -a "Bhishan Poudel" -v 1 -r 0 \
     --ext-autodoc --ext-doctest --ext-viewcode --ext-imgmath \
     --no-batchfile --sep docs

    #4. Copy edit_conf file 
    cp ~/Applications/edit_sphinx_conf.py edit_sphinx_conf.py

    #5. Edit conf.py file.
    python3 edit_sphinx_conf.py; rm -rf edit_sphinx_conf.py

    #6. Create html folder (also creates doctrees).
    cd docs; make html; cd -; pwd


    #7. Auto create rst files.
    sphinx-apidoc -o docs/rst "$1"

    #8. Copy conf.py to docs/rst folder.
    cp docs/source/conf.py docs/rst/; mv docs/rst/modules.rst docs/rst/index.rst

    #9. Add path to conf.py
    awk -v n=23 -v s="sys.path.append('../$1')" 'NR == n {print s} {print}' \
    docs/rst/conf.py > docs/rst/conf_new.py; 
    rm docs/rst/conf.py; mv docs/rst/conf_new.py docs/rst/conf.py

    #10. Add Table of Contents to index.rst
    awk -v n=1 -v s=".. contents:: Table of Contents\n   :depth: 3\n\n" \
                    'NR == n {print s} {print}' \
                  docs/rst/index.rst > docs/rst/tmp; mv docs/rst/tmp docs/rst/index.rst

    #11. Add Logo to index.rst
    mkdir -p docs/html/_images
    cp ~/Applications/logos/logo.jpg docs/html/_images/logo.jpg
    awk -v n=1 -v s=" .. image:: ../html/_images/logo.jpg\n   :height: 100px\n   :width: 3000 px\n   :align: center\n\n" \
                    'NR == n {print s} {print}' \
                  docs/rst/index.rst > docs/rst/tmp; mv docs/rst/tmp docs/rst/index.rst


    #12. Build to get html and pdf
    cd docs; sphinx-build -b html rst html; cd -

    # Also generate pdf
    #cd docs; sphinx-build -b latex rst latex; cd -; pwd
    #cd docs/latex; make;  cd - ; mkdir docs/pdf
    #cp docs/latex/Research.pdf docs/pdf/Research.pdf; rm -r docs/latex


    #12. Delete pycache
    rm -rf "$1"/__pycache__

    #13. Open html
    open docs/html/index.html
    }




# Add another folder to previous scripts.
# Usage: spallf2 Another_folder
function spallf2 () {
    sphinx-apidoc -o docs/rst "$1"
    echo "" >> docs/rst/index.rst
    echo "" >> docs/rst/index.rst
    cat docs/rst/modules.rst >> docs/rst/index.rst
    rm -rf docs/rst/modules.rst
    awk -v n=25 -v s="sys.path.append('../$1')" 'NR == n {print s} {print}' docs/rst/conf.py > docs/rst/conf_new.py
    cp docs/rst/conf_new.py docs/rst/tmp.py
    rm -rf docs/rst/conf.py; mv docs/rst/conf_new.py docs/rst/conf.py
    cd docs; make clean; cd -
    cd docs; sphinx-build -b html rst html; cd -
    rm -rf "$1"/__pycache__
    open docs/html/index.html
     }

edit_sphinx_conf.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File        : ~/Applications/edit_sphinx_conf.py
# Author      : Bhishan Poudel, Physics PhD Student, Ohio University
# Date        : Jul 04, 2017 Tue
# Ref:
# http://www.sphinx-doc.org/en/stable/theming.html
#
# Imports
import time
import os
import subprocess

def edit_sphinx_conf_py():
    """Edit sphinx conf.py file."""

    html_theme_options = """html_theme_options = { 'linkcolor': '#808000',
        'collapsiblesidebar': True, 
        'sidebarbgcolor': 'fuchia', 
        'sidebartextcolor': 'teal', 
        'sidebarlinkcolor': 'gray', 
        'relbarbgcolor': '#5D6D7E', 
        'externalrefs': True
        }
    """

    conf, conf2 = 'docs/source/conf.py', 'docs/source/conf2.py'
    if os.path.isfile(conf): subprocess.call('mv %s %s '% (conf, conf2), shell=True)
    with open(conf2, 'r') as f, open(conf,'w') as fo:
        for line in f.readlines():
            olds = [r'# import os', 
                    r'# import sys',
                    r"# sys.path.insert(0, os.path.abspath('.'))",
                    r"html_theme = 'alabaster'"]
            news = [r'import os', 
                    r'import sys',
                    r"sys.path.insert(0, os.path.abspath('.'))",
                    r"html_theme = 'classic'",
                    html_theme_options,
                    r"html_style = 'custom.css'"]

            # os
            if olds[0] in line:
                print(line.replace(line, news[0]), file=fo, end='\n')

            # sys
            elif olds[1] in line:
                print(line.replace(line, news[1]), file=fo, end='\n')

            # path
            elif olds[2] in line:
                print(line.lstrip('#').lstrip(' '), file=fo, end='\n')

            # theme
            elif olds[3] in line:
                print(line.replace(line, news[3]), file=fo)
                print(news[4], file=fo)
                print(news[5], file=fo)

            # Other lines
            else:
                print(line, file=fo, end='')
    os.remove(conf2)
    print('Editing file: ', conf)

if __name__ == '__main__':
    edit_sphinx_conf_py()

<强> custom.css 文件:〜/ Applications / custom.css

@import url("classic.css");


div.admonition-todo {
    border-top: 2px solid red;
    border-bottom: 2px solid red;
    border-left: 2px solid red;
    border-right: 2px solid red;
    background-color: #ff6347
}

div.admonition-info {
    border-top: 2px solid green;
    border-bottom: 2px solid green;
    border-left: 2px solid green;
    border-right: 2px solid green;
    background-color: #63cc47
}

div.admonition-readme {
    border-top: 2px solid red;
    border-bottom: 2px solid red;
    border-left: 2px solid red;
    border-right: 2px solid red;
    background-color: #F08080
}

Geany filetypes.restructuredtext Geany&gt;工具&gt;配置文件&gt;文件类型配置&gt;标记语言&gt; filetypes.restructuredtext

# Author    : Bhishan Poudel
# Date      : Jul 06, 2017 Thu
# Version   : 1.0
# File: ~/.config/geany/filedefs/filetypes.restructuredtext

[styling]
function=type
variable=keyword_1,bold
label=string
userdefined=keyword_1,bold


[keywords]
functions=toctree automodulue contents automodule
variables=depth maxdepth  
lables=note warning todo seealso
userdefined=

[lexer_properties]
nsis.uservars=1
nsis.ignorecase=0


[settings]
# default extension used when saving files
extension=rst

# single comments, like # in this file
comment_single=..\s
comment_use_indent=true
lexer_filetype=NSIS


[build-menu]
EX_00_LB=Execute
EX_00_CM=cd ../ ; make clean; sphinx-build -b html rst html && xdg-open html/index.html
EX_00_WD=
FT_00_LB=Compile
FT_00_CM=pandoc -o %e.pdf %f && xdg-open %e.pdf
FT_00_WD=
EX_03_LB=
EX_03_CM=
EX_03_WD=
FT_01_LB=Build
FT_01_CM=
FT_01_WD=

Geany snippets.conf

##***********************************************************************
##=======================================================================
##         reStructuredText (reST)
##=======================================================================
##***********************************************************************
[reStructuredText]
# https://www.youtube.com/watch?v=L-fXOoxrt0M
hdr=.. contents:: Table of Contents\n   :depth: 3\n\n
contents=.. contents:: Table of Contents\n   :depth: 3\n\n
toc=.. toctree::\n   :maxdepth: 4\n\n   %cursor%
h=%cursor%\n################################################################################\n\n
h2=%cursor%\n********************************************************************************\n\n
h3=%cursor%\n================================================================================\n\n
h4=%cursor%\n--------------------------------------------------------------------------------\n\n
h5=%cursor%\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n
h6=%cursor%\n""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""\n\n
img=.. image:: ../images/%cursor%.png\n   :height: 100px\n   :width: 400 px\n   :align: center\n
fig=\n.. figure:: ../images/a.png\n    :width: 200px\n    :align: center\n    :height: 100px\n    :alt: alternate text\n    :figclass: align-center\n\n    This is caption.\n
footnote=[#f1]_  \n\n.. rubric:: Footnotes\n\n.. [#f1] Text of the first footnote.\n\n
cite=[book]_ \n\n.. [book] Name of book
link=`Link text <%cursor%>`_
link2=`a link`_.\n\n.. _a link: %cursor%\n\n
table=\n\n=====  =====  =======\nA      B      A and B\n=====  =====  =======\nF      F      F\nT      F      F\nF      T      F\nT      T      T\n=====  =====  =======\n\n
table2=\n\n+------------------------+------------+----------+----------+\n| Header1                | Header 2   | Header 3 | Header 4 |\n+========================+============+==========+==========+\n| ..                     | 12         |   13     | 14       |\n+------------------------+------------+----------+----------+\n| 21                     | 22         | 23       |       24 |\n+------------------------+------------+----------+----------+\n\n
ss=|H2O|\n\n.. |H2O| replace:: H\ :sub:`2`\ O\n
superscript=|H2O|\n\n.. |H2O| replace:: H\ :sub:`2`\ O\n
code=::\n\n    This is code.
i=\n    %cursor%
# new line
nl=\n| %cursor%\n| %cursor%
doctest=>>> print 'this is a Doctest block'\nthis is a Doctest block
hlist=.. hlist::\n   :columns: 3\n\n   * A list of\n   * short items\n   * that should be\n   * displayed\n   * horizontally\n\n
note=.. note::\n\n   %cursor%.
seealso=.. seealso::\n\n   %cursor%.
seealso2=.. seealso::\n   Module :py:mod:`zipfile`\n      Documentation of the :py:mod:`zipfile` standard module.\n\n   `GNU tar manual, Basic Tar Format <http://link>`_\n      Documentation for tar archive files, including GNU tar extensions.\n
warning=.. warning::\n\n   Write complete sentence.
todo=.. admonition:: todo\n\n   %cursor%
info=.. admonition:: Info\n\n   %cursor%
info=.. admonition:: Readme\n\n   %cursor%
code=.. code-block:: c\n\n    printf("hi there");\n
math=\n:math:`\alpha > \beta`
math2=.. math::\n\n    n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k\n
topic=.. topic:: Topic\n\n    Indented text is the body.
sidebar=.. sidebar:: Sidebar\n\n   Body.
i=\n\n    %cursor%
test=.. testcode::\n\n    print("hi")\n\n.. testoutput::\n\n    hi\n
class=:class:`~fibonacci_doctest` 
meth=:meth:`~fibonacci_doctest.fib`
paired_index=..  index::\npair: poetry; bad # gives bad>poetry and poetry>bad.
single_index=..  index::\nsingle: Pythagoras # gives bad>poetry and poetry>bad.

Geany构建命令

Open Geany text editor
open index.rst
Tools > Build > Set Build Commands > Execute >
cd ../; make clean; sphinx-build -b html rst html && open html/index.html
# For ubuntu use xdg-open instead of open

<强>用法

pwd: Location of Scripts
spallf Scripts
Add another folder: spallf2 Scripts2 

<强>注意事项
sphinx可能在python2中运行不好,对我来说它只适用于anaconda3版本。标准python2和python3都无法运行带有TemplatesNotFound错误的命令make html命令。

要运行多个版本的python,请将anaconda3的PATH放在底部 .bash_profile.bashrc然后sphinx会运行良好。

另外,顺便说一下程序PHOSIM需要python2并运行phosim put .bash_profile底部的python2 PATH行。

那就是它!现在用狮身人面像很好,很容易记录。
当然,我应该学习rST,这将有助于我的文档看起来更好。