我已经做了一些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的文件,这些文件随后会被删除。
如何避免在工作目录中创建不需要的文件?
解决方案
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)发布于 2013-10-30 13:26:12
使用临时目录。临时目录始终是可写的,可以在重新启动后由操作系统清除。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)https://stackoverflow.com/questions/19683123
复制相似问题