Untitled
unknown
plain_text
2 years ago
908 B
9
Indexable
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
Editor is loading...
Leave a Comment