Python OSError not reporting errors
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 t开发者_开发技巧he 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)
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
.
A better think will be to use check_call from the subprocess module, it raises CalledProcessError when the subprocess returned a non zero value.
You can access ImageMagick directly through Python using PythonMagick (download here). A more popular tool for image manipulation is PIL.
+
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:
...
精彩评论