Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile latex from python

I have made some python function for compiling passed string as pdf file using latex. The function works as expected and has been quite useful, therefore I look for ways to improve it.

The code which I have:

def generate_pdf(pdfname,table):
    """
    Generates the pdf from string
    """
    import subprocess
    import os

    f = open('cover.tex','w')
    tex = standalone_latex(table)   
    f.write(tex)
    f.close()

    proc=subprocess.Popen(['pdflatex','cover.tex'])
    subprocess.Popen(['pdflatex',tex])
    proc.communicate()
    os.unlink('cover.tex')
    os.unlink('cover.log')
    os.unlink('cover.aux')
    os.rename('cover.pdf',pdfname)

The problem with the code is that it creates bunch of files named cover in the working directory which afterwards are removed.

How to avoid of creating unneeded files at the working directory?

Solution

def generate_pdf(pdfname,tex):
"""
Genertates the pdf from string
"""
import subprocess
import os
import tempfile
import shutil

current = os.getcwd()
temp = tempfile.mkdtemp()
os.chdir(temp)

f = open('cover.tex','w')
f.write(tex)
f.close()

proc=subprocess.Popen(['pdflatex','cover.tex'])
subprocess.Popen(['pdflatex',tex])
proc.communicate()

os.rename('cover.pdf',pdfname)
shutil.copy(pdfname,current)
shutil.rmtree(temp)
like image 527
Jānis Erdmanis Avatar asked Oct 30 '13 13:10

Jānis Erdmanis


People also ask

Can Python compile LaTeX?

PyLaTeX is a Python library for creating and compiling LaTeX files. The goal of this library is to be an easy, but extensible interface between Python and LaTeX.

How do I compile TEX in overleaf?

Click on the Overleaf menu icon above the file list panel, and set the Compiler setting to 'LaTeX'. Recompile your project. Click on the "Logs and output files" button next to the Recompile button. Scroll right to the bottom, and click on "Other logs and output files".

What is PythonTeX?

Abstract—PythonTeX is a new LaTeX package that provides access to the full power of Python from within LaTeX documents. It allows Python code entered within a LaTeX document to be executed, and provides access to the output.


1 Answers

Use a temporary directory. Temporary directories are always writable and can be cleared by the operating system after a restart. tempfile library lets you create temporary files and directories in a secure way.

path_to_temporary_directory = tempfile.mkdtemp()
# work on the temporary directory
# ...
# move the necessary files to the destination
shutil.move(source, destination)
# delete the temporary directory (recommended)
shutil.rmtree(path_to_temporary_directory)
like image 127
Eser Aygün Avatar answered Sep 23 '22 14:09

Eser Aygün