Untitled
unknown
plain_text
a year ago
1.0 kB
6
Indexable
import subprocess import time import signal 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. """ # Open a new process group for the external program pgid = os.getpgrp() process = subprocess.Popen(command, preexec_fn=os.setsid) try: # Wait for the specified time time.sleep(timeout) except KeyboardInterrupt: print("Exiting due to keyboard interrupt.") pass finally: # Send SIGKILL to the process group to kill the external program and any subprocesses os.killpg(pgid, signal.SIGKILL) if __name__ == "__main__": # Replace "your_command" with the actual command you want to run command = "your_command" # Set the desired timeout in seconds timeout = 30 # Run the command and kill it after timeout run_and_kill(command.split(), timeout) print("Process killed successfully.")
Editor is loading...
Leave a Comment