【问题标题】:How to use python functions in conf.py file in Sphinx如何在 Sphinx 的 conf.py 文件中使用 python 函数
【发布时间】:2013-08-21 11:30:06
【问题描述】:

我编写了一个名为 myFunction 的小 Python 函数,存储在我想在 conf.py 文件中调用的 function.py 中。从测试 python 文件调用该函数时,该函数工作正常,因此我似乎在此文件中专门导入模块时遇到问题。

设置是这样的:

DocumentSourceFolder/sourcefile.txt

DocumentSourceFolder/conf.py

DocumentSourceFolder/function.py

在 conf.py 中我添加了以下内容:

import function

variable = function.myFunction()

(其中变量是 conf.py 文件中已经存在的东西)。

但是,在此文档上运行 sphinx 时,我收到错误:

ImportError: No module named function

有什么想法吗?

谢谢

【问题讨论】:

    标签: python import python-sphinx


    【解决方案1】:

    试试:

    from function import function
    

    与:

    import function 
    

    Python 尝试导入一个模块;你的文件显然不是。 请参阅http://docs.python.org/2/tutorial/modules.html#more-on-modules中的部分

    【讨论】:

    • 感谢您的回答。这只给出了与以前相同的错误。解决方案实际上是使用狮身人面像。
    • 我在下面添加了我的解决方案。
    • "Python 试图导入一个模块;你的文件显然不是"?你为什么这么说?当然它是一个模块。 A module is a file containing Python definitions and statements.
    【解决方案2】:

    事实证明,Sphinx 对在 conf.py 文件中导入 python 模块有点挑剔。为避免错误,您需要执行 2 个步骤:

    1) 添加到你的conf.py文件

    import sys, os
    sys.path.append(os.path.relpath('relative/path/to/folder/containing/module'))
    

    这意味着 sphinx 现在在这里寻找扩展模块。然后你必须将模块名称添加到extensions = [...] 列表中。

    2) 将以下内容添加到您的模块中:

    def setup(app):
        return
    

    sphinx 需要此“setup() 函数”才能接受您的模块确实是扩展模块。

    完成!

    【讨论】:

    • 您可以在 conf.py 中导入您喜欢的任何模块(只要它在 sys.path 中)。它不必是具有setup() 函数的扩展模块。
    • 在没有 setup() 函数的情况下尝试运行 Sphinx 时会出错
    • 如果你只想从 conf.py 中导入一个模块,请确保它可以通过sys.path 找到。如果模块应该是 Sphinx 扩展模块,您还必须将其添加到扩展配置变量中并包含 setup() 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多