简体   繁体   English

从python编译乳胶

[英]Compile latex from python

I have made some python function for compiling passed string as pdf file using latex. 我已经制作了一些python函数,用于使用latex编译传递的字符串作为pdf文件。 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. 代码的问题在于它在工作目录中创建了一堆名为cover的文件,之后被删除。

How to avoid of creating unneeded files at the working directory? 如何避免在工作目录中创建不需要的文件?

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)

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. 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM