python - 将标准输出从命令行函数发送到 python StringIO 对象

标签 python django amazon-s3 imagemagick

哇,很难将我的问题概括为一个简洁的标题。我希望我成功了。

我有一个简单的缩略图功能,当我尝试从 Amazon S3 检索 URL,然后使用 ImageMagick 对其进行转换时,该功能会导致出现问题。我通常会使用 PIL 读取图像文件并将其转换,但 PIL 不读取 PDF 格式,因此我求助于通过子进程调用进行转换。

这是 djangoviews.py 中的一些代码。这里的想法是,我从 S3 获取一个文件 url,用 convert 打开它,将其处理为 PNG,将其发送到 stdout,然后使用输出的缓冲区加载 StringIO 对象,该对象然后传回 default_storages 以将缩略图文件保存回 S3。对于这样一个简单的工作来说,真是太疯狂了,但是就这样吧。

请注意:我无法在使用 Heroku 的生产设置中使用 convert 可靠地将文件保存到磁盘,否则我已经这样做了。

def _large_thumbnail_s3(p):

    # get the URL from S3, trimming off the expiry info etc. So far so good.

    url = default_storage.url(p+'.pdf').split('?')
    url = url[0]

    # this opens the PDF file fine, and proceeds to convert and send 
    # the new PNG to the buffer via standard output.

    from subprocess import call 
    call("convert -thumbnail '400x600>' -density 96 -quality 85 "
        +url
        +" png:-", shell=True)

    from StringIO import StringIO

    # here's where the problem starts. I'm clearly not reading
    # in the stdout correctly, as I get a IOError: File not open for reading
    # from this next line of code:

    completeStdin = sys.stdout.read()
    im = StringIO(completeStdin)

    # now take the StringIO PNG object and save it back to S3 (this 
    # should not be an issue.

    im = default_storage.open(p+'_lg.png', 'w+b')
    im.close()

任何人都可以告诉我a)在将输出发送回缩略图功能方面我可能会出错的地方,以及b)您是否可以建议任何更强大的替代方案来替代看起来相当老套的方法!

TIA

最佳答案

您需要使用subprocess.check_output,而不是subprocess.call:

from subprocess import check_output
from StringIO import StringIO

out, err = check_output("convert -thumbnail '400x600>' -density 96 -quality 85 "
    +url
    +" png:-", shell=True)

buffer = StringIO(out)

关于python - 将标准输出从命令行函数发送到 python StringIO 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17777728/

相关文章:

python - 如何在 Django 中获取阿拉伯字符串的 Unicode 表示?

python - 尝试使用 pyspark 从 S3 获取数据时出现空指针异常

Python - Fine Uploader 服务器端 AWS 版本 4 签名请求

python - GeoDjango 图层映射和外键

javascript - 将 Python 中的数组传递给 Django 模板

django - 获取存在外键类型的对象

node.js - 适用于 Node.js 的 AWS S3 SDK V3 - GetObjectCommand v/s getSignedUrl

php - 亚马逊 S3 : Monitor my bucket's current disk and bandwidth usage using PHP?

python - 如何在 Django 中将 PDFTemplateResponse 转换为类似字节的对象?

Python:如果列表中不存在文件则创建文件