从 python 编译 Latex

2024-01-01

我制作了一些 python 函数来将传递的字符串编译为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在工作目录中,然后将其删除。

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

Solution

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)

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

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 python 编译 Latex 的相关文章

随机推荐