生成 TeX/LaTeX 文件并在 Python 中编译

Generate TeX/LaTeX file and compile both in Python

我正在准备一个数据处理代码,这些代码的结果将被提供给一个 TeX/LaTeX 文件,该文件将由 Python 编译(即 Python 应该发送编译TeX/LaTeX文件的命令)

目前我打算用TeX/LaTeX的必要语法生成一个文本文件(扩展名为.tex),然后使用os.system调用外部系统命令。有没有更简单的方法或模块可以做到这一点?

不存在这样的 Python 模块,但您可以尝试使用扩展名为 .tex 的文本文件的所需语法生成文本文件,并通过 运行 系统命令和 Python 编译它:

import os
os.system("pdflatex filename")

您可以为此使用 PyLaTeX。这正是它的用途之一。 https://github.com/JelteF/PyLaTeX

确保您已经安装了 PerlMikTeXlatexmkpdflatex 编译器支持)在你的系统中。

如果没有,您可以从 https://www.perl.org/get.html

下载 Perl

MikTeX 来自 https://miktex.org/download.

另外不要忘记查看 http://mg.readthedocs.io/latexmk.html#installation,因为它很好地指导了 Latex 编译器。

我有 document.tex 内容如下。

\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
%
%
%
\begin{document}%
\normalsize%
\section{A section}%
\label{sec:A section}%
Some regular text and some %
\textit{italic text. }%
\subsection{A subsection}%
\label{subsec:A subsection}%
Also some crazy characters: $\&\#\{\}

%
\end{document}

最后创建任何 python 文件并粘贴以下任一代码和 运行。

第一种方式

# 1st way
import os

tex_file_name = "document.tex";
os.system("latexmk " + tex_file_name + " -pdf");

第二种方式

# 2nd way
import os

tex_file_name = "document.tex";
os.system("pdflatex " + tex_file_name);

为了编译复杂的 Latex 文件,您需要查找通过 latexmkpdflatex 命令传递的额外选项。

谢谢。