简体   繁体   English

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

[英]Generate TeX/LaTeX file and compile both in Python

I am preparing a data processing code and the results from these are to be fed to a TeX/LaTeX file and the file is to be compiled by Python (ie Python should send the command to compile the TeX/LaTeX file) 我正在准备一个数据处理代码,这些代码的结果将被提供给TeX / LaTeX文件,文件将由Python编译(即Python应该发送命令来编译TeX / LaTeX文件)

At present I plan to generate a text file (with .tex extension) with the necessary syntax for TeX/LaTeX and then call external system command using os.system. 目前我计划使用TeX / LaTeX的必要语法生成一个文本文件(扩展名为.tex),然后使用os.system调用外部系统命令。 Is there any easier way or modules that can do this? 有没有更简单的方法或模块可以做到这一点?

No such Python modules exist but you could try generating text files with the required syntax of the text file with .tex extension and compile it by running system commands with Python: 不存在这样的Python模块,但您可以尝试使用扩展名为.tex的文本文件的所需语法生成文本文件,并通过使用Python运行系统命令来编译它:

import os
os.system("pdflatex filename")

You could use PyLaTeX for this. 你可以使用PyLaTeX。 This is exactly one of the things that it is meant to be used for. 这正是它应该用于的事情之一。 https://github.com/JelteF/PyLaTeX https://github.com/JelteF/PyLaTeX

Make sure, you have installed Perl and MikTeX (for latexmk and pdflatex compilers support) in your system. 确保您已在系统中安装了PerlMikTeX (用于latexmkpdflatex编译器支持)。

If not, you can download Perl from https://www.perl.org/get.html 如果没有,您可以从https://www.perl.org/get.html下载Perl

and MikTeX from https://miktex.org/download . 和来自https://miktex.org/download的 MikTeX

Also do not forget to check http://mg.readthedocs.io/latexmk.html#installation as it guides nicely about Latex compilers. 另外不要忘记检查http://mg.readthedocs.io/latexmk.html#installation,因为它很好地指导了Latex编译器。

I have document.tex with following content. 我有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}

Finally create any python file and paste any one of the below code and run. 最后创建任何python文件并粘贴以下任何一个代码并运行。

1st way 第一路

# 1st way
import os

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

2nd way 第二种方式

# 2nd way
import os

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

For compiling complex latex files, you need to look for extra options passed with latexmk or pdflatex commands. 要编译复杂的乳胶文件,您需要查找使用latexmkpdflatex命令传递的额外选项。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM