Search code examples
pythonwindows-10python-sphinx

Sphinx can't find the root module of my project


I have this sample project to learn how Sphinx works.

Directory structure is looking like this:

.
+--app
|  +--api
|     +--endpoints
|        +--address.py
|
|--docs
|  +--conf.py
|  +--index.rst
|  +--source
|     +--modules.rst
|     +--address.rst

I've added the relevant filepaths to my path in conf.py, as follows:

import os
import sys
from pathlib import Path

project_root = Path(os.getcwd()).parent.absolute()
sys.path.insert(0, project_root)

path_app = os.path.join(project_root, "app")
sys.path.insert(0, path_app)

path_address = os.path.join(project_root, "app", "api", "endpoints")
sys.path.insert(0, path_address)

I have my ./docs/index.rst file, autogenerated by Sphinx:

.. Sky-Payment documentation master file, created by
   sphinx-quickstart on Fri Apr 16 17:23:31 2021.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Sky-Payment's documentation!
=======================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:



Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Then I have my docs/source/modules.rst file:

app
===

.. toctree::
   :maxdepth: 4

   address

and my docs/source/address.rst file:

address module
==============

.. automodule:: app.api.endpoints.address
   :members:
   :undoc-members:
   :show-inheritance:

when I run sphinx-build.exe -b html . .\_build from .\docs, I get this error:

WARNING: autodoc: failed to import module 'api.endpoints.address' from
module 'app'; the following exception was raised: No module named
'app'

What am I doing wrong here?


Solution

  • In your conf.py, put sys.path.insert(0, ".."). The ../ relative path navigates to the parent directory. Since conf.py is located in docs/, the parent directory of docs/ is the root of your project. This way, sphinx will be able to access your project files and it will be able to import your modules.