python进行系统相关操作时都有点力不从心,尤其是windows下,比如获取进程的cpu、内存等等,可以通过以下方法可以达到这种要求:
1、安装pywin32、psutil这种第三方库,里面提供了很多相关的api
2、用c++写,编译成dll,把相关api导出,让python去调用
3、通过ctypes去调用windows api实现
psutil是跨平台的,不过功能比较弱,举几个例子
##根据进程名获取PID
def nametopid(x):
num=[]
for r in psutil.process_iter():
aa = str(r)
f = re.compile(x,re.I)
if f.search(aa):
num.append( aa.split('pid=')[1].split(',')[0] )
return num
print nametopid('chrome')
##根据进程名获取进程全路径
def nametopath(x):
num=[]
for i in nametopid(x):
num.append(psutil.Process(int(i)).exe())
return num
print nametopath('notepad')
##根据PID获取进程名
def pidtoname(x):
return psutil.Process(int(x)).name()
# print pidtoname('sasa')
##根据PID获取进程全路径
def pidtopath(x):
return psutil.Process(int(x)).exe()
# print pidtopath('1280')
##杀进程
def killprocess(x):
if x.isdigit():
psutil.Process(int(x)).terminate()
else:
for i in nametopid(x):
psutil.Process(int(i)).terminate()
# killprocess('notepad')
# killprocess('1111')
##杀进程树
def killprocesstree(x):
if x.isdigit():#根据pid杀
for pid in psutil.pids():
if psutil.Process(int(pid)).ppid()==int(x):
psutil.Process(int(pid)).terminate()
psutil.Process(int(x)).terminate()
else:#根据进程名杀
try:
for pid in psutil.pids():#杀子进程
if str(psutil.Process(int(pid)).ppid()) in nametopid(x): #if 'a' in theList:
psutil.Process(int(pid)).terminate()
for i in nametopid(x):#杀父进程
psutil.Process(int(i)).terminate()
except Exception,info:
return "input the right pname!"
# killprocesstree('procexp.exe')
##获取进程内存占用 , psutil does not expose the private working set
def getprocessmem(x):
if x.isdigit():
return psutil.Process(int(x)).memory_info()
else:
for i in nametopid(x):
return psutil.Process(int(i)).memory_info()
# print getprocessmem('236')
##获取进程CPU占用
def getprocesscpu(x):
if x.isdigit():
return psutil.Process(int(x)).cpu_percent(interval=1.0) / psutil.cpu_count()
else:
num=[]
for i in nametopid(x):
num.append(psutil.Process(int(i)).cpu_percent(interval=1.0) / psutil.cpu_count() )
return num