AndyAO
V2EX  ›  问与答

为什么 Sphinx 找不到我的模块?它明明是可以导入的。

  •  3
     
  •   AndyAO · Aug 18, 2021 · 1611 views
    This topic created in 1910 days ago, the information mentioned may be changed or developed.

    我想利用 Sphinx 生成模块的文档,使用 sphinx-quickstart 初始化,在配置文件中,指定了extensions = ['sphinx.ext.autodoc'],并且在 index.rst 中指定模块 my_module_for_test:

    .. automodule:: my_module_for_test
       :members:
    

    进入根目录的 venv 虚拟环境,并运行 make 脚本或者sphinx-build -b html source build生成 html 文档,但是却报告找不到模块 my_module_for_test 。

    WARNING: autodoc: failed to import module 'my_module_for_test'; the following exception was raised:
    No module named 'my_module_for_test'
    

    在这里可以看到上述项目 project_for_autodoc - GitHub.

    这看起来像是环境出了问题,但是,在 source 目录下,运行位于 source 的 test_import.py 脚本,却可以成功导入 my_module_for_test

    这到底出了什么问题?我现在感到很困惑。

    7 replies  •  2021-08-18 18:06:53 +08:00
    ampedee
    ampedee
    Aug 18, 2021 via Android❤️1
    1
    之前写过一篇博客讲这个: https://www.waynerv.com/posts/use-sphinx-auto-generate-api-reference/


    > 为了获取文档字符串,Sphinx 需要能够导入文档所在的代码模块。也就是说,我们的源码模块必须位于 Sphinx 的导入层级结构中,这有许多种实现途径,本例选择在 conf.py 中将代码模块所在的目录(即 conf.py 文件所在的上一级目录)加入到 sys.path 中,在 conf.py 中加入以下代码:

    1 2 3 4 import os import sys sys.path.insert(0, os.path.abspath('..')
    FurN1
    FurN1
    Aug 18, 2021❤️1
    2
    把你这几行 https://github.com/Andy-AO/project_for_autodoc/blob/66668ed9ca8df1640aaec46647db3a3ac5521e05/source/conf.py#L13-L15

    首先取消注释,然后第 15 行改成
    sys.path.insert(0, os.path.abspath(".."))
    FurN1
    FurN1
    Aug 18, 2021
    3
    @ampedee 哇比我快几秒钟
    AndyAO
    AndyAO
    OP
    Aug 18, 2021
    4
    @IgniteWhite
    @ampedee

    谢谢两位,本来以为,已经用 venv 了,那么应该不需要手动添加。

    整个 Sphinx 文档上都没有直接介绍,还需要用 sys.path.insert 。

    现在看来相关的介绍居然在配置文件的注释当中,是我忽略了它。

    可是为什么 venv 对 conf.py 不起效,但对同目录的 test_import.py 却有效果呢?
    FurN1
    FurN1
    Aug 18, 2021❤️1
    5
    @AndyAO 它就是这样的,要明写,没研究过为啥

    sphinx 文档真的是难读,东一榔头西一棒子。你后面 autodoc 用一用可能遇到各种文档说的不清楚的问题,好多特性都只在超长的 changelog 里写,还有些 auto attribute 的功能甚至在我发 issue 前都没实现完全。

    我看了一下厉害的项目,其实 autodoc 的功能使用的很有限,都是在 docstring 里面自己写。不过有很多编辑器插件能自动在 docstring 的位置生成一个 doc 模版,还能定义文档是使用 numpy 风格还是 google 风格。
    FurN1
    FurN1
    Aug 18, 2021
    6
    我之前提的 autoattribute 这个 issue 已经修好了,如果有需求可以参考:
    https://github.com/sphinx-doc/sphinx/issues/9283
    AndyAO
    AndyAO
    OP
    Aug 18, 2021
    7
    @IgniteWhite

    目前将 Sphinx 的 PDF 文档,以及 Docutils 的 HTML 文档,全部都下载到本地了,这样的可以全文搜索。

    搜索引擎不太好用,有符号的时候经常就找不到想要的东西。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3089 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 04:11 · PVG 12:11 · LAX 20:11 · JFK 23:11
    ♥ Do have faith in what you're doing.