Python - tempfile模块创建一个无法打开的文件?

时间:2016-06-21 19:46:45

标签: python imagemagick temporary-files

我正在使用tempfile模块和imagemagick,当我尝试运行此代码时:

width = height = 100
temp_file = tempfile.NamedTemporaryFile()
canvas = "convert -size {}x{} canvas:black {}/canvas.png".format(scale_width, scale_height, temp_file.name)
os.system(canvas)

我收到以下错误:

  

转换:无法打开图片   /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh/canvas.png': Not a directory @ error/blob.c/OpenBlob/2705. convert: WriteBlob Failed /变种/文件夹/ JN / phqf2ygs0wlgflgfvvv0ctbw0009tb / T / tmpeMcIuh / canvas.png'   @ error / png.c / MagickPNGErrorHandler / 1630。

可能是什么问题? 我只想创建一个存储在随机生成的临时文件中的黑色图像(分辨率为100x100)。

谢谢!

1 个答案:

答案 0 :(得分:1)

你必须离开/canvas.png位。 tempfile.NamedTemporaryFile()创建的临时文件为/var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh。因此,将它用作输出文件的父目录会通过imagemagick引发错误。

要通过文件扩展名指定输出格式PNG,可以使用suffix关键字参数创建临时文件:

temp_file = tempfile.NamedTemporaryFile(suffix='.png')

此外,您应该使用subprocess模块来运行子进程。这样你就不必使用字符串格式化整个命令来传递子进程'争论,例如

subprocess.check_call(['convert',
                       '-size', '{}x{}'.format(scale_width, scale_height),
                       'canvas:black',
                       temp_file.name])

另一个评论:NamedTemporaryFile()打开一个文件描述符,你应该立即关闭它。文档还声明您负责再次删除该文件。

相关问题