2010-03-26 48 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: 
    ...