Python 判断一个进程是否存在

通常我们需要杀死一个进程首先需要判断这个进程是否存在

有返回值的函数:

复制代码
 1 def CheckProcExistByPN(process_name):
 2   try:
 3     WMI = win32com.client.GetObject('winmgmts:') 
 4     processCodeCov = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % process_name)
 5   except Exception,e:
 6     print process_name + "error : ", e;
 7   if len(processCodeCov) > 0:
 8     print process_name + " exist";
 9     return 1
10   else:
11     print process_name + " is not exist";
12     return 0
13   
14 if __name__ == '__main__':
15   CheckProcExistByPN('notepad.exe')
复制代码

无返回值的函数:

复制代码
 1 #-*- coding:utf-8 -*-
 2 
 3 import win32com.client
 4 
 5 def check_exsit(process_name):
 6     WMI = win32com.client.GetObject('winmgmts:')
 7     processCodeCov = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % process_name)
 8     if len(processCodeCov) > 0:
 9         print '%s is exists' % process_name
10     else:
11         print '%s is not exists' % process_name
12 
13 if __name__ == '__main__':
14     check_exsit('notepad.exe')
15  
复制代码

你可能感兴趣的:(操作系统,Python)