Kill or terminate subprocess when timeout?

前端 未结 5 474
迷失自我
迷失自我 2020-12-01 02:24

I would like to repeatedly execute a subprocess as fast as possible. However, sometimes the process will take too long, so I want to kill it. I use signal.signal(...) like

5条回答
  •  半阙折子戏
    2020-12-01 02:55

    Here is something I wrote as a watchdog for subprocess execution. I use it now a lot, but I'm not so experienced so maybe there are some flaws in it:

    import subprocess
    import time
    
    def subprocess_execute(command, time_out=60):
        """executing the command with a watchdog"""
    
        # launching the command
        c = subprocess.Popen(command)
    
        # now waiting for the command to complete
        t = 0
        while t < time_out and c.poll() is None:
            time.sleep(1)  # (comment 1)
            t += 1
    
        # there are two possibilities for the while to have stopped:
        if c.poll() is None:
            # in the case the process did not complete, we kill it
            c.terminate()
            # and fill the return code with some error value
            returncode = -1  # (comment 2)
    
        else:                 
            # in the case the process completed normally
            returncode = c.poll()
    
        return returncode   
    

    Usage:

     return = subprocess_execute(['java', '-jar', 'some.jar'])
    

    Comments:

    1. here, the watchdog time out is in seconds; but it's easy to change to whatever needed by changing the time.sleep() value. The time_out will have to be documented accordingly;
    2. according to what is needed, here it maybe more suitable to raise some exception.

    Documentation: I struggled a bit with the documentation of subprocess module to understand that subprocess.Popen is not blocking; the process is executed in parallel (maybe I do not use the correct word here, but I think it's understandable).

    But as what I wrote is linear in its execution, I really have to wait for the command to complete, with a time out to avoid bugs in the command to pause the nightly execution of the script.

提交回复
热议问题