python – Fabric:处理异常,所以我可以在try块中捕获它
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Fabric:处理异常,所以我可以在try块中捕获它,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2551字,纯文字阅读大概需要4分钟。
内容图文
![python – Fabric:处理异常,所以我可以在try块中捕获它](/upload/InfoBanner/zyjiaocheng/725/5566b866337340fd91f3de473adabb46.jpg)
我试图找到一种方法来处理Fabric错误.
示例:如果我的远程主机停机进行维护,并且我的应用程序正在运行,尝试完成一些工作,我从Fabric获得了一个例外.这阻止了我的应用程序,并打印出可怕的堆栈跟踪.
为了避免这种情况,因为我需要知道主机何时关闭,我将我的请求包装到远程,使用try块,但我不确定应该在except块中放入什么,以便仅捕获来自Fabric的异常(比如networkError和类似的).
使用Fabric处理try-except块的正确方法是什么?或者更具体地说,我将什么放在“except”块中,因此它将捕获来自结构的任何异常,并避免让整个应用程序退出并打印出堆栈错误?
解决方法:
在捕获错误后,logging.exception将输出回溯:
import logging
try:
1/0
except Exception as e:
logging.exception(e)
ERROR:root:division by zero
Traceback (most recent call last):
File "/home/padraic/Dropbox/python/py3/size.py", line 105, in <module>
1/0
ZeroDivisionError: division by zero
Process finished with exit code 0
如果您查看文档中的failure-handling,您将看到您可以使用上下文管理器仅在您获得非零退出状态时发出警告.
Once the task list has been constructed, Fabric will start executing them as outlined in Execution strategy, until all tasks have been run on the entirety of their host lists. However, Fabric defaults to a “fail-fast” behavior pattern: if anything goes wrong, such as a remote program returning a nonzero return value or your fabfile’s Python code encountering an exception, execution will halt immediately.
This is typically the desired behavior, but there are many exceptions to the rule, so Fabric provides env.warn_only, a Boolean setting. It defaults to False, meaning an error condition will result in the program aborting immediately. However, if env.warn_only is set to True at the time of failure – with, say, the settings context manager – Fabric will emit a warning message but continue executing.
from fabric.api import settings
with settings(warn_only=True):
p = run('sudo foo')
if p.return_code == 0:
...
elif p.return_code == 1:
....
还有一个env.abort_exception:
默认值:无
Fabric normally handles aborting by printing an error message to stderr and calling sys.exit(1). This setting allows you to override that behavior (which is what happens when env.abort_exception is None.)
Give it a callable which takes a string (the error message that would have been printed) and returns an exception instance. That exception object is then raised instead of SystemExit (which is what sys.exit does.)
Much of the time you’ll want to simply set this to an exception class, as those fit the above description perfectly (callable, take a string, return an exception instance.) E.g. env.abort_exception = MyExceptionClass.
内容总结
以上是互联网集市为您收集整理的python – Fabric:处理异常,所以我可以在try块中捕获它全部内容,希望文章能够帮你解决python – Fabric:处理异常,所以我可以在try块中捕获它所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。