Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python操作系统错误不报告错误_Python_Imagemagick - Fatal编程技术网

Python操作系统错误不报告错误

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

我得到了这个片段,我用它把图像文件转换成tiff。当文件无法转换时,我希望得到通知。Imagemagick在成功运行时退出0,因此我认为以下代码段将报告此问题。但是,没有报告任何错误


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和以更正常的方式处理信号有几个优点。