2010-03-26 50 views
0

我得到了这个片段,我用图片文件转换为TIFF。我想在文件无法转换时收到通知。 Imagemagick成功运行时退出0,所以我想下面的代码片段会报告问题。然而,根本没有报道任何错误。Python OSError不报告错误


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

os.system()如果返回值不为零,则不会引发异常。你应该做的是获取返回值,并检查:

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

当然,你应该做的就是subprocess取代os.system()

3

一个更好的想法是使用子进程模块中的check_call,当子进程返回非零值时,会引发CalledProcessError。

+0

这将有超过使用'os.system'-几个优点调用者想要的Pythonic API,避免使用shell,并以更常规的方式处理信号。 – 2010-03-26 01:25:44

0

+通常是在Python中构建字符串的不好方法。

我会倾向于与

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

更换"convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif"话虽这么说,你会更换整个os.system呼叫使用

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: 
    ...