Autodoc Python Sphinx не отображается в readthedocs
У меня есть пакет Python spike2py, размещенный на Github . Я подготовил свои документы, используя файлы Sphinx и .rst. Эти файлы размещены на GitHub здесь . Я могу успешно работать make html
локально и получать желаемый результат. То есть часть документации Справочное руководство содержит API, автоматически сгенерированный с использованием строки документации, которую я включил в свой код, и на которую ссылаются с помощью вызовов autoclass
и autofunction
( reference_guide.rst ).
Например, вот как выглядит первая часть Справочного руководства, когда я визуализирую ее локально:

Однако, когда документация отображается readthedocs
( см. Здесь ), Справочное руководство не содержит извлеченных строк доктрин; только заголовки, найденные в файле .rst.
Ожидаемое поведение
Я ожидал, что документы, отображаемые в readthedocs, будут такими же, как и документы, отображаемые локально. Однако этого не происходит.
Посмотрев здесь , я подтвердил, что версия, представленная в readthedocs в текущей версии моей документации.
Но когда я пытаюсь загрузить версии документации в формате PDF или HTML, Справочное руководство не включает строки документации.
Дополнительная информация
Согласно документации readthedocs , локальные сборки не следует отправлять на GitHub; только исходные файлы.
Это отчасти связано с этой проблемой , но мне не удалось заставить предлагаемое решение работать.
ОБНОВЛЕНИЕ Я последовал решению, рекомендованному Стивом Пирси, и это решило часть проблемы. Я добавил docs/requirements.txt
файл, а также .readthedocs.yml
файл.
Затем я заметил, что сборка использует Python 3.7.9. Учитывая, что я использовал подсказки типа из Python> = 3.8, мне пришлось указать версию Python в .readthedocs.yml
файле.
Затем я застрял в сборке RTD, говоря мне, что не может найти мой файл index.rst.
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/cmd/build.py", line 280, in build_main
app.build(args.force_all, filenames)
File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/application.py", line 348, in build
self.builder.build_update()
File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 297, in build_update
self.build(to_build,
File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 311, in build
updated_docnames = set(self.read())
File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 421, in read
raise SphinxError('master file %s not found' %
sphinx.errors.SphinxError: master file /home/docs/checkouts/readthedocs.org/user_builds/spike2py/checkouts/latest/docs/index.rst not found
Sphinx error:
master file /home/docs/checkouts/readthedocs.org/user_builds/spike2py/checkouts/latest/docs/index.rst not found
Но затем я решил это, указав в моем следующее .readthedocs.yml
:
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/source/conf.py
После этого исправления документы создаются без ошибок и включают следующее:
generating indices... genindex py-modindexdone
highlighting module code... [ 20%] spike2py.channels
highlighting module code... [ 40%] spike2py.plot
highlighting module code... [ 60%] spike2py.read
highlighting module code... [ 80%] spike2py.sig_proc
highlighting module code... [100%] spike2py.trial
И да, доктрины появились на RTD.
Ответы
Зависимости вашего проекта не указаны в RTD, но вы установили зависимости локально. Вы можете проверить это в журнале сборки . Посетите Сборки своего проекта, щелкните сборку и нажмите «просмотреть необработанные».
WARNING: autodoc: failed to import class 'trial.TrialInfo' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'trial.Trial' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import function 'trial.load' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'channels.ChannelInfo' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'channels.Channel' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'channels.Event' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'channels.Keyboard' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'channels.Waveform' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'channels.Wavemark' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import class 'sig_proc.SignalProcessing' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import function 'plot.plot_channel' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import function 'plot.plot_trial' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
WARNING: autodoc: failed to import function 'read.read' from module 'spike2py'; the following exception was raised:
cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py)
Чтобы исправить ситуацию, вы должны указать, что зависимости вашего проекта должны быть установлены. См. Указание зависимостей .
Вы должны либо:
- Создайте файл требований к пипу, в котором указаны требования , или
- Создайте файл, определяющий
pip install
параметр, который будет устанавливать требования, уже определенные в другом месте, например, вsetup.py
docs_requires
строфе. См. Пример в репозитории Pyramid с его rtd.txt и setup.py .
rtd.txt
-e .[docs]
setup.py
docs_extras = [
'Sphinx >= 3.0.0', # Force RTD to use >= 3.0.0
'docutils',
'pylons-sphinx-themes >= 1.0.8', # Ethical Ads
'pylons_sphinx_latesturl',
'repoze.sphinx.autointerface',
'sphinxcontrib-autoprogram',
]
# ...
extras_require={'testing': testing_extras, 'docs': docs_extras},
После того, как вы определили требования к проекту в этом файле, вы должны настроить Read the Docs для распознавания этого файла для установки зависимостей. Предпочтительный метод - использовать файл конфигурации , но вы также можете сделать это через панель администратора проекта .
У меня была точно такая же проблема. Readthedocs не смог извлечь строки документации из моего проекта, потому что не нашел мой модуль проекта.
Я решил это, добавив 2 относительных пути в docs / conf.py:
sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath("../"))
Итак, теперь верхняя часть docs / conf.py выглядит следующим образом:
import os
import sys
import sphinx_rtd_theme
# 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("."))
sys.path.insert(0, os.path.abspath("../"))
sys.path.insert(1, os.path.dirname(os.path.abspath("../")) + os.sep + "feature_engine")