Skip to main content
 首页 » 编程设计

Python-sphinx:忽略 .rst 文件中的文本

2025年05月04日18emanlee

我在 GitHub 上有一个 README.rst,它也包含在 Sphinx 为 Python 项目生成的文档中。我想在文件顶部添加一条注释,该注释将显示在 GitHub 上(仅呈现 .rst)但不会显示在 Sphinx 生成的文档中。

我知道我可以使用 .. blah blah blah 在 .rst 文件中包含注释,但是有什么方法可以包含一行只考虑 Sphinx 的评论? (或者,让 Sphinx 忽略该行。)

请您参考如下方法:

您想在 GitHub 上包含 .rst 文件中的一行,但在您的 Sphinx 文档中被忽略。

可以使用 ifconfig 指令来实现 sphinx.ext.ifconfig – Include content based on configuration这样。

在你的 conf.py 文件中检查是否启用了 sphinx.ext.ifconfig 扩展

# conf.py 
extensions = [ 
    ... 
    'sphinx.ext.ifconfig', 
    ... 
] 

并注册一个变量

# conf.py 
# custom variables 
def setup(app): 
    app.add_config_value(name='show_github_hote', default=True, rebuild='env') 
 
# uncomment in Sphinx doc to hide the note 
# show_github_hote = False 

然后在你的.rst文件中

.. ifconfig:: show_github_hote 
 
    THIS NOTE IS FOR GITHUB ONLY. 
 
    Use bigger indentation for the note. 
 
Further text with smaller indent.  

如果未设置 show_github_hote var,则默认值为 True 并且应该打印注释。在 conf.py 中隐藏注释集 show_github_hote = False。