views:

65

answers:

4

Ive got this snippet that Im using to convert image files to tiff. I want to be informed when a file fails to convert. Imagemagick exits 0 when successfully run, so I figured the following snippet would report the issue. However no errors are being reported at all.


def image(filePath,dirPath,fileUUID,shortFile):
  try:
    os.system("convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif")
  except OSError, e:
    print >>sys.stderr, "image conversion failed: %s" % (e.errno, e.strerror)
    sys.exit(-1)
+5  A: 

os.system() does not throw an exception if the return value is non-zero. What you should do is capture the return value and check that:

ret = os.system(...)
if ret == ...:

Of course, what you should also do is replace os.system() with subprocess.

Ignacio Vazquez-Abrams
+3  A: 

A better think will be to use check_call from the subprocess module, it raises CalledProcessError when the subprocess returned a non zero value.

lazy1
This will have several advantages over using `os.system`—The Pythonic API the caller wanted, avoiding using the shell, and handling signals in a more normal way.
Mike Graham
+1  A: 

You can access ImageMagick directly through Python using PythonMagick (download here). A more popular tool for image manipulation is PIL.

Mike Graham
A: 

+ is generally a bad way to build strings in Python.

I would tend to replace "convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif" with

import os.path
"convert %s +compress %s.tif" % (filePath, os.path.join(dirPath, shortFile))

That being said, you'd replace the whole os.system call using

from subprocess import check_call, CalledProcessError

newFile = "%s.tif" % (filePath, os.path.join(dirPath, shortFile)
command = ["convert", filePath, "+compress", newFile]
try:
    check_call(command)
except CalledProcessError as e:
    ...
Mike Graham