Gambit2007 Gambit2007 - 5 months ago 8
Python Question

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:

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'
@ 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.

Thanks!

Answer

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.

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. The docs also state that you are in charge of deleting the file again.

Comments