从python编译latex

从python编译latex,python,compiler-construction,latex,Python,Compiler Construction,Latex,我制作了一些python函数,用于使用latex将传递的字符串编译为pdf文件。该函数按预期工作,非常有用,因此我寻找改进它的方法 我拥有的代码: def generate_pdf(pdfname,table): """ Generates the pdf from string """ import subprocess import os f = open('cover.tex','w') tex = standalone_latex

我制作了一些python函数,用于使用latex将传递的字符串编译为pdf文件。该函数按预期工作,非常有用,因此我寻找改进它的方法

我拥有的代码:

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)
代码的问题在于,它在工作目录中创建了一堆名为cover的文件,这些文件随后被删除

如何避免在工作目录中创建不需要的文件

解决方案
使用临时目录。临时目录始终是可写的,可以在重新启动后由操作系统清除
tempfile
library允许您以安全的方式创建临时文件和目录

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)

您可以在创建的文件夹中生成pdf,完成后移出pdf并递归删除文件夹。这些文件不是多余的,它们由
latex
使用。您不能创建它们,只能在以后像现在一样删除它们(或使用指向
tempfile.mkdtemp()
)的当前目录运行该进程)。这些文件是
LaTeX
运行所必需的。请参阅TEX.SXI上的。我想看看带有一些虚拟目录的解决方案。有关创建内存中文件系统的方法,请参阅模块。这似乎是一个好的开始。如何移动到目的地?请查看
shutil
库。我已经在回答中包括了相关的电话。
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)