首页 > 解决方案 > 如何将源代码添加到使用 sphinx 生成的 LaTeX 文档中

问题描述

我正在使用 Sphinx 生成我的 python 库的文档。我使用扩展sphinx.ext.viewcode

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.doctest",
    "sphinx.ext.intersphinx",
    "sphinx.ext.ifconfig",
    "sphinx.ext.viewcode",  # Add links to highlighted source code
    "sphinx.ext.napoleon",  # to render Google format docstrings
]

这会生成一个指向源文档的链接,类似于:

class MyClass(param1, param2)[source]

就像这张图片:

截屏

如果我按源,我会在我的 HTML 页面中正确地看到源代码。

我想在生成 LaTeX 文件时做同样的事情。当您从 LaTeX 创建 pdf 时,我无法在文档中找到如何添加源代码。有什么提示吗?

标签: pythonlatexpython-sphinx

解决方案


有一种方法可以通过名为listings的包向 python 添加代码。这个包允许显示代码甚至完整的文件。

为了实现这一点,conf.py您可以添加:

latex_elements = {
    "papersize": "letterpaper",
    "pointsize": "10pt",
    "figure_align": "htbp",
    "preamble": r"""
        \usepackage{listings}
        \lstset{ 
            language=Python,                 % the language of the code
            title=\lstname                   % show the filename of files included with \lstinputlisting; also try caption instead of title
        }
    """,
}

可以添加更多设置lstset

然后可以将代码添加到.rst文件中,如下所示:

.. raw:: latex

    \section{Code}
    \lstinputlisting{../../../path/to/my/file.py}

推荐阅读