Gambit2007 Gambit2007 - 1 year ago 52
Python Question

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

I'm using the

module and
and when i try to run this code:

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

I get the following error:

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



You have to leave the /canvas.png bit. The temporary file created by tempfile.NamedTemporaryFile() was /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh. So using it as parent directory for the output file raises the error by imagemagick.

To specify the output format PNG by filename extension, the temporary file can be created with the suffix keyword argument:

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

Additionally, you should use the subprocess module to run subprocesses. That way you do not have to use string formatting the whole command in order to pass the subprocesses' arguments, e.g.

                       '-size', '{}x{}'.format(scale_width, scale_height),

And another remark: NamedTemporaryFile() opens a file descriptor, which you should close right away. The docs also state that you are in charge of deleting the file again.