在RST文件中插入伪代码报错‘unknown environment {algorithm}’求助
问题原因与解决方案
核心问题
你在conf.py中配置的LaTeX包仅对PDF/LaTeX输出生效,Sphinx的HTML渲染引擎无法识别LaTeX的algorithm/algorithmic环境——这就是HTML页面报错unknown environment {algorithm}的直接原因。另外,将伪代码嵌套在.. math::块里也不合适,这个指令是专门用于渲染数学公式的,不是伪代码容器。
解决方案分两种场景:
场景1:需要同时支持HTML和PDF显示伪代码
使用Sphinx官方维护的伪代码扩展,推荐sphinxcontrib-pseudocode,它能同时生成兼容HTML和PDF的伪代码。
- 安装扩展
pip install sphinxcontrib-pseudocode
- 在
conf.py中启用扩展
extensions = [ # 保留你已有的其他扩展 'sphinxcontrib.pseudocode', ]
- 在RST文件中用扩展语法编写伪代码
.. pseudocode:: :linenos: % This quicksort algorithm is extracted from Chapter 7, Introduction to Algorithms (3rd edition) procedure Quicksort(A, p, r) if p < r then q = Partition(A, p, r) Quicksort(A, p, q - 1) Quicksort(A, q + 1, r) end if end procedure procedure Partition(A, p, r) x = A[r] i = p - 1 for j = p to r - 1 do if A[j] < x then i = i + 1 exchange A[i] with A[j] end if end for exchange A[i+1] with A[r] return i + 1 end procedure
注:修正了你原Partition过程中的逻辑错误——最后一步交换的是A[i+1]而非A[i],并补充了返回值。
场景2:仅需PDF显示伪代码(HTML可忽略)
如果只要求PDF输出有伪代码,HTML端可以跳过渲染,用.. raw:: latex包裹LaTeX代码,这样HTML构建时会直接忽略这段内容:
.. raw:: latex \begin{algorithm} \caption{Quicksort} \begin{algorithmic} \PROCEDURE{Quicksort}{$A, p, r$} \IF{$p < r$} \STATE $q = $ \CALL{Partition}{$A, p, r$} \STATE \CALL{Quicksort}{$A, p, q - 1$} \STATE \CALL{Quicksort}{$A, q + 1, r$} \ENDIF \ENDPROCEDURE \PROCEDURE{Partition}{$A, p, r$} \STATE $x = A[r]$ \STATE $i = p - 1$ \FOR{$j = p$ \TO $r - 1$} \IF{$A[j] < x$} \STATE $i = i + 1$ \STATE exchange $A[i]$ with $A[j]$ \ENDIF \ENDFOR \STATE exchange $A[i+1]$ with $A[r]$ \RETURN $i+1$ \ENDPROCEDURE \end{algorithmic} \end{algorithm} .. note:: 伪代码仅在PDF版本中可见。
内容的提问来源于stack exchange,提问作者Lux
相关产品推荐
相关产品推荐

