【问题标题】:Design a sanity check设计健全性检查
【发布时间】:2012-11-04 08:35:55
【问题描述】:

我有一个基于 GUI 的项目。我想把它放到代码本身和 GUI 部分。

这是我的代码: Main.py:

class NewerVersionWarning(Exception):
    def __init__(self, newest, current=__version__):
        self.newest = newest
        self.current = current
    def __str__(self):
        return "Version v%s is the latest version. You have v%s." % (self.newest, self.current)

class NoResultsException(Exception):
    pass

# ... and so on
def sanity_check():
    "Sanity Check for script."
    try:
        newest_version = WebParser.WebServices.get_newestversion()
        if newest_version > float(__version__):
            raise NewerVersionWarning(newest_version)
    except IOError as e:
        log.error("Could not check for the newest version (%s)" % str(e))

    if utils.get_free_space(config.temp_dir) < 200*1024**2: # 200 MB
        drive = os.path.splitdrive(config.temp_dir)[0]
        raise NoSpaceWarning(drive, utils.get_free_space(config.temp_dir))

# ... and so on

现在,在 GUI 部分,我只是在 try-except 块中调用函数:

    try:
        Main.sanity_check()
    except NoSpaceWarning, e:
        s = tr("There are less than 200MB available in drive %s (%.2fMB left). Application may not function properly.") % (e.drive, e.space/1024.0**2)
        log.warning(s)
        QtGui.QMessageBox.warning(self, tr("Warning"), s, QtGui.QMessageBox.Ok)
    except NewerVersionWarning, e:
        log.warning("A new version of iQuality is available (%s)." % e.newest)
        QtGui.QMessageBox.information(self, tr("Information"), tr("A new version of iQuality is available (%s). Updates includes performance enhancements, bug fixes, new features and fixed parsers.<br /><br />You can grab it from the bottom box of the main window, or from the <a href=\"%s\">iQuality website</a>.") % (e.newest, config.website), QtGui.QMessageBox.Ok)

在当前设计中,检查在第一个警告/异常时停止。当然,异常应该停止代码,但警告应该只向用户显示一条消息,然后继续。我怎么能这样设计呢?

【问题讨论】:

  • 一种简单的方法是在遇到警告时不引发异常(将其添加到警告列表或其他内容中)。 Python 在 IMO 中使用异常的方式过于宽松,当有更简单的解决方案可用时,它会限制人们使用异常。

标签: python sanity-check


【解决方案1】:

也许你应该看看 Python 的warning mechanism

它应该允许您在不停止程序的情况下警告用户危险情况。

【讨论】:

    【解决方案2】:

    尽管 python 提供了警告机制,但我发现这样做更容易:

    1. Warning 类的子类警告。
    2. 使用_warnings 列表并将所有警告附加到它。
    3. 返回_warnings并在外部代码处处理:

      try:
          _warnings = Main.sanity_check()
      except CustomException1, e:
          # handle exception
      except CustomException2, e:
          # handle exception
      
      for w in _warnings:
          if isinstance(w, NoSpaceWarning):
              pass # handle warning
          if isinstance(w, NewerVersionWarning):
              pass # handle warning
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2015-04-10
      • 1970-01-01
      相关资源
      最近更新 更多