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