从python编译乳胶

Jān*_*nis 6 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(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)
Run Code Online (Sandbox Code Playgroud)

代码的问题在于它在工作目录中创建了一堆名为cover的文件,之后被删除.

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

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)
Run Code Online (Sandbox Code Playgroud)

Ese*_*gün 8

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

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)
Run Code Online (Sandbox Code Playgroud)