从Python编译LaTeX

7

我为编译latex字符串成pdf文件制作了一些Python函数。这个函数按预期工作,非常有用,因此我正在寻找改进它的方法。

以下是我的代码:

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的文件,之后这些文件会被删除。

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

解决方案

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)

你可以创建一个文件夹来构建你的PDF,完成后将PDF移出文件夹并递归删除该文件夹。 - Theolodis
1
这些文件并非是不必要的,它们被latex使用。你不能不创建它们,只能像现在一样在之后删除它们(或在当前目录指向tempfile.mkdtemp()的情况下运行该过程)。 - fjarri
这些文件是 LaTeX 运行所必需的。请参阅 TEX.SX 上的 此问题 - darthbith
我想看一下带有某些虚拟目录的解决方案。 - Jānis Erdmanis
请参考 fs 模块,其中一种方法是创建一个内存文件系统。 - chepner
显示剩余2条评论
1个回答

9

使用临时目录。临时目录总是可写的,并且可以在重启后由操作系统清除。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)

看起来是个不错的开始。如何移动到目的地? - Jānis Erdmanis
看一下 shutil 库。我已经在答案中包含了相关的调用。 - Eser Aygün

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接