【问题标题】:Python - tempfile module creates a file that cannot be opened?Python - tempfile 模块创建一个无法打开的文件?
【发布时间】:2016-06-21 19:46:45
【问题描述】:

我正在使用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 /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh/canvas.png' @error/png.c/MagickPNGErrorHandler/1630.

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

谢谢!

【问题讨论】:

标签: python imagemagick temporary-files


【解决方案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() 打开一个文件描述符,你应该马上关闭它。文档还声明您负责再次删除该文件。

【讨论】:

  • 但是我怎么能告诉 imagemagick 我想要一个在那个位置以某种方式命名的 .png 文件呢?
  • NamedTemporaryFile() 有一个 suffix 关键字参数。答案已相应编辑。
  • 马上关闭文件描述符?然后是 mkstemp 返回值是一个元组的不一致。将tempfile API 包含在标准库中是不是有点奇怪?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
相关资源
最近更新 更多