【问题标题】:Print Python Exception Type (Raised in Fabric)打印 Python 异常类型(在 Fabric 中引发)
【发布时间】:2013-07-21 05:32:52
【问题描述】:

我正在使用 Fabric 进行自动化,包括创建目录的任务。这是我的 fabfile.py:

#!/usr/bin/env python
from fabric.api import *

def init():
    try:
        local('mkdir ./www')
    except ##what exception?##:
        #print exception name to put in above

运行 fab fabfile.py 并且 f 我已经有 ./www 创建了一个错误,但我不知道是什么类型的,所以我还不知道如何处理错误。 Fabric 只打印出以下内容:

mkdir: cannot create directory ‘./www’: File exists

Fatal error: local() encountered an error (return code 1) while executing 'mkdir ./www'

Aborting.

我想要做的是能够找出错误类型,这样我就可以在没有笼统陈述的情况下正确排除我的错误。如果答案不仅告诉我如何处理mkdir 异常,而且打印(或以其他方式找到名称)any 我可能会遇到的异常(mkdir只是一个例子)。

谢谢!

【问题讨论】:

标签: python exception python-2.7 exception-handling


【解决方案1】:

问题在于fabric 使用子流程来做这些事情。如果您查看local 的源代码,您会发现它实际上并没有引发异常。它调用 suprocess.Popen 并使用communicate() 读取标准输出和标准错误。如果有一个非零返回码,那么它会返回对warnabort 的调用。默认值为中止。所以,做你想做的事,试试这个:

def init():
    with settings(warn_only=True):
        local('mkdir ./www')

如果您查看abort 的来源,它看起来像这样:

 10 def abort(msg):
 21     from fabric.state import output
 22     if output.aborts:
 23         sys.stderr.write("\nFatal error: %s\n" % str(msg))
 24         sys.stderr.write("\nAborting.\n")
 25     sys.exit(1)

因此,异常将是 SystemExit 异常。虽然您可以抓住这一点,但上面使用settings 概述了正确的方法。

【讨论】:

  • 如果它保存了别人的谷歌搜索:从 fabric.api 导入设置
【解决方案2】:

无异常处理,来自fabric api

尝试将整个脚本的 warn_only 设置为 true

  env.warn_only = True

【讨论】:

    【解决方案3】:

    通常,当您遇到未捕获的异常时,Python 会打印异常类型以及错误消息:

    >>> raise IOError("Error message.")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IOError: Error message.
    

    如果没有发生这种情况,您可能根本没有遇到异常。

    如果你真的想捕获任意异常并打印它,你想捕获ExceptionBaseExceptionBaseException 甚至会包含 KeyboardInterrupt 这样的东西,所以要小心。

    def init():
    try:
        local('mkdir ./www')
    except BaseException as e:
        print "local() threw a", type(e).__name__
        raise # Reraise the exception
    

    【讨论】:

      【解决方案4】:

      一般:

          try:
              some_code()
          except Exception, e:
              print 'Hit An Exception', e
              raise
      

      会告诉您异常是什么,但如果您不打算实际处理一些异常,那么只需摆脱 try: except: 行将具有完全相同的效果。

      此外,如果您在调试器下运行代码,则可以更详细地查看遇到的异常。

      【讨论】:

        【解决方案5】:
        def init():
            try:
                local('mkdir ./www')
            except Exception as e:
                print e.__class__.__name__
        

        仅此而已!

        编辑:重新阅读您的问题并意识到我的代码只会在您的情况下打印“致命”。看起来fabric正在抛出一个错误并返回他们自己的错误代码,所以你必须查看文档。我对面料没有任何经验,所以如果你还没有的话,我建议你看看here。对不起,如果这没有帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-01
          • 2019-09-22
          • 2017-05-26
          • 2011-05-14
          • 2021-10-14
          相关资源
          最近更新 更多