killProcName.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Kills a process by process name
  2. #
  3. # Uses the Performance Data Helper to locate the PID, then kills it.
  4. # Will only kill the process if there is only one process of that name
  5. # (eg, attempting to kill "Python.exe" will only work if there is only
  6. # one Python.exe running. (Note that the current process does not
  7. # count - ie, if Python.exe is hosting this script, you can still kill
  8. # another Python.exe (as long as there is only one other Python.exe)
  9. # Really just a demo for the win32pdh(util) module, which allows you
  10. # to get all sorts of information about a running process and many
  11. # other aspects of your system.
  12. import win32api, win32pdhutil, win32con, sys
  13. def killProcName(procname):
  14. # Change suggested by Dan Knierim, who found that this performed a
  15. # "refresh", allowing us to kill processes created since this was run
  16. # for the first time.
  17. try:
  18. win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname)
  19. except:
  20. pass
  21. pids = win32pdhutil.FindPerformanceAttributesByName(procname)
  22. # If _my_ pid in there, remove it!
  23. try:
  24. pids.remove(win32api.GetCurrentProcessId())
  25. except ValueError:
  26. pass
  27. if len(pids)==0:
  28. result = "Can't find %s" % procname
  29. elif len(pids)>1:
  30. result = "Found too many %s's - pids=`%s`" % (procname,pids)
  31. else:
  32. handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pids[0])
  33. win32api.TerminateProcess(handle,0)
  34. win32api.CloseHandle(handle)
  35. result = ""
  36. return result
  37. if __name__ == '__main__':
  38. if len(sys.argv)>1:
  39. for procname in sys.argv[1:]:
  40. result = killProcName(procname)
  41. if result:
  42. print(result)
  43. print("Dumping all processes...")
  44. win32pdhutil.ShowAllProcesses()
  45. else:
  46. print("Killed %s" % procname)
  47. else:
  48. print("Usage: killProcName.py procname ...")