2017-09-01 3 views
1

Je souhaite tester le format de plusieurs dates à l'aide de cette fonction, puis sys.exit (1) pour quitter après toutes les vérifications si l'une d'entre elles a renvoyé une erreur. Comment puis-je retourner si l'un de plusieurs chèques comportait une erreur?Rechercher si une erreur s'est produite dans le bloc try/except de la fonction

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

À part propager l'exception en dehors de l'appel de fonction? –

Répondre

0

Vous pouvez retourner un indicateur:

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

Tout d'abord, laisse supposer que vous avez la liste datestring/tuple. c'est-à-dire datestring_list = ["201701", "201702", "201799"]. Donc l'extrait de code est comme suit ...

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)