Compiling latex from python

I made some python function to compile the passed string in pdf format using latex. The function works as expected and was very useful, so I'm looking for ways to improve it.

The code I have is:

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 a bunch of files called cover in the working directory, which is subsequently deleted.

How to avoid creating unnecessary files in the working directory?

Decision

 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) 
+6
source share
1 answer

Use a temporary directory. Temporary directories are always writable and may be deleted by the operating system after a reboot. The tempfile library allows you to safely create temporary files and directories.

 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) 
+8
source

Source: https://habr.com/ru/post/957038/


All Articles