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