【问题标题】:Sphinx autodoc fails to import moduleSphinx autodoc 无法导入模块
【发布时间】:2019-02-21 20:29:50
【问题描述】:

我正在尝试使用 Sphinx 记录一个项目,但遇到了一个问题,即仅从文件夹中导入了一些模块。我的项目结构如下:

Project
|
|--Main
|    |--Scripts
|          __init__.py
|          libsmop.py
|          conv_table.py
|          f_discrim.py
|          recipes.py
|          ...

当我尝试运行 make htmllibsmoprecipes 导入时没有任何问题,但是 conv_tablef_discrim 得到以下错误:

WARNING: autodoc: failed to import module u'conv_table' from module u'Scripts'; the following exception was raised:No module named conv_table

我不认为这是我的配置文件,因为当我运行 sphinx-apidoc -o _rst Main/Scripts 时它会找到所有文件,并且我已确认它们出现在生成的 Scripts.rst 文件中。

为什么 autodoc 会找到一些模块而不是其他模块?

编辑: conv_table.py 是这种形式:

import re
import numpy as np

"""
conv_table dictionary at the bottom of this file maps from matlab functions
to their python equivalents.
"""

def get_args(line,separator=",", open_char='(', close_char=')'):
    """Returns the arguments of line

    >>> get_args('ones(3,1,length(arr))')

...
< a bunch of function definitions>
...

conv_table = {... < a very big dictionary > ...}

【问题讨论】:

  • 收到__init__.py?每个目录都需要它以使其成为 Python 模块并且可导入。
  • 是的,我在Scripts 目录中有一个__init__.py 文件。
  • Sphinx autodoc 命令长什么样子?

标签: python python-sphinx autodoc


【解决方案1】:

由于您的 autodoc 正在获取一些模块,这可能是因为失败模块的依赖项要么是 1)未正确导入,要么是 2)未安装在您的 python 环境下。您将需要检查所有导入语句是否在失败的模块中工作。

【讨论】:

  • 太棒了!我猜 Sphinx 不应该吞噬来自 python 解释器的警告。
【解决方案2】:

你要检查模块加载路径,根据Sphinx docs:

为了让 Sphinx(实际上是执行 Sphinx 的 Python 解释器)找到您的模块,它必须是可导入的。这意味着模块或包必须位于 sys.path 上的目录之一中——相应地调整配置文件中的 sys.path。

此外,了解 Scripts 目录中的 __init__.py 的外观以及 conv_table 模块的外观也会很有用。

【讨论】:

  • 我认为模块加载路径是正确的,因为它正在拾取文件夹中的某些模块。现在我将添加一个编辑,显示我的 conv_table,但我的 __init__.py 仅包含 cmets。
  • 还在您的conf.py 中添加任何定义sys.path 的行。
  • 我有两行代码:sys.path.insert(0, os.path.abspath('.'))sys.path.append('Main')
  • @AlexCavanaugh 代码是开源的吗?如果没有其他源代码,很难看到路径发生了什么
  • 不幸的是它不是开源的。但我认为我应该能够做类似sys.path.append(os.path.abspath('./Main/Scripts')) 的事情,因为Sphinx 已经用完了Project 目录。听起来对吗?
【解决方案3】:

我遇到了和你类似的问题,解决方法是在 ../source/conf.py 文件中附加包含该模块的路径

sys.path.insert(0, os.path.abspath('任何适合你的文件夹结构的相对路径')) sys.path.append('/path/to/the/conv_table/')

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 2020-01-05
    • 2022-06-30
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多