python中一些常用函数的实现

python中一些常用函数的实现

1.   实现函数超时设置
# subprocess open wrapper(with timeout)
def SystemCallWithTimeout(command, timeout=5):
    proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    poll_seconds = 0.5
    deadline = time.time() + timeout
    while time.time() < deadline and proc.poll() == None:
        time.sleep(poll_seconds)
    if proc.poll() == None:
        return '', ''
    stdout, stderr = proc.communicate()
    return stdout, stderr
2.   获取进程的pid
#return pid if found, return 0 if not
def GetPid(processName, excludedList = [], machineIP = ''):
    cmd =''
    processName = processName.replace('[', '\[')
    processName = processName.replace(']', '\]')
    processName = '\'' + processName + '\''
    if (machineIP):
        cmd = 'ssh ' + machineIP + ' \'ps aux | grep ' + processName + '\''
    else:
        cmd = 'ps aux | grep ' + processName
    for excludeName in excludedList:
        cmd += ' | grep -v %s' %excludedName
    cmd += ' | grep -v grep | awk \'{print $2}\''
    result = SystemCall(cmd)
    if (not result):
        result = 0
    return result
3.   获取进程的cpu和memory利用率
#return process cpu and memory percentage
def GetProcessCPUMem(processName, machineIP = ''):
    cmd =''
    if (machineIP):
        cmd = 'ssh ' + machineIP + '\'ps aux | grep ' + processName + '\''
    else:
        cmd = 'ps aux | grep -w ' + processName
    cmd += ' | grep -v grep | awk \'{print $3, $6}\'';
    result = SystemCall(cmd)
    if (not result):
        error("No process: %s in machine: %s" %(processName, machineIP), True)
        return 0,0
    fst = result.split(' ')
    # cpu 100 means 1 cpu core used 100%
    # mem unit is MB
    cpu ,mem = float(fst[0]), float(fst[1])/1024.0
    return cpu, mem
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值