2016-04-02 17 views
0

Sadece böyle bir şey arıyordu:C# sürümüne benzeyen şık bir Python yeniden kullanılabilir bekle var mı?

public static class Retry 
{ 
    public static void Do(
     Action action, 
     TimeSpan retryInterval, 
     int retryCount = 3) 
    { 
     Do<object>(() => 
     { 
      action(); 
      return null; 
     }, retryInterval, retryCount); 
    } 

    public static T Do<T>(
     Func<T> action, 
     TimeSpan retryInterval, 
     int retryCount = 3) 
    { 
     var exceptions = new List<Exception>(); 

     for (int retry = 0; retry < retryCount; retry++) 
     { 
      try 
      { 
       if (retry > 0) 
        Thread.Sleep(retryInterval); 
       return action(); 
      } 
      catch (Exception ex) 
      { 
       exceptions.Add(ex); 
      } 
     } 

     throw new AggregateException(exceptions); 
    } 
} 

bu görevinden:

Cleanest way to write retry logic? Birisi bazı ipuçları varsa bu gerçekten güzel olabileceğini öğrenmek Python yeterli iyi değilim. Bu, test kodunun çok sık görüldüğü, ancak nadiren zarif bir şekilde ele alındığı bir test kodudur.

+1

Bu [** Yeniden deneme **] (https://pypi.python.org/pypi/ Yeniden deneme/paket paketi istediğiniz gibi olabilir. – Anzel

cevap

0

Sen lütfen senin kadar istisna işleme ve diğer çan ve ıslık ekleyerek, böyle bir şey yapabilirsiniz:

def retry_fn(retry_count, delay, fn, *args, *kwargs): 
    retry = True 
    while retry and retry_count: 
     retry_count -= 1 
     success, results = fn(*args, **kwargs): 
     if success or not retry_count: 
      return results 
     time.sleep(delay) 
İlgili konular