简体   繁体   中英

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)

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. 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:

import os
os.system("pdflatex filename")

You could use PyLaTeX for this. This is exactly one of the things that it is meant to be used for. https://github.com/JelteF/PyLaTeX

Make sure, you have installed Perl and MikTeX (for latexmk and pdflatex compilers support) in your system.

If not, you can download Perl from https://www.perl.org/get.html

and MikTeX from https://miktex.org/download .

Also do not forget to check http://mg.readthedocs.io/latexmk.html#installation as it guides nicely about Latex compilers.

I have document.tex with following content.

\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.

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.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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