【问题标题】:Calling rst2pdf through subprocess in Django app truncates file通过 Django 应用程序中的子进程调用 rst2pdf 截断文件
【发布时间】:2013-10-18 22:34:45
【问题描述】:

我正在使用 rst2pdf 在我的 Django 应用程序中生成格式化的 pdf 文件。这是我用来执行此操作的代码:

temp_file = tempfile.NamedTemporaryFile(mode='w+t', dir=PDF_PATH, delete=False)
temp_pdf = tempfile.NamedTemporaryFile(dir=PDF_PATH, delete=False)
temp_file.write(plaintext)

subprocess.call('rst2pdf ' + temp_file.name +' -s '+ STYLESHEET_PATH +' -o ' + temp_pdf.name, shell=True)
pdf = open(temp_pdf.name, 'rb')

response = HttpResponse(pdf.read(), mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=output.pdf'
response['Content-Length'] = os.stat(temp_pdf.name).st_size


return response

由于某种原因,作为响应提供的 pdf 在最后一页被截断。文件系统上的 pdf 被截断。我可以看到正在写入 pdf 的纯文本,它就在那里。我什至在命令行上使用所有相同的参数运行了相同的 rst2pdf 调用,并且 pdf 生成得很好。但由于某种原因,当我从我的 Django 应用程序中调用 rst2pdf 时,该文件被截断。关于可能导致这种情况的任何想法,或者关于如何调试子进程调用的任何想法?

【问题讨论】:

    标签: python django subprocess rst2pdf


    【解决方案1】:

    看来我没有完全理解 python 如何处理可写文件。显然在调用 temp_file.write 之后,缓冲区中仍有数据不会被写出,除非我调用 temp_file.close() 或 temp_file.flush()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2016-06-07
      • 1970-01-01
      • 2014-07-28
      • 2011-10-26
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多