python - 设计健全性检查

标签 python warnings

我有一个基于 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 block 中调用该函数:

    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 的 warning mechanism .

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

关于python - 设计健全性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13217195/

相关文章:

python - NameError:未定义名称“LabelEncoder”

ios - 'imgView' 的本地声明隐藏实例变量(应用程序崩溃)

r - 当 "warnings()"出现在 R 中时中断循环

Python:安装和使用 Exscript 模块 Windows x86

python - httplib 和 HTTPs 代理

python - 在python中自定义字典迭代器

c++ - 如何处理clang中的 "exit-time destructor"警告?

ios - 当我尝试呈现 View 时收到此警告 "attempt to present ViewController whose view is not in the window hierarchy"

ruby - 如何运行所有带警告的 Ruby 脚本?

python - 在 Python 中删除 HTML 文件中的前导空格