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)
source share