"""Kill processes lasting more than a specified number of minutes.""" import psutil import time PROCESS = 'chrome' USER = 'selenium' MAX_MINUTES = 20 def kill_chrome_processes(name, username, max_time_in_minutes): """Find and kills processes running longer than a specified time.""" for proc in psutil.process_iter(): try: if proc.name() == name and proc.username() == username: print(proc) time_running = time.time() - proc.create_time() if time_running > max_time_in_minutes * 60: kill_proc = proc.kill() return kill_proc except Exception as e: print(e) kill_chrome_processes(PROCESS, USER, MAX_MINUTES)