python运行shell超时退出

执行的是后台shell命令操作,这里有一个超时退出操作

import time
import subprocess
import sys


# 超时异常类
class TimeOutError(Exception):
    def __init__(self, *args, **kwargs):
        self.message = "The Command timeout."
        pass


# 超时控制
def executeCMD(cmd, timeout=60):
    """执行命令cmd,返回命令输出的内容。
    如果超时将会抛出TimeoutError异常。
    cmd - 要执行的命令
    timeout - 最长等待时间,单位:秒
    """
    print("time start.command timeout =", str(timeout))
    p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, shell=True)
    t_beginning = time.time()
    while True:
        if p.poll() is not None:
            if p.returncode != 0:
                print(p.returncode)
                sys.exit(9)
            break
        seconds_passed = time.time() - t_beginning
        if timeout and seconds_passed > timeout:
            p.kill()
            print("timeout.command will be kill. 任务已超时,已经被kill...")
            raise TimeOutError(cmd, timeout)
        time.sleep(1)


cmd = 'python3 /tmp/timeout_kill/a.py'
executeCMD(cmd)

如果完善其他程序,可以在这个基础上进行封装

posted @ 2022-04-26 14:30  醉城、  阅读(761)  评论(0编辑  收藏  举报