2017-09-01 74 views
1

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

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) 
+1

除了在函数调用外传播异常吗? –

回答

0

你可以返回一些指标:

所有的
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) 
0

首先,让我们假设你有datestring的列表/元组。即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) 
相关问题