代码示例

将代码片段格式化为独立的字面块。有几种方法可以在 RST 文件中定义代码块。

标准字面块

指令

::code

参数

none

选项

none

描述

  • 引入标准的 reST 字面块。

  • 保留换行符和空格。

  • 自动高亮语言(默认情况下为 Python)

如果您在一个文件中提供用一种编程语言编写的代码片段,请使用 ::code 指令。 默认情况下,以这种方式格式化的代码块以 Python 高亮模式显示。

要定义另一种高亮语言,请使用 code-block 指令,如 非标准字面块 部分所述。

输入

Add logging statements::

  from nova.openstack.common import log as logging
  LOG = logging.getLogger(__name__)

输出

添加日志语句

from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)

非标准字面块

指令

code-block

参数

python(默认)、rubycconsoleini

选项

linenosemphasize-lines

描述

  • 直接指定高亮语言。

  • 保留换行符和空格。

为了优化特定编程语言的代码输出,请使用 code-block 及其相应的参数指定。 使用 ini 用于配置文件,console 用于控制台输入和输出,依此类推。

输入

.. code-block:: ini

   # Configuration for nova-rootwrap
   # This file should be owned by (and only-writeable by) the root user

   [DEFAULT]
   # List of directories to load filter definitions from (separated by ',').

输出

# Configuration for nova-rootwrap
# This file should be owned by (and only-writeable by) the root user

[DEFAULT]
# List of directories to load filter definitions from (separated by ',').

注意

编写命令示例时,应将控制台的输入和输出原样写入一个代码块中,不要添加额外的空行,也不要将其拆分为输入块和输出块。 在适当的情况下,您可以省略输出。

code-block 指令的选项

您可以使用 :linenos: 参数为代码示例添加行号,并使用 :emphasize-lines: 参数突出显示某些特定行

输入

.. code-block:: python
   :linenos:
   :emphasize-lines: 3,5-6

   def some_function():
       interesting = False
       print 'This line is highlighted.'
       print 'This one is not...'
       print '...but this one is.'
       print 'This one is highlighted too.'

输出

1def some_function():
2    interesting = False
3    print 'This line is highlighted.'
4    print 'This one is not...'
5    print '...but this one is.'
6    print 'This one is highlighted too.'

使用远程文件的字面块

指令

remote-code-block

参数

python(默认)、rubycconsoleini

选项

linenosemphasize-lines

描述

  • 直接指定高亮语言。

  • 保留换行符和空格。

此指令的行为与 code-block 指令完全相同,但从远程 URL(httphttps)获取内容。

remote-code-block 是一个自定义指令。

输入

.. remote-code-block:: ini

   https://opendev.org/openstack/nova/src/branch/stable/2025.2/etc/nova/api-paste.ini

输出

############
# Metadata #
############
[composite:metadata]
use = egg:Paste#urlmap
/: meta

[pipeline:meta]
pipeline = cors ec2faultwrap logrequest metaapp