设计一个健全的ch

2024-10-01 09:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基于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块中的函数:

^{pr2}$

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


Tags: 代码selfconfiggetversiondefdirexception
2条回答

也许你应该看看Python的warning mechanism。在

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

尽管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
    

相关问题 更多 >