Python操作系统错误不报告错误
我得到了这个片段,我用它把图像文件转换成tiff。当文件无法转换时,我希望得到通知。Imagemagick在成功运行时退出0,因此我认为以下代码段将报告此问题。但是,没有报告任何错误Python操作系统错误不报告错误,python,imagemagick,Python,Imagemagick,我得到了这个片段,我用它把图像文件转换成tiff。当文件无法转换时,我希望得到通知。Imagemagick在成功运行时退出0,因此我认为以下代码段将报告此问题。但是,没有报告任何错误 def image(filePath,dirPath,fileUUID,shortFile): try: os.system("convert " + filePath + " +compress " + dirPath + "/" + shortFile + ".tif") except OSE
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()
如果返回值非零,则不会引发异常。您应该做的是捕获返回值并检查:
ret = os.system(...)
if ret == ...:
当然,您还应该将
os.system()
替换为。更好的方法是从子流程模块使用,当子流程返回非零值时,它会引发CalledProcessError。您可以使用PythonMagick()通过Python直接访问。一个更流行的图像处理工具是。+
通常是在Python中构建字符串的一种不好的方法
我倾向于将“convert”+filePath+“+compress”+dirPath+“/”+shortFile+“.tif”
替换为
import os.path
"convert %s +compress %s.tif" % (filePath, os.path.join(dirPath, shortFile))
也就是说,您将使用
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:
...
这将比使用调用方想要的pythonicapi
os.system
、避免使用shell和以更正常的方式处理信号有几个优点。