Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a process and kill it if it doesn't end within one hour

I need to do the following in Python. I want to spawn a process (subprocess module?), and:

  • if the process ends normally, to continue exactly from the moment it terminates;
  • if, otherwise, the process "gets stuck" and doesn't terminate within (say) one hour, to kill it and continue (possibly giving it another try, in a loop).

What is the most elegant way to accomplish this?

like image 849
Federico A. Ramponi Avatar asked Aug 31 '09 20:08

Federico A. Ramponi


People also ask

How do you kill a process in python?

A process can be killed by calling the Process. kill() function. The call will only terminate the target process, not child processes.

What is the command to kill a process with process ID as 100?

Kill a Process by the kill command To terminate a process, execute the kill command followed by PID. To locate the PID of a process, use the top or ps aux command, as explained above. To kill a process having PID 5296, execute the command as follows: kill 5296.


2 Answers

The subprocess module will be your friend. Start the process to get a Popen object, then pass it to a function like this. Note that this only raises exception on timeout. If desired you can catch the exception and call the kill() method on the Popen process. (kill is new in Python 2.6, btw)

import time  def wait_timeout(proc, seconds):     """Wait for a process to finish, or raise exception after timeout"""     start = time.time()     end = start + seconds     interval = min(seconds / 1000.0, .25)      while True:         result = proc.poll()         if result is not None:             return result         if time.time() >= end:             raise RuntimeError("Process timed out")         time.sleep(interval) 
like image 66
Peter Shinners Avatar answered Oct 12 '22 22:10

Peter Shinners


There are at least 2 ways to do this by using psutil as long as you know the process PID. Assuming the process is created as such:

import subprocess subp = subprocess.Popen(['progname']) 

...you can get its creation time in a busy loop like this:

import psutil, time  TIMEOUT = 60 * 60  # 1 hour  p = psutil.Process(subp.pid) while 1:     if (time.time() - p.create_time()) > TIMEOUT:         p.kill()         raise RuntimeError('timeout')     time.sleep(5) 

...or simply, you can do this:

import psutil  p = psutil.Process(subp.pid) try:     p.wait(timeout=60*60) except psutil.TimeoutExpired:     p.kill()     raise 

Also, while you're at it, you might be interested in the following extra APIs:

>>> p.status() 'running' >>> p.is_running() True >>> 
like image 25
Giampaolo Rodolà Avatar answered Oct 12 '22 23:10

Giampaolo Rodolà