dmypy_os.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from __future__ import annotations
  2. import sys
  3. from typing import Any, Callable
  4. if sys.platform == "win32":
  5. import ctypes
  6. import subprocess
  7. from ctypes.wintypes import DWORD, HANDLE
  8. PROCESS_QUERY_LIMITED_INFORMATION = ctypes.c_ulong(0x1000)
  9. kernel32 = ctypes.windll.kernel32
  10. OpenProcess: Callable[[DWORD, int, int], HANDLE] = kernel32.OpenProcess
  11. GetExitCodeProcess: Callable[[HANDLE, Any], int] = kernel32.GetExitCodeProcess
  12. else:
  13. import os
  14. import signal
  15. def alive(pid: int) -> bool:
  16. """Is the process alive?"""
  17. if sys.platform == "win32":
  18. # why can't anything be easy...
  19. status = DWORD()
  20. handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
  21. GetExitCodeProcess(handle, ctypes.byref(status))
  22. return status.value == 259 # STILL_ACTIVE
  23. else:
  24. try:
  25. os.kill(pid, 0)
  26. except OSError:
  27. return False
  28. return True
  29. def kill(pid: int) -> None:
  30. """Kill the process."""
  31. if sys.platform == "win32":
  32. subprocess.check_output(f"taskkill /pid {pid} /f /t")
  33. else:
  34. os.kill(pid, signal.SIGKILL)