查找函数的 try/except 块中是否发生错误

Find if error occured in function's try/except block

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

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)

您可以return一些指标:

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)

首先,假设您有 datestring 作为 list/tuple。即datestring_list = ["201701", "201702", "201799"]。所以代码片段如下...

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)