killthreads.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import psutil
  2. import os
  3. import ctypes,inspect
  4. import traceback
  5. def _async_raise(tid, exctype):
  6. """raises the exception, performs cleanup if needed"""
  7. tid = ctypes.c_long(tid)
  8. if not inspect.isclass(exctype):
  9. exctype = type(exctype)
  10. res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
  11. if res == 0:
  12. raise ValueError("invalid thread id")
  13. elif res != 1:
  14. ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
  15. raise SystemError("PyThreadState_SetAsyncExc failed")
  16. def stop_thread(thread):
  17. if isinstance(thread,(int)):
  18. _ident = thread
  19. else:
  20. _ident = thread.ident
  21. print(_ident)
  22. _async_raise(_ident, SystemExit)
  23. for pid in [124564]:
  24. try:
  25. proc = psutil.Process(pid)
  26. exeFile = os.path.basename(proc.exe())
  27. threads = psutil._psutil_windows.proc_threads(pid)
  28. times = 0
  29. for thread in threads:
  30. print(thread)
  31. stop_thread(thread[0])
  32. for timeUsed in thread[1:]:
  33. times += timeUsed
  34. print('='*20)
  35. print('Exe file:', os.path.basename(proc.exe()))
  36. print('Number of threads:', len(threads))
  37. print('Time used:', times)
  38. except:
  39. traceback.print_exc()