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?
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)
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.
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".
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With