简体   繁体   English

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

[英]Python - tempfile module creates a file that cannot be opened?

I'm using the tempfile module and imagemagick and when i try to run this code: 我正在使用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)

I get the following error: 我收到以下错误:

convert: unable to open image /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': Not a directory @ error/blob.c/OpenBlob/2705. convert: WriteBlob Failed /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. /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。

What could be the problem? 可能是什么问题呢? I'm just trying to create a black image (resolution of 100x100) stored in a randomly generated temp file. 我只是想创建一个存储在随机生成的临时文件中的黑色图像(分辨率为100x100)。

Thanks! 谢谢!

You have to leave the /canvas.png bit. 您必须离开/canvas.png位。 The temporary file created by tempfile.NamedTemporaryFile() was /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh . tempfile.NamedTemporaryFile()创建的临时文件是/var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh So using it as parent directory for the output file raises the error by imagemagick. 因此,将其用作输出文件的父目录会引起imagemagick的错误。

To specify the output format PNG by filename extension, the temporary file can be created with the suffix keyword argument: 要通过文件名扩展名指定输出格式PNG,可以使用suffix关键字参数创建临时文件:

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

Additionally, you should use the subprocess module to run subprocesses. 此外,您应该使用subprocess模块来运行子流程。 That way you do not have to use string formatting the whole command in order to pass the subprocesses' arguments, eg 这样,您不必使用字符串格式化整个命令即可传递子过程的参数,例如

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

And another remark: NamedTemporaryFile() opens a file descriptor, which you should close right away. 还有另一句话: NamedTemporaryFile()打开一个文件描述符,您应该立即将其关闭。 The docs also state that you are in charge of deleting the file again. 该文档还指出,您负责再次删除该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM