要在 Sphinx 中展示源代码,您可以通过以下步骤来配置:
1. **安装必要的插件**:首先,您需要安装一个插件`sphinx-better-include`,这个插件可以帮助您更方便地包含代码片段。可以通过运行以下命令来安装:
```bash
pip install sphinx-better-include
```
2. **配置Sphinx**:在您的 Sphinx 项目中,您需要编辑 `conf.py` 文件,添加对插件的引用以及设置包含代码片段的方式。以下是一个示例配置:
```python
extensions = [
'sphinx_better_include', # 引入 sphinx-better-include 插件
]
# 使用 sphinx-better-include 时使用的代码语言
pygments_style = 'sphinx'
# 定义如何包含代码片段的指令
source_parsers = {
'.rst': 'sphinx.directives.codeblock',
}
```
3. **创建代码示例**:在您的文档中,使用以下语法来包含代码:
```python
.. code-include:: /path/to/your/file
:language: python
:start-after: [start]
:end-before: [end]
```
其中,`/path/to/your/file`是您要包含的代码文件的路径,`python`是代码的语言(根据需要更改),`[start]`和`[end]`是文件中用于标记开始和结束的部分。
4. **测试您的文档**:保存您的文档并构建它,然后查看生成的 HTML 文件中是否正确显示了您包含的代码片段。
以下是一个完整的示例:
```python
# conf.py
extensions = [
'sphinx_better_include',
]
pygments_style = 'sphinx'
source_parsers = {
'.rst': 'sphinx.directives.codeblock',
}
```
您的文档(如 `index.rst`)中的内容可能如下:
```rst
Welcome to the Documentation!
=============================
Here's a sample Python code:
.. code-include:: /path/to/your/file
:language: python
:start-after: [start]
:end-before: [end]
This is the end of the document.
```
在这个示例中,您首先配置了 `sphinx_better_include` 插件,然后通过 `.. code-include::` 指令包含了一个 Python 代码片段。通过 `start-after` 和 `end-before` 选项,我们指定了代码块的开始和结束位置。
如果您需要更复杂的控制,还可以使用 Sphinx 的其他内置功能,如 `literalinclude` 或 `highlight` 指令。python