从类中实例化python类作为字符串,仅在内存中!

时间:2010-08-28 09:07:47

标签: python reportlab

我正在使用Reportlab来创建PDF。我正在创建两个PDF,我想在创建后合并它们。 Reportlab提供了一种方法来将pycanvas (source)(基本上是我的pdf文件在内存中)保存为python文件,并在该python文件上调用方法doIt(filename),将重新创建pdf文件。这很好,因为您可以在源代码的基础上组合两个PDF并创建一个合并pdf。

这样做是这样的:

from reportlab.pdfgen import canvas, pycanvas
#create your canvas
p = pycanvas.Canvas(buffer,pagesize=PAGESIZE)
#...instantiate your pdf...

# after that, close the PDF object cleanly.
p.showPage()
p.save()

#now create the string equivalent of your canvas
source_code_equiv = str(p)
source_code_equiv2 = str(p)

#merge the two files on str. basis
#not shown how it is exactly done, to make it more easy to read the source
#actually one just have to take the middle part of source_code_equiv2 and add it into source_code_equiv
final_pdf = source_code_equiv_part1 + source_code_equiv2_center_part + source_code_equiv_part2

#write the source-code equivalent of the pdf
open("n2.py","w").write(final_pdf)
from myproject import n2
p = n2.doIt(buffer)

# Get the value of the StringIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response  

这很好用,但我想跳过将n2.py保存到磁盘的步骤。因此,我正在寻找一种方法来从final_pdf字符串中实例化相应的python类,并直接在源代码中使用它。这可能吗?

它应该以某种方式工作..

n2 = instantiate_python_class_from_source(final_pdf)
p = n2.doIt(buffer)

原因主要是没有必要将源保存到磁盘,其次它绝对不是线程保存。我可以在运行时命名创建的文件,但后来我不知道要导入什么!?如果无法阻止文件保存,是否有办法根据文件名定义导入,该文件名是在运行时定义的??

有人可能会问为什么我不提前创建一个pdf,但这是不可能的,因为它们来自不同的应用程序。

2 个答案:

答案 0 :(得分:1)

这似乎是一个很长的路要走你想要的。 Reportlab是否有一个Canvas类可以从中提取PDF文档?我不明白为什么这里应该涉及生成的Python源代码。

但是如果由于某种原因有必要,那么你可以使用StringIO将源“写”到一个字符串,然后执行它来执行它:

from cStringIO import StringIO

source_code = StringIO()
source_code.write(final_pdf)
exec(source_code)
p = doIt(buffer)

答案 1 :(得分:0)

好吧,我想你可以使用代码模块来提供标准的解释器的交互模式。以下将执行函数doIt。

import code
import string
coded_data = """
def doIt():
    print "XXXXX"
"""
script = coded_data + "\ndoIt()\n" 
co = code.compile_command(script, "<stdin>", "exec")
if co:
    exec co

如果有帮助,请告诉我。

相关问题