python中一些常用函数的实现
2016-12-19 22:12
381 查看
python中一些常用函数的实现
1. 实现函数超时设置
2. 获取进程的pid
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 result3. 获取进程的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
相关文章推荐
- H面试程序(0):字符串一些常用函数的实现
- Python实现的一些常用日期函数
- Python的一些常用高级函数
- 机器学习(3)-一些常用的Python3.0函数
- 一些常用字符串操作函数的内部实现
- c++ string的一些常用函数的源码以及string的简单实现
- 零基础学python-4.4 常用的一些内建函数
- 陆续一些常用函数汇编实现
- 零基础学python-2.24 一些常用函数
- python 一些常用函数笔记
- python 面向对象中一些常用内建函数【getattr(), setattr(). hasattr(). delattr()...】
- 零基础学python-2.24 一些常用函数
- 一些常用字符串操作函数的内部实现
- 一些常用函数模拟实现
- 一些常用函数模拟实现
- H面试程序(0):字符串一些常用函数的实现
- Python学习笔记——一些常用函数、常见错误总结
- Python一些不常用的函数的收集
- python中一些常用的函数命令
- 一些Linux用到的C工具集常用函数实现