Я следую учебному пособию по Sphinx для проекта Python и, похоже, не могу получить автоматически созданный HTML-файл для добавления в функцию doc-строки.
Я следовал инструкциям на начальном сайте Руководство по началу работы с Sphinx и успешно создал HTML-код, содержащий основы (в основном пустые).
Вот как устроен мой тестовый проект:
- /sphinx-test/
-- doc/
-- sphinx-test/
--- __init__.py
--- api.py
__init__.py
пусто, а api.py
содержит одну функцию:
def square_num(num):
"""Example function
Args:
num (float): A float to square.
Returns:
float: The squared number
"""
return num**2
Я перешел в каталог doc/
и запустил $sphinx-quickstart
.
Вот как я ответил на $sphinx-quickstart
вопросов:
> Root path for the documentation [.]:
> Separate source and build directories (y/n) [n]: y
> Name prefix for templates and static dir [_]:
> Project name: sphinx_test
> Author name(s): nick
> Project version: 0.0.1
> Project release [0.0.1]:
> 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]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> intersphinx: link between Sphinx documentation of different projects (y/n) [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]: y
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]: n
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: n
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: y
> 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]: n
> Create Makefile? (y/n) [y]: y
> Create Windows command file? (y/n) [y]: n
Я сделал одно изменение в файле сборки conf.py
, чтобы Sphinx мог перемещаться вверх по одному каталогу к проекту. Вот соответствующие строки в conf.py
:
# -*- coding: utf-8 -*-
import os
import sys
sys.path.insert(0, os.path.abspath('../'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinx_test'
copyright = u'2019, foobar'
author = u'foobar'
version = u'0.0.1'
release = u'0.0.1'
language = None
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
pygments_style = 'sphinx'
todo_include_todos = True
html_theme = 'alabaster'
html_static_path = ['_static']
htmlhelp_basename = 'sphinx_testdoc'
latex_elements = {
}
latex_documents = [
(master_doc, 'sphinx_test.tex', u'sphinx\\_test Documentation',
u'foobar', 'manual'),
]
man_pages = [
(master_doc, 'sphinx_test', u'sphinx_test Documentation',
[author], 1)
]
texinfo_documents = [
(master_doc, 'sphinx_test', u'sphinx_test Documentation',
author, 'sphinx_test', 'One line description of project.',
'Miscellaneous'),
]
Я тогда побежал $make html
.
Это сгенерировало файл index.html
, как и ожидалось, но он не содержит никакой информации в моей square_num()
строке документации. Я не редактировал другие файлы sphinx-quickstart
по умолчанию.
Что я должен сделать, чтобы получить строки документации в документации?
EDIT:
Это не совсем дубликат
Как сгенерировать документацию Python с использованием Sphinx с нулевой конфигурацией?
Конкретные решения в этом вопросе не сработали. В строке 3 conf.py
я уже реализовал это решение, добавив строку: sys.path.insert(0, os.path.abspath('../'))
. Хотя проблема была та же, решения были немного другими.
Решение, которое я нашел, было после этой строки:
sys.path.append(os.path.join(os.path.dirname(__name__), '..'))
(см. Ответ)