Python 我可以在内存文件上运行pdflatex吗?

Python 我可以在内存文件上运行pdflatex吗?,python,pdflatex,Python,Pdflatex,我将生成一系列pdf文件,其内容将用Python(2.7)生成。通常的解决方案是将.tex内容保存在某个目录中,对文件调用pdflatex,然后读入pdf文件,以便最终将文件放在相关的位置。如下所示: import os texFile = \ """\\documentclass[11pt,a4paper,final]{article} \\begin{document} Hello, world! \\end{document} """ # Clearly will a more awes

我将生成一系列pdf文件,其内容将用Python(2.7)生成。通常的解决方案是将.tex内容保存在某个目录中,对文件调用pdflatex,然后读入pdf文件,以便最终将文件放在相关的位置。如下所示:

import os

texFile = \
"""\\documentclass[11pt,a4paper,final]{article}
\\begin{document}
Hello, world!
\\end{document}
""" # Clearly will a more awesome file be generated here!

with open('hello.tex', 'w') as f:
    f.write(texFile)
os.system('pdflatex hello.tex')
pdfFile = open('hello.pdf', 'rb').read()
# Now place the file somewhere relevant ...
我希望使用相同的程序,但以内存为基础,以提高速度并避免文件泄漏到某个文件夹中。所以我的问题是,如何在内存中运行pdflatex并将生成的pdf提取回Python?

看一看。它为TeX命令行工具提供内存中的API。例如:

>>> from tex import latex2pdf
>>> document = ur"""
... \documentclass{article}
... \begin{document}
... Hello, World!
... \end{document}
... """
>>> pdf = latex2pdf(document)

>>> type(pdf)
<type 'str'>
>>> print "PDF size: %.1f KB" % (len(pdf) / 1024.0)
PDF size: 5.6 KB
>>> pdf[:5]
'%PDF-'
>>> pdf[-6:]
'%%EOF\n'
>>来自tex import latex2pdf
>>>文件=ur“”
…\documentclass{article}
…\begin{document}
……你好,世界!
…\end{document}
... """
>>>pdf=latex2pdf(文档)
>>>类型(pdf)
>>>打印“PDF大小:%.1f KB%”(len(PDF)/1024.0)
PDF大小:5.6KB
>>>pdf[:5]
“%PDF-”
>>>pdf[-6:]
“%%EOF\n”

只需运行
pip install tex
即可安装它。还请注意,对于字符串块,您可以简单地在
r
前面加上前缀,使其成为原始字符串。这样你就不必逃避所有的反斜杠。

谢谢你的回复。我已经尝试过了,但收到以下错误消息:ValueError:如果重定向stdin/stdout/stderr,Windows平台上不支持close_fds。我正在使用Windows7。我还没有找到解决方案,也无法成功安装其后续产品“texcaller”,我认为这是因为它还没有为windows打包。但我还不确定。这听起来更像是Windows兼容性问题。我使用的是Linux,所以我不可能重现这个问题。快速搜索将显示其他项目是如何修复它的:。还要确保您使用的是PyPI中最新的软件包版本。ValueError表示重定向有错误,因此UNIX系统下的管道是错误的。你使用Cygwin吗?请注意,
texcaller
仍然在引擎盖下调用
pdflatex
,在磁盘上写入文件,所以从技术上讲它不是“内存中的”。通过
子进程运行
pdflatex
。在临时目录中运行
,执行时间相同(甚至更好),避免了所有编译模糊。