我有以下文件:
from fabric.api import env, execute, run
env.hosts = ['1.2.3.4']
def taskA():
run('ls')
def main():
try:
execute(taskA)
except:
print "Exception Caught"
main()
当我运行这个时,我能够看到打印的"异常捕获":
$ python test.py
[1.2.3.4] Executing task 'taskA'
[1.2.3.4] run: ls
Fatal error: Timed out trying to connect to 1.2.3.4 (tried 1 time)
Underlying exception:
timed out
Aborting.
Exception Caught
但是,当我将其切换到此时:
def main():
try:
execute(taskA)
except Exception, e:
print "Exception Caught", e
main()
我没有看到异常被捕获:
[1.2.3.4] run: ls
Fatal error: Timed out trying to connect to 1.2.3.4 (tried 1 time)
Underlying exception:
timed out
Aborting.
有什么原因让我能够在上面的代码而不是下面的代码中捕获错误吗?
此异常不是从Exception
派生的。它看起来像一个SystemExit
,直接来源于BaseException
。except Exception
只捕获Exception
的实例。
如果你真的想捕获绝对所有的异常,你可以这样做
except BaseException as e:
SystemExit
由sys.exit
和一些类似的函数引发,导致解释器关闭(或至少结束线程(,同时仍运行__exit__
方法和finally
块。它也可以手动抛出。
BaseException
存在,因此SystemExit
和一些类似的异常不会被通常不打算处理它们的except Exception
块捕获。它类似于Java的Throwable
。就个人而言,我希望普通except:
块不会抓住BaseException
;它首先违背了BaseException
的一些目的。
当你使用except Exception, e
时,它
未捕获
BaseException
或系统退出异常SystemExit
、KeyboardInterrupt
和GeneratorExit
其中 asexcept
捕获所有异常类型。请参阅 Python 中的 except: 和 except Exception as e: 之间的区别。
因此,您在使用except
时会看到"异常捕获",但在使用except Exception, e
时不会
来自晶圆厂文档
如果引发 Python 异常,fab 将中止,退出状态为 1。