22import  glob 
33
44import  pystache 
5+ import  time 
6+ import  random 
57
68from  snippet .config  import  Config 
79from  snippet .logs  import  logger 
@@ -28,8 +30,18 @@ def write_example(config: Config, example_name, example_block):
2830 os .makedirs (config .output_dir )
2931 output_file  =  os .path .join (config .output_dir , output_file_name )
3032 logger .info ('writing %r to %s' , example_name , output_file )
31-  with  open (output_file , 'a'  if  config .output_append  else  'w' ) as  fh :
32-  fh .write (output )
33+  for  i  in  range (1 , config .write_attempts  +  1 ):
34+  # we run a retry loop as there may be contention on the output file in 
35+  # a multi-process environment 
36+  try :
37+  with  open (output_file , 'a'  if  config .output_append  else  'w' ) as  fh :
38+  fh .write (output )
39+  break 
40+  except  IOError  as  err :
41+  time .sleep (i  *  0.5  +  0.1  *  random .randint (0 , 5 ))
42+  logger .info ('write failed (%s) retrying attempt: %s' , err , i )
43+  else :
44+  raise  IOError ('could not write output file after %s attempts'  %  config .write_attempts )
3345
3446
3547def  load_file_lines (path ):
0 commit comments