1. import psutil
  2. import time
  3. import logging
  4. import os
  5. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  6. def teardown_processes(process_arrays, retry_interval=1):
  7. """
  8. Tear down processes from given arrays with retry intervals.
  9. Args:
  10. process_arrays (list of lists): A list of lists, where each inner list
  11. contains process names to terminate.
  12. retry_interval (int): The interval (in seconds) between retry attempts.
  13. """
  14. for process_list in process_arrays:
  15. for process_name in process_list:
  16. max_retries = 5 # Set a maximum number of retries
  17. retries = 0
  18. while retries < max_retries:
  19. try:
  20. for proc in psutil.process_iter(['name']):
  21. if proc.info['name'] == process_name:
  22. proc.kill()
  23. logging.info(f"Killed process: {process_name}")
  24. break # Exit inner loop after killing the process
  25. else:
  26. logging.warning(f"Process {process_name} not found.")
  27. break # exit retry loop if process not found
  28. break # Exit outer loop if process is killed
  29. except psutil.NoSuchProcess:
  30. logging.warning(f"Process {process_name} already terminated.")
  31. break
  32. except Exception as e:
  33. logging.error(f"Error terminating process {process_name}: {e}")
  34. retries += 1
  35. if retries < max_retries:
  36. time.sleep(retry_interval)
  37. if __name__ == '__main__':
  38. # Example usage
  39. process_arrays = [
  40. ['my_process_1', 'my_process_2'],
  41. ['another_process']
  42. ]
  43. teardown_processes(process_arrays, retry_interval=0.5)

Add your comment