从python编译乳胶 [英] Compile latex from python

查看:184
本文介绍了从python编译乳胶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一些python函数编译传递的字符串作为 pdf 文件使用latex。

I have made some python function for compiling passed string as pdf file using latex. The function works as expected and has been quite useful, therefore I look for ways to improve it.

我拥有的代码:

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

The problem with the code is that it creates bunch of files named cover in the working directory which afterwards are removed.

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

How to avoid of creating unneeded files at the working directory?

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 库可让您以安全的方式创建临时文件和目录。

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.

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)

这篇关于从python编译乳胶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆