subprocess如何设置命令超时时间

一、subprocess如何设置命令超时时间

最近遇到一个问题,就是我需要在服务器上执行某些shell命令,但是有些命令失败的时候是不会自动终止的,只会一直停在那里,很耗时间。

因此想到了设置超时时间,而 subprocess 模块是没有超时功能的。至于为什么不用其他模块执行shell命令,因为subprocess比较安全。

 

这时我一开始想到的是使用 multiprocessing.Process 进程的守护进程去实现的,但是发现还是很low而且实现不好。

后面就突然想到了定时器,线程模块有,于是:

import subprocess
from threading import Timer


def kill_command(p):
    """终止命令的函数"""
    p.kill()


def execute(command, timeout):
    # 执行shell命令
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # 设置定时器去终止这个命令
    timer = Timer(timeout, kill_command, [p])

    try:
        timer.start()
        stdout, stderr = p.communicate()
        return_code = p.returncode
        print(return_code)
        print(stdout)
        print(stdout)
    except Exception as ex:
        print(ex)
    finally:
        timer.cancel()

 

posted @ 2020-12-15 22:30  我用python写Bug  阅读(5760)  评论(0编辑  收藏  举报