Поиск по блогу

четверг, 26 июня 2014 г.

Устанавливаем в Kali "sphinx-bootstrap-theme"

Меня заинтересовала тема "sphinx-bootstrap-theme" ... я нашел несколько дистрибутивов на GitHub, но понравившийся мне предлагал установку только под Linux. Я не уверен в себе, потому хочу учится на "правильных примерах". Потому здесь установил Sphinx и тему ... и распечатал структуру папок и conf.py для Spinx "/usr/local/lib/python2.7/dist-packages/sphinx/config.py"... а потом записал весь процесс успешной установки в Debian
sphinx-bootstrap-theme 0.4.0 - устанавливал "отсюда"
Sphinx theme adapted from Twitter's Bootstrap - идеологически неправильная сборка
A small introduction to Python Eggs

Сначала устанавливаем Sphinx

In []:
root@kali:/home/kiss# pip install sphinx
Downloading/unpacking sphinx
  Downloading Sphinx-1.2.2.tar.gz (3.1Mb): 3.1Mb downloaded
  Running setup.py egg_info for package sphinx
    
    no previously-included directories found matching 'doc/_build'
Requirement already satisfied (use --upgrade to upgrade): Pygments>=1.2 in /usr/lib/python2.7/dist-packages (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): docutils>=0.7 in /usr/lib/pymodules/python2.7 (from sphinx)
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.3 in /usr/lib/python2.7/dist-packages (from sphinx)
Installing collected packages: sphinx
  Running setup.py install for sphinx
    
    no previously-included directories found matching 'doc/_build'
    Installing sphinx-apidoc script to /usr/local/bin
    Installing sphinx-build script to /usr/local/bin
    Installing sphinx-quickstart script to /usr/local/bin
    Installing sphinx-autogen script to /usr/local/bin
Successfully installed sphinx
Cleaning up...

Тему sphinx_bootstrap_theme тоже устанавливаем пипом

In []:
root@kali:/home/kiss# pip install sphinx_bootstrap_theme
Downloading/unpacking sphinx-bootstrap-theme
  Downloading sphinx-bootstrap-theme-0.4.0.tar.gz (922Kb): 922Kb downloaded
  Running setup.py egg_info for package sphinx-bootstrap-theme
    
    warning: no previously-included files matching '*' found under directory 'bootstrap'
    warning: no previously-included files matching '.DS_Store' found anywhere in distribution
    warning: no previously-included files found matching 'bootstrap'
    warning: no previously-included files found matching 'demo'
    warning: no previously-included files found matching 'fabfile.py'
Requirement already satisfied (use --upgrade to upgrade): distribute in /usr/lib/python2.7/dist-packages (from sphinx-bootstrap-theme)
Installing collected packages: sphinx-bootstrap-theme
  Running setup.py install for sphinx-bootstrap-theme
    
    warning: no previously-included files matching '*' found under directory 'bootstrap'
    warning: no previously-included files matching '.DS_Store' found anywhere in distribution
    warning: no previously-included files found matching 'bootstrap'
    warning: no previously-included files found matching 'demo'
    warning: no previously-included files found matching 'fabfile.py'
Successfully installed sphinx-bootstrap-theme
Cleaning up...
root@kali:/home/kiss# 

В Windows я до сих пор не нашел sphinx-build, а здесь вот он... И другие файлы нашлись тоже...

In [1]:
!ls /usr/local/bin
ipcluster     ipcontroller2  iptest   ipython2       sphinx-build

ipcluster2    ipengine      iptest2  sphinx-apidoc   sphinx-quickstart

ipcontroller  ipengine2      ipython  sphinx-autogen  xsser


In [3]:
ls /usr/local/lib/python2.7/dist-packages
backports/

backports.ssl_match_hostname-3.4.0.2.egg-info/

IPython/

ipython-2.1.0.egg-info/

sphinx/

Sphinx-1.2.2.egg-info/

sphinx_bootstrap_theme/

sphinx_bootstrap_theme-0.4.0.egg-info/

tornado/

tornado-3.2.1.egg-info/

XSSer/

xsser-1.6.egg-info/


Последнее время работал в Windows и "отвык" от Linux. Пришлось искать find -name "phinx" ...нашел директорию установки:
In [5]:
ls /usr/local/lib/python2.7/dist-packages/sphinx
addnodes.py      domains/          locale/              setup_command.pyc

addnodes.pyc     environment.py    make_mode.py         texinputs/

apidoc.py        environment.pyc   make_mode.pyc        themes/

apidoc.pyc       errors.py         pycode/              theming.py

application.py   errors.pyc        pygments_styles.py   theming.pyc

application.pyc  ext/              pygments_styles.pyc  transforms.py

builders/        highlighting.py   quickstart.py        transforms.pyc

cmdline.py       highlighting.pyc  quickstart.pyc       util/

cmdline.pyc      __init__.py       roles.py             versioning.py

config.py        __init__.pyc      roles.pyc            versioning.pyc

config.pyc       jinja2glue.py     search/              websupport/

directives/      jinja2glue.pyc    setup_command.py     writers/


Очевидно, что есть отличия от Windows, там, например, пакеты размещаются не в dist-packages,а в lib/site-pkg (если не ошибаюсь)
И, как мне и хотелось, здесь тема sphinx_bootstrap_theme не добавляется к предустановленным темам, а размещается в папке dist-packages (рядом с папкой Sphinx). В списке ссылок в начале поста у меня есть пример идеологически неправильной сборки - там автор запихивает sphinx_bootstrap_theme в папку с дефолтными темами dist-packages/sphinx/themes
Посмотрим конфигурационные файлы, там должен быть добавлвен путь к теме (она же кастомная)... Сначала в папке sphinx:
In [6]:
%load "/usr/local/lib/python2.7/dist-packages/sphinx/config.py"
In []:
"""
    sphinx.config
    ~~~~~~~~~~~~~

    Build configuration file handling.

    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import os
import re
import sys
from os import path

from sphinx.errors import ConfigError
from sphinx.locale import l_
from sphinx.util.osutil import make_filename
from sphinx.util.pycompat import bytes, b, execfile_

nonascii_re = re.compile(b(r'[\x80-\xff]'))

CONFIG_SYNTAX_ERROR = "There is a syntax error in your configuration file: %s"
if sys.version_info >= (3, 0):
    CONFIG_SYNTAX_ERROR += "\nDid you change the syntax from 2.x to 3.x?"

class Config(object):
    """
    Configuration file abstraction.
    """

    # the values are: (default, what needs to be rebuilt if changed)

    # If you add a value here, don't forget to include it in the
    # quickstart.py file template as well as in the docs!

    config_values = dict(
        # general options
        project = ('Python', 'env'),
        copyright = ('', 'html'),
        version = ('', 'env'),
        release = ('', 'env'),
        today = ('', 'env'),
        today_fmt = (None, 'env'),  # the real default is locale-dependent

        language = (None, 'env'),
        locale_dirs = ([], 'env'),

        master_doc = ('contents', 'env'),
        source_suffix = ('.rst', 'env'),
        source_encoding = ('utf-8-sig', 'env'),
        exclude_patterns = ([], 'env'),
        # the next three are all deprecated now
        unused_docs = ([], 'env'),
        exclude_trees = ([], 'env'),
        exclude_dirnames = ([], 'env'),
        default_role = (None, 'env'),
        add_function_parentheses = (True, 'env'),
        add_module_names = (True, 'env'),
        trim_footnote_reference_space = (False, 'env'),
        show_authors = (False, 'env'),
        pygments_style = (None, 'html'),
        highlight_language = ('python', 'env'),
        templates_path = ([], 'html'),
        template_bridge = (None, 'html'),
        keep_warnings = (False, 'env'),
        modindex_common_prefix = ([], 'html'),
        rst_epilog = (None, 'env'),
        rst_prolog = (None, 'env'),
        trim_doctest_flags = (True, 'env'),
        primary_domain = ('py', 'env'),
        needs_sphinx = (None, None),
        nitpicky = (False, 'env'),
        nitpick_ignore = ([], 'html'),

        # HTML options
        html_theme = ('default', 'html'),
        html_theme_path = ([], 'html'),
        html_theme_options = ({}, 'html'),
        html_title = (lambda self: l_('%s %s documentation') %
                                   (self.project, self.release),
                      'html'),
        html_short_title = (lambda self: self.html_title, 'html'),
        html_style = (None, 'html'),
        html_logo = (None, 'html'),
        html_favicon = (None, 'html'),
        html_static_path = ([], 'html'),
        html_extra_path = ([], 'html'),
        # the real default is locale-dependent
        html_last_updated_fmt = (None, 'html'),
        html_use_smartypants = (True, 'html'),
        html_translator_class = (None, 'html'),
        html_sidebars = ({}, 'html'),
        html_additional_pages = ({}, 'html'),
        html_use_modindex = (True, 'html'),  # deprecated
        html_domain_indices = (True, 'html'),
        html_add_permalinks = (u'\u00B6', 'html'),
        html_use_index = (True, 'html'),
        html_split_index = (False, 'html'),
        html_copy_source = (True, 'html'),
        html_show_sourcelink = (True, 'html'),
        html_use_opensearch = ('', 'html'),
        html_file_suffix = (None, 'html'),
        html_link_suffix = (None, 'html'),
        html_show_copyright = (True, 'html'),
        html_show_sphinx = (True, 'html'),
        html_context = ({}, 'html'),
        html_output_encoding = ('utf-8', 'html'),
        html_compact_lists = (True, 'html'),
        html_secnumber_suffix = ('. ', 'html'),
        html_search_language = (None, 'html'),
        html_search_options = ({}, 'html'),
        html_search_scorer = ('', None),

        # HTML help only options
        htmlhelp_basename = (lambda self: make_filename(self.project), None),

        # Qt help only options
        qthelp_basename = (lambda self: make_filename(self.project), None),

        # Devhelp only options
        devhelp_basename = (lambda self: make_filename(self.project), None),

        # Epub options
        epub_basename = (lambda self: make_filename(self.project), None),
        epub_theme = ('epub', 'html'),
        epub_theme_options = ({}, 'html'),
        epub_title = (lambda self: self.html_title, 'html'),
        epub_author = ('unknown', 'html'),
        epub_language = (lambda self: self.language or 'en', 'html'),
        epub_publisher = ('unknown', 'html'),
        epub_copyright = (lambda self: self.copyright, 'html'),
        epub_identifier = ('unknown', 'html'),
        epub_scheme = ('unknown', 'html'),
        epub_uid = ('unknown', 'env'),
        epub_cover = ((), 'env'),
        epub_guide = ((), 'env'),
        epub_pre_files = ([], 'env'),
        epub_post_files = ([], 'env'),
        epub_exclude_files = ([], 'env'),
        epub_tocdepth = (3, 'env'),
        epub_tocdup = (True, 'env'),
        epub_tocscope = ('default', 'env'),
        epub_fix_images = (False, 'env'),
        epub_max_image_width = (0, 'env'),
        epub_show_urls = ('inline', 'html'),
        epub_use_index = (lambda self: self.html_use_index, 'html'),

        # LaTeX options
        latex_documents = (lambda self: [(self.master_doc,
                                          make_filename(self.project) + '.tex',
                                          self.project,
                                          '', 'manual')],
                           None),
        latex_logo = (None, None),
        latex_appendices = ([], None),
        latex_use_parts = (False, None),
        latex_use_modindex = (True, None),  # deprecated
        latex_domain_indices = (True, None),
        latex_show_urls = ('no', None),
        latex_show_pagerefs = (False, None),
        # paper_size and font_size are still separate values
        # so that you can give them easily on the command line
        latex_paper_size = ('letter', None),
        latex_font_size = ('10pt', None),
        latex_elements = ({}, None),
        latex_additional_files = ([], None),
        latex_docclass = ({}, None),
        # now deprecated - use latex_elements
        latex_preamble = ('', None),

        # text options
        text_sectionchars = ('*=-~"+`', 'env'),
        text_newlines = ('unix', 'env'),

        # manpage options
        man_pages = (lambda self: [(self.master_doc,
                                    make_filename(self.project).lower(),
                                    '%s %s' % (self.project, self.release),
                                    [], 1)],
                     None),
        man_show_urls = (False, None),

        # Texinfo options
        texinfo_documents = (lambda self: [(self.master_doc,
                                            make_filename(self.project).lower(),
                                            self.project, '',
                                            make_filename(self.project),
                                            'The %s reference manual.' %
                                            make_filename(self.project),
                                            'Python')],
                             None),
        texinfo_appendices = ([], None),
        texinfo_elements = ({}, None),
        texinfo_domain_indices = (True, None),
        texinfo_show_urls = ('footnote', None),
        texinfo_no_detailmenu = (False, None),

        # linkcheck options
        linkcheck_ignore = ([], None),
        linkcheck_timeout = (None, None),
        linkcheck_workers = (5, None),
        linkcheck_anchors = (True, None),

        # gettext options
        gettext_compact = (True, 'gettext'),

        # XML options
        xml_pretty = (True, 'env'),
    )

    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if "extensions" in overrides:
            config["extensions"] = overrides["extensions"]
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            olddir = os.getcwd()
            try:
                # we promise to have the config dir as current dir while the
                # config file is executed
                os.chdir(dirname)
                try:
                    execfile_(filename, config)
                except SyntaxError, err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
            finally:
                os.chdir(olddir)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)
        self.extensions = config.get('extensions', [])

    def check_unicode(self, warn):
        # check all string values for non-ASCII characters in bytestrings,
        # since that can result in UnicodeErrors all over the place
        for name, value in self._raw_config.iteritems():
            if isinstance(value, bytes) and nonascii_re.search(value):
                warn('the config value %r is set to a string with non-ASCII '
                     'characters; this can lead to Unicode errors occurring. '
                     'Please use Unicode strings, e.g. %r.' % (name, u'Content')
                )

    def init_values(self):
        config = self._raw_config
        for valname, value in self.overrides.iteritems():
            if '.' in valname:
                realvalname, key = valname.split('.', 1)
                config.setdefault(realvalname, {})[key] = value
            else:
                config[valname] = value
        for name in config:
            if name in self.values:
                self.__dict__[name] = config[name]
        del self._raw_config

    def __getattr__(self, name):
        if name.startswith('_'):
            raise AttributeError(name)
        if name not in self.values:
            raise AttributeError('No such config value: %s' % name)
        default = self.values[name][0]
        if hasattr(default, '__call__'):
            return default(self)
        return default

    def __getitem__(self, name):
        return getattr(self, name)

    def __setitem__(self, name, value):
        setattr(self, name, value)

    def __delitem__(self, name):
        delattr(self, name)

    def __contains__(self, name):
        return name in self.values
Да, есть опции, которые относятся к теме, вот я их скопировал отдельно:
In []:
...
# HTML options
        html_theme = ('default', 'html'),
        html_theme_path = ([], 'html'),
        html_theme_options = ({}, 'html'),
...
Но в Windows конфигурационный файл с таким же именем формировался и в папке (каждого) проекта. А нам что мешает создать проект? Только сомнения по поводу того, где его размещать. С одной стороны, привык к папке www (проавила для LAMP), с другой стороны (не помню, где) прочитал, что в Python нет соглашения о структуре папок для размещения сайта... Забабахаю ка папку на рабочий стол.
In []:
#Создааем подпапку
kiss@kali:~/Desktop/www/sphinx/test$
In []:
#В директории sphinx находим quickstart.py и пытаемся его запустить:
kiss@kali:/usr/local/lib/python2.7/dist-packages/sphinx$ python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 17, in <module>
    from docutils.utils import column_width
  File "/usr/lib/pymodules/python2.7/docutils/utils.py", line 18, in <module>
    from docutils.error_reporting import ErrorOutput, SafeString
  File "/usr/lib/pymodules/python2.7/docutils/error_reporting.py", line 47, in <module>
    locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
AttributeError: 'module' object has no attribute 'getlocale'
Очевидно, в Kali не высталвен параметр locale. проверим, так ли это
In [1]:
!locale
LANG=en_GB.utf8

LANGUAGE=

LC_CTYPE="en_GB.utf8"

LC_NUMERIC="en_GB.utf8"

LC_TIME="en_GB.utf8"

LC_COLLATE="en_GB.utf8"

LC_MONETARY="en_GB.utf8"

LC_MESSAGES="en_GB.utf8"

LC_PAPER="en_GB.utf8"

LC_NAME="en_GB.utf8"

LC_ADDRESS="en_GB.utf8"

LC_TELEPHONE="en_GB.utf8"

LC_MEASUREMENT="en_GB.utf8"

LC_IDENTIFICATION="en_GB.utf8"

LC_ALL=


Я грубо ошибся. В Linux есть папка для скриптов " /usr/local/bin" (она была распечатана выше), скрипты из этой папки можно запустить из любой директории (как я запускаю ipython...). Обратим на нее внимание еще раз:
In [2]:
!ls /usr/local/bin
ipcluster     ipcontroller2  iptest   ipython2       sphinx-build

ipcluster2    ipengine      iptest2  sphinx-apidoc   sphinx-quickstart

ipcontroller  ipengine2      ipython  sphinx-autogen  xsser


Итак, оказалось, что я просто запустил не тот файл. Надо было прямо из папки создаваемого проекта:
In []:
kiss@kali:~/Desktop/www/sphinx/test$ sphinx-quickstart
Welcome to the Sphinx 1.2.2 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]: y

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: for_bootstrap
> Author name(s): Sergey

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: 1.0.0
> Project release [1.0.0]: 

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]: 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]: y
> 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]: y
> coverage: checks for documentation coverage (y/n) [n]: 
> pngmath: include math, rendered as PNG 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

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]: n

Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.

Finished: An initial directory structure has been created.

You should now populate your master file ./source/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.

kiss@kali:~/Desktop/www/sphinx/test$ 

Вот эти папки созданы, а них свежий conf.py проекта (сайта)

In [4]:
!ls ~/Desktop/www/sphinx/test
build  Makefile  source


Здесь две папки и Makefile - если его запустить, то в build будут сгенерированы файлы .html ...естественно из сырцов (.rst) в папке source.
In [5]:
!ls ~/Desktop/www/sphinx/test/source
conf.py  index.rst  _static  _templates


In []:
В папке _static - файлы картинок, стилей, джава-скриптов, а в _templates 
In [6]:
%load ~/Desktop/www/sphinx/test/source/conf.py
In []:
#
# for_bootstrap documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 24 15:16:20 2014.
#
# 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.

import sys
import os

# 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.
#sys.path.insert(0, os.path.abspath('.'))

# -- 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.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.viewcode',
]

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

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'for_bootstrap'
copyright = u'2014, Sergey'

# 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 = '1.0.0'
# The full version, including alpha/beta/rc tags.
release = '1.0.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

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

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

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

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = 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 = 'default'

# 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 themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# 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']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

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


# -- 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': '',
}

# 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 = [
  ('index', 'for_bootstrap.tex', u'for\\_bootstrap Documentation',
   u'Sergey', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True


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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'for_bootstrap', u'for_bootstrap Documentation',
     [u'Sergey'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False


# -- 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 = [
  ('index', 'for_bootstrap', u'for_bootstrap Documentation',
   u'Sergey', 'for_bootstrap', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

Теперь сразу попробуем установить тему Edit the "conf.py" configuration file to point to the bootstrap theme:

In []:
Но сначала проверим здесь, как установился модуль sphinx_bootstrap_theme
In [7]:
# At the top.
import sphinx_bootstrap_theme

# ...

# Activate the theme.
html_theme = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
In [8]:
html_theme_path
Out[8]:
['/usr/local/lib/python2.7/dist-packages/sphinx_bootstrap_theme']

Проверка прошла отлично, теперь нам нужно изменить три строчки в conf.py Но сначала убедимся, что дефолтные настройки работают. Просто выполним:

In []:
kiss@kali:~/Desktop/www/sphinx/test$ make html
sphinx-build -b html -d build/doctrees   source build/html
Making output directory...
Running Sphinx v1.2.2
loading pickled environment... not yet created
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                                                                
writing additional files... (0 module code pages) genindex search
copying static files... done
copying extra files... done
dumping search index... done
dumping object inventory... done
build succeeded.

Build finished. The HTML pages are in build/html.
Запустим в браузере file:///home/kiss/Desktop/www/sphinx/test/build/html/index.html Поверьте на слово, все работает (сайдбар слева, грязно-синий цвет...)
In []:
#Теперь добавим в /home/kiss/Desktop/www/sphinx/test/source/conf.py
html_theme = 'bootstrap' # Added by Sergey
...
# Закомментируем дефолтные строчки и вставим вместо них
...
html_theme = 'bootstrap' # Added by Sergey
...
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # Added by Sergey

Теперь попробуем обновить файлы

In []:
kiss@kali:~/Desktop/www/sphinx/test$ make clear
make: *** No rule to make target `clear'.  Stop.
kiss@kali:~/Desktop/www/sphinx/test$ make html
sphinx-build -b html -d build/doctrees   source build/html
Running Sphinx v1.2.2
loading pickled environment... done
building [html]: targets for 1 source files that are out of date
updating environment: 0 added, 0 changed, 0 removed
looking for now-outdated files... none found
preparing documents... done
writing output... [100%] index                                                                
writing additional files... (0 module code pages) genindex search
copying static files... done
copying extra files... done
dumping search index... done
dumping object inventory... done
build succeeded.

Build finished. The HTML pages are in build/html.

Тема мгновенно поменялась. Все, вроде бы..., работает. Отметим, что команда "make clear" не прошла так, как в Window...

Откуда я вообще взял "make html"? При создании проекта (Sphinx-quickstart) скрипт спросил, нужно ли генерировать makefile... и здесь же рассказал про "make html" Распечатаем Makefile
In [9]:
%load /home/kiss/Desktop/www/sphinx/test/Makefile
In []:
# Makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
PAPER         =
BUILDDIR      = build

# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source

.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext

help:
 @echo "Please use \`make <target>' where <target> is one of"
 @echo "  html       to make standalone HTML files"
 @echo "  dirhtml    to make HTML files named index.html in directories"
 @echo "  singlehtml to make a single large HTML file"
 @echo "  pickle     to make pickle files"
 @echo "  json       to make JSON files"
 @echo "  htmlhelp   to make HTML files and a HTML help project"
 @echo "  qthelp     to make HTML files and a qthelp project"
 @echo "  devhelp    to make HTML files and a Devhelp project"
 @echo "  epub       to make an epub"
 @echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
 @echo "  latexpdf   to make LaTeX files and run them through pdflatex"
 @echo "  latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
 @echo "  text       to make text files"
 @echo "  man        to make manual pages"
 @echo "  texinfo    to make Texinfo files"
 @echo "  info       to make Texinfo files and run them through makeinfo"
 @echo "  gettext    to make PO message catalogs"
 @echo "  changes    to make an overview of all changed/added/deprecated items"
 @echo "  xml        to make Docutils-native XML files"
 @echo "  pseudoxml  to make pseudoxml-XML files for display purposes"
 @echo "  linkcheck  to check all external links for integrity"
 @echo "  doctest    to run all doctests embedded in the documentation (if enabled)"

clean:
 rm -rf $(BUILDDIR)/*

html:
 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
 @echo
 @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

dirhtml:
 $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
 @echo
 @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

singlehtml:
 $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
 @echo
 @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."

pickle:
 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
 @echo
 @echo "Build finished; now you can process the pickle files."

json:
 $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
 @echo
 @echo "Build finished; now you can process the JSON files."

htmlhelp:
 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
 @echo
 @echo "Build finished; now you can run HTML Help Workshop with the" \
       ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
 $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
 @echo
 @echo "Build finished; now you can run "qcollectiongenerator" with the" \
       ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
 @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/for_bootstrap.qhcp"
 @echo "To view the help file:"
 @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/for_bootstrap.qhc"

devhelp:
 $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
 @echo
 @echo "Build finished."
 @echo "To view the help file:"
 @echo "# mkdir -p $$HOME/.local/share/devhelp/for_bootstrap"
 @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/for_bootstrap"
 @echo "# devhelp"

epub:
 $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
 @echo
 @echo "Build finished. The epub file is in $(BUILDDIR)/epub."

latex:
 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
 @echo
 @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
 @echo "Run \`make' in that directory to run these through (pdf)latex" \
       "(use \`make latexpdf' here to do that automatically)."

latexpdf:
 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
 @echo "Running LaTeX files through pdflatex..."
 $(MAKE) -C $(BUILDDIR)/latex all-pdf
 @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

latexpdfja:
 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
 @echo "Running LaTeX files through platex and dvipdfmx..."
 $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
 @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

text:
 $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
 @echo
 @echo "Build finished. The text files are in $(BUILDDIR)/text."

man:
 $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
 @echo
 @echo "Build finished. The manual pages are in $(BUILDDIR)/man."

texinfo:
 $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
 @echo
 @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
 @echo "Run \`make' in that directory to run these through makeinfo" \
       "(use \`make info' here to do that automatically)."

info:
 $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
 @echo "Running Texinfo files through makeinfo..."
 make -C $(BUILDDIR)/texinfo info
 @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."

gettext:
 $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
 @echo
 @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."

changes:
 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
 @echo
 @echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
 @echo
 @echo "Link check complete; look for any errors in the above output " \
       "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
 $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
 @echo "Testing of doctests in the sources finished, look at the " \
       "results in $(BUILDDIR)/doctest/output.txt."

xml:
 $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
 @echo
 @echo "Build finished. The XML files are in $(BUILDDIR)/xml."

pseudoxml:
 $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
 @echo
 @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."


Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий