python - 如何将源代码添加到使用 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 时,我无法在文档中找到如何添加源代码。有什么提示吗?
解决方案
有一种方法可以通过名为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}
推荐阅读
- c++ - CURL 作为 C++ 类的私有成员
- linux - 如何在装配中打开像素 (NASM)
- python - 使用 pip3 安装后未找到 Python3 模块错误
- unit-testing - 使用 bufconn 对 gRPC 进行单元测试时模拟“peer”
- ios - 如何在使用 ffmpeg 将介绍图像开始合并到视频后保持视频质量相同
- c - 顺序错误的命令行程序
- python - Python Flask SSL 超时,非 SSL 很好
- typescript - webpack 导入 App.vue 或其他组件 vue 失败
- php - 如何在 PHP 中保护 HTML 输入字符串
- python - 具有多个输入的 TensorFlow 自定义层中构建方法的 Input_shape