我如何才能让Sphinx展示源代码?

2022-04-22 00:00:00 python python-sphinx documentation

问题描述

我正在使用Sphinx从文档字符串生成文档。

这是我用一些文档字符串编写的一个简单函数:

# myproject/src/foo.py

def my_func(arg1: int, arg2: int, arg3: str = "some_text") -> tuple[str, str, str]:
    """summary
    
    extended_summary
    
    :param int arg1: description
    :param int arg2: description
    :param str, optional arg3: description, defaults to "some_text"
    
    :return: [description]
    :rtype: tuple[str, str, str]
    """
    
    a, b, c = str(arg1), str(arg2), arg3
 
    return a, b, c
我在myproject/docssphinx-quickstart。然后我运行sphinx-apidoc --force -o ./docs/_modules ./src 然后将目录更改为docs并运行make html

这是我的一些conf.py

sys.path.insert(
    0, os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "src")
)
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.viewcode",
    "sphinx.ext.intersphinx",
    "sphinx.ext.autosummary",
]

autodoc_member_order = "bysource"

autodoc_default_options = {
    "members": True,
    "show-inheritance": True,
}
autosummary_generate = True

这将生成:

但是当我点击[Source]时,它没有显示代码。有什么问题?

由于这是一个大项目的一部分,因此有一些警告

Running Sphinx v4.4.0
.
.
.
* ModuleNotFoundError: No module named 'src'
.
.
.
WARNING: autodoc: failed to import module '....' from module '....'; the following exception was raised:
No module named 'src'
WARNING: autodoc: failed to import module '....' from module '....'; the following exception was raised:
No module named 'src'

WARNING: autodoc: failed to import module '.....' from module '....'; the following exception was raised:
No module named 'src'
looking for now-outdated files... none found
pickling environment... done
checking consistency... C:...docs\_modulesmodules.rst: **WARNING**: document isn't included in any toctree
done
preparing documents... done
writing output... [100%] index
generating indices... genindex py-modindex done
highlighting module code... [100%] xml_reader.xml_reader
writing additional pages... search done
copying static files... done
copying extra files... done
dumping search index in English (code: en)... done
dumping object inventory... done
build succeeded, 4 warnings.

The HTML pages are in _buildhtml.

项目结构如下:

myproject
   docs
       conf.py
   src
       foo.py
       package_1
            bar.py
            __init__.py
   venv

我尝试过的内容: 我将foo.py移到了Package_1目录。如果有的话,那就是奏效了。但在src中,即使我已将init.py添加到src

,也无法工作

解决方案

这解决了问题

更改

sys.path.insert(
    0, os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "src")
)

sys.path.insert(0, os.path.abspath('../'))

并将init.py添加到src

myproject
   docs
       conf.py
   src
       __init__.py
       foo.py
       package_1
            bar.py
            __init__.py
   venv

相关文章