2017-09-01 33 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)