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

前端 未结 5 894
猫巷女王i
猫巷女王i 2020-12-05 00:51

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
5条回答
  •  死守一世寂寞
    2020-12-05 01:49

    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
    >>>
    

提交回复
热议问题