Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
908 B
1
Indexable
Never
import subprocess
import time
import signal
import psutil 

def run_and_kill(command, timeout):
  """
  Runs a command-line process and kills it after a specified timeout.

  Args:
      command: The command string to execute.
      timeout: The time in seconds to wait before killing the process.
  """
  process = subprocess.Popen(command)

  def kill_descendants(parent_pid):
      try:
          parent = psutil.Process(parent_pid)
          children = parent.children(recursive=True)
          for child in children:
              child.kill()
          parent.kill()
      except psutil.NoSuchProcess:
          return

  try:
    # Wait for the specified time
    time.sleep(timeout)
  except KeyboardInterrupt:
    print("Exiting due to keyboard interrupt.")
    pass
  finally:
    # Kill the process and its descendants 
    kill_descendants(process.pid)

# ...rest of the script remains the same

Leave a Comment