【问题标题】:Find if error occured in function's try/except block查找函数的 try/except 块中是否发生错误
【发布时间】:2017-09-02 00:14:28
【问题描述】:

我想使用这个函数测试多个日期的格式,然后在所有检查完成后使用 sys.exit(1) 退出,如果其中任何一个返回错误。如果多个检查中的任何一个出现错误,我该如何返回?

def test_date_format(date_string):
    try:
        datetime.strptime(date_string, '%Y%m')
    except ValueError:
        logger.error()

test_date_format("201701")
test_date_format("201702")
test_date_format("201799")

# if any of the three tests had error, sys.exit(1)

【问题讨论】:

  • 除了在函数调用之外传播异常?

标签: python-3.x try-except


【解决方案1】:

你可以返回一些指标:

def test_date_format(date_string):
    try:
        datetime.strptime(date_string, '%Y%m')
        return True
    except ValueError:
        logger.error()
        return False

error_happened = False # Not strictly needed, but makes the code neater IMHO
error_happened |= test_date_format("201701")
error_happened |= test_date_format("201702")
error_happened |= test_date_format("201799")

if error_happened:
    logger.error("oh no!")
    sys.exit(1)

【讨论】:

    【解决方案2】:

    首先,假设您将datestring 作为列表/元组。即datestring_list = ["201701", "201702", "201799"]。所以sn-p的代码如下...

    datestring_list = ["201701", "201702", "201799"]
    
    def test_date_format(date_string):
        try:
            datetime.strptime(date_string, '%Y%m')
            return True
        except ValueError:
            logger.error('Failed for error at %s', date_string)
            return False
    
    if not all([test_date_format(ds) for ds in datestring_list]):
        sys.exit(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2018-11-24
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多