问题:
我一直在和Read the Docs战斗.导入的模块与 I/O 交互,因此文档不包含任何文本。但构建不会失败。
尝试的解决方案:
我正在尝试使用 mock
或 MagicMock
在 doc/conf.py 但它不起作用。
所需的解决方案
基本上,我想mock
整个导入。所以 RTD 确实 不是 尝试运行任何代码。只需从 DocStrings 生成文档。
我只是想mock
全部 一个模块的元素。 类(class) , 功能 , 和 变量 .任何带有 DocString 的东西。
目前我必须 将项目安装在 virtualenv 中,以满足导入。如果没有必要,我想避免这种情况。现在......如果我不这样做,文档也不包含任何文本。同样,构建不会失败。
细节
例子.py
"""Basic DocSting Comments"""
from external.module import *
foo = module()
foo.connect()
"""
I want this to show up in RTD.
"""
我的具体案例可以找到here .文档/conf.py
from mock import MagicMock
MOCK_MODULES = ['external.module', 'eternal.module.module', 'external.module.module.connect']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = MagicMock()
我尝试了十几种不同的方法,但都没有运气。使用 mock
和 MagicMock
, 不同 advanced settings
在 RTD 中。 一切都没有运气。 一个丑陋的黑客:
我确实遇到了一个丑陋的黑客。但这违背了使用 DocStrings 的目的。再次编写代码以便 RTD 可以捕获 DocStings,不妨将其写在单独的文档中。
if __name__ == "__main__":
this = foo.connect()
"""
This is where the real DocStrings go.
"""
else:
this = 'this is the connect'
"""
This is where the RTD DocStrings would go
"""
我不想以两次代码结束,只是为了添加一些文档。MySQL 连接器/Python
我还想将它与 MySQL 连接器一起使用。由于 RTD 在遇到此包时也会中断。我无法用
requirements.txt
修复它.import mysql.connector as db
db_connection = db.connect(**my_config)
"""
Perhaps I want to include some details here.
"""
最佳答案
我在 this blog post 上找到的以下解决方案为我工作。我想模拟 open3d
我能够做到这一点:
from unittest import mock
# Mock open3d because it fails to build in readthedocs
MOCK_MODULES = ["open3d"]
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = mock.Mock()
注意需要导入mock
来自 unittest
因为 unittest.mock 是从 Python 3.3 ( source ) 开始的内置模块。如果你想模拟多个包,你可以这样做:
from unittest import mock
# Mock open3d because it fails to build in readthedocs
MOCK_MODULES = ["open3d", "numpy", "matplotlib", "matplotlib.pyplot"]
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = mock.Mock()
关于python - 如何模拟导入以阅读文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40736124/