【问题标题】:code is cluttered by try-except in Python代码被 Python 中的 try-except 弄乱了
【发布时间】:2015-02-27 12:06:09
【问题描述】:

我有一系列处理大量文本的过程。 该过程可能会因任何原因而失败。

如果我想记录每个进程的失败,我应该使用try-except子句吗? 问题是我的代码被 try-except 压得喘不过气来,主要流程被分割成碎片。

for path in paths:
    with open(path) as file:
        text=file.read()
        try:
            process1(text)
        except Exception as e:
            handle e
            record_failure( process1 , file.name)
            continue

        try:
            process2(text)
        except Exception as e:
            handle e
            record_failure( process2 , file.name)
            continue
        .
        .
        .
        processN

或者我以后应该在异常日志文件中分析,我认为这并不容易。

有没有更好的方法来解决这个问题?

【问题讨论】:

  • 将所有进程放在一个列表中,迭代并尝试一次/除外

标签: python exception logging decorator contextmanager


【解决方案1】:

您可以将所有进程置于一个循环中:

allProcs = [process1, process2, processN]

for path in paths:
    with open(path) as file:
        text=file.read()
        for proc in allProcs:
            try:
                proc(text)
            except Exception as e:
                # handle e
                record_failure( proc , file.name)
                continue

【讨论】:

    最近更新 更多