Created
September 17, 2026 10:54
-
-
Save EncodeTheCode/cca90ec1420243ae5c683ed33852512f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ```python | |
| from __future__ import annotations | |
| import asyncio | |
| import os | |
| import subprocess | |
| import sys | |
| import threading | |
| import psutil | |
| import pystray | |
| from PIL import Image, ImageDraw | |
| # ============================================================ | |
| # Applications | |
| # ============================================================ | |
| TARGETS = ( | |
| "notepad.exe", | |
| "example.exe", | |
| ) | |
| CHECK_DELAY = 2.0 | |
| NORMAL_WAIT = 8.0 | |
| FORCED_WAIT = 3.0 | |
| BETWEEN_PROCESSES = 1.0 | |
| WATCH_DELAY = 0.20 | |
| TARGET_NAMES = frozenset( | |
| value.casefold() | |
| for value in TARGETS | |
| ) | |
| CREATE_NO_WINDOW = getattr( | |
| subprocess, | |
| "CREATE_NO_WINDOW", | |
| 0, | |
| ) | |
| # ============================================================ | |
| # Tray | |
| # ============================================================ | |
| def create_tray_image() -> Image.Image: | |
| image = Image.new( | |
| "RGB", | |
| (32, 32), | |
| "white", | |
| ) | |
| draw = ImageDraw.Draw(image) | |
| draw.ellipse( | |
| (4, 4, 28, 28), | |
| fill="black", | |
| ) | |
| draw.rectangle( | |
| (15, 9, 17, 21), | |
| fill="white", | |
| ) | |
| draw.ellipse( | |
| (12, 19, 20, 27), | |
| fill="white", | |
| ) | |
| return image | |
| def create_tray( | |
| loop: asyncio.AbstractEventLoop, | |
| stop_event: asyncio.Event, | |
| ) -> pystray.Icon: | |
| icon = pystray.Icon( | |
| "Application Manager", | |
| create_tray_image(), | |
| "Application Manager", | |
| ) | |
| def exit_application( | |
| _icon: pystray.Icon, | |
| _item: pystray.MenuItem, | |
| ) -> None: | |
| loop.call_soon_threadsafe( | |
| stop_event.set | |
| ) | |
| _icon.stop() | |
| icon.menu = pystray.Menu( | |
| pystray.MenuItem( | |
| "Exit", | |
| exit_application, | |
| ) | |
| ) | |
| return icon | |
| # ============================================================ | |
| # Process discovery | |
| # ============================================================ | |
| def find_targets() -> list[tuple[int, float]]: | |
| """ | |
| Return (PID, creation_time) for every target currently running. | |
| Creation time is retained so a recycled PID cannot accidentally | |
| refer to a different process later. | |
| """ | |
| found: list[tuple[int, float]] = [] | |
| for process in psutil.process_iter( | |
| ["pid", "name", "create_time"] | |
| ): | |
| try: | |
| name = process.info["name"] | |
| if ( | |
| name | |
| and name.casefold() in TARGET_NAMES | |
| ): | |
| found.append( | |
| ( | |
| process.info["pid"], | |
| process.info["create_time"], | |
| ) | |
| ) | |
| except ( | |
| psutil.NoSuchProcess, | |
| psutil.AccessDenied, | |
| psutil.ZombieProcess, | |
| ): | |
| continue | |
| return found | |
| def get_process( | |
| pid: int, | |
| creation_time: float, | |
| ) -> psutil.Process | None: | |
| """ | |
| Re-open a PID and verify that it is still the same process. | |
| """ | |
| try: | |
| process = psutil.Process(pid) | |
| if process.create_time() != creation_time: | |
| return None | |
| return process | |
| except ( | |
| psutil.NoSuchProcess, | |
| psutil.AccessDenied, | |
| psutil.ZombieProcess, | |
| ): | |
| return None | |
| # ============================================================ | |
| # Windows termination | |
| # ============================================================ | |
| def windows_terminate( | |
| pid: int, | |
| force: bool, | |
| ) -> bool: | |
| """ | |
| Terminate exactly one PID through Windows taskkill. | |
| """ | |
| if sys.platform != "win32": | |
| return False | |
| command = [ | |
| "taskkill", | |
| "/PID", | |
| str(pid), | |
| "/T", | |
| ] | |
| if force: | |
| command.append("/F") | |
| try: | |
| result = subprocess.run( | |
| command, | |
| stdin=subprocess.DEVNULL, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| creationflags=CREATE_NO_WINDOW, | |
| check=False, | |
| ) | |
| return result.returncode == 0 | |
| except ( | |
| OSError, | |
| subprocess.SubprocessError, | |
| ): | |
| return False | |
| async def wait_for_process( | |
| pid: int, | |
| creation_time: float, | |
| seconds: float, | |
| stop_event: asyncio.Event, | |
| ) -> bool: | |
| """ | |
| Confirm that the exact original process has disappeared. | |
| """ | |
| loop = asyncio.get_running_loop() | |
| deadline = loop.time() + seconds | |
| while not stop_event.is_set(): | |
| if loop.time() >= deadline: | |
| return False | |
| process = get_process( | |
| pid, | |
| creation_time, | |
| ) | |
| if process is None: | |
| return True | |
| try: | |
| if not process.is_running(): | |
| return True | |
| except ( | |
| psutil.NoSuchProcess, | |
| psutil.AccessDenied, | |
| ): | |
| return True | |
| await asyncio.sleep(WATCH_DELAY) | |
| return False | |
| # ============================================================ | |
| # Single-process handling | |
| # ============================================================ | |
| async def terminate_one( | |
| pid: int, | |
| creation_time: float, | |
| stop_event: asyncio.Event, | |
| ) -> None: | |
| process = get_process( | |
| pid, | |
| creation_time, | |
| ) | |
| if process is None: | |
| return | |
| try: | |
| # First ask psutil/Windows to terminate the exact process. | |
| process.terminate() | |
| except ( | |
| psutil.NoSuchProcess, | |
| psutil.AccessDenied, | |
| ): | |
| return | |
| # Give the application an opportunity to exit. | |
| if await wait_for_process( | |
| pid, | |
| creation_time, | |
| NORMAL_WAIT, | |
| stop_event, | |
| ): | |
| return | |
| if stop_event.is_set(): | |
| return | |
| # Fallback through Windows taskkill for the exact PID. | |
| await asyncio.to_thread( | |
| windows_terminate, | |
| pid, | |
| True, | |
| ) | |
| # Verify the process actually disappeared. | |
| await wait_for_process( | |
| pid, | |
| creation_time, | |
| FORCED_WAIT, | |
| stop_event, | |
| ) | |
| # ============================================================ | |
| # Continuous manager | |
| # ============================================================ | |
| async def manager( | |
| stop_event: asyncio.Event, | |
| ) -> None: | |
| while not stop_event.is_set(): | |
| targets = find_targets() | |
| if targets: | |
| # One process at a time. | |
| for pid, creation_time in targets: | |
| if stop_event.is_set(): | |
| return | |
| await terminate_one( | |
| pid, | |
| creation_time, | |
| stop_event, | |
| ) | |
| if stop_event.is_set(): | |
| return | |
| await asyncio.sleep( | |
| BETWEEN_PROCESSES | |
| ) | |
| # Immediately scan again. | |
| # This catches processes that were restarted | |
| # while the previous batch was being handled. | |
| continue | |
| try: | |
| await asyncio.wait_for( | |
| stop_event.wait(), | |
| timeout=CHECK_DELAY, | |
| ) | |
| except asyncio.TimeoutError: | |
| pass | |
| # ============================================================ | |
| # Administrator elevation | |
| # ============================================================ | |
| def is_administrator() -> bool: | |
| if os.name != "nt": | |
| return False | |
| command = ( | |
| "$p = New-Object " | |
| "Security.Principal.WindowsPrincipal(" | |
| "[Security.Principal.WindowsIdentity]::GetCurrent()); " | |
| "if ($p.IsInRole(" | |
| "[Security.Principal.WindowsBuiltInRole]::Administrator" | |
| ")) { exit 0 } else { exit 1 }" | |
| ) | |
| try: | |
| result = subprocess.run( | |
| [ | |
| "powershell.exe", | |
| "-NoProfile", | |
| "-NonInteractive", | |
| "-Command", | |
| command, | |
| ], | |
| stdin=subprocess.DEVNULL, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| creationflags=CREATE_NO_WINDOW, | |
| check=False, | |
| ) | |
| return result.returncode == 0 | |
| except ( | |
| OSError, | |
| subprocess.SubprocessError, | |
| ): | |
| return False | |
| def ensure_administrator() -> None: | |
| if os.name != "nt": | |
| return | |
| if is_administrator(): | |
| return | |
| script = os.path.abspath(sys.argv[0]) | |
| arguments = subprocess.list2cmdline( | |
| [ | |
| script, | |
| *sys.argv[1:], | |
| ] | |
| ) | |
| python_path = sys.executable.replace( | |
| "'", | |
| "''", | |
| ) | |
| arguments = arguments.replace( | |
| "'", | |
| "''", | |
| ) | |
| command = ( | |
| f"Start-Process " | |
| f"-FilePath '{python_path}' " | |
| f"-Verb RunAs " | |
| f"-ArgumentList '{arguments}'" | |
| ) | |
| subprocess.Popen( | |
| [ | |
| "powershell.exe", | |
| "-NoProfile", | |
| "-NonInteractive", | |
| "-Command", | |
| command, | |
| ], | |
| stdin=subprocess.DEVNULL, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| creationflags=CREATE_NO_WINDOW, | |
| ) | |
| raise SystemExit(0) | |
| # ============================================================ | |
| # Entry point | |
| # ============================================================ | |
| async def main() -> None: | |
| loop = asyncio.get_running_loop() | |
| stop_event = asyncio.Event() | |
| tray = create_tray( | |
| loop, | |
| stop_event, | |
| ) | |
| tray_thread = threading.Thread( | |
| target=tray.run, | |
| name="SystemTray", | |
| daemon=True, | |
| ) | |
| tray_thread.start() | |
| try: | |
| await manager(stop_event) | |
| finally: | |
| tray.stop() | |
| if __name__ == "__main__": | |
| ensure_administrator() | |
| try: | |
| asyncio.run(main()) | |
| except KeyboardInterrupt: | |
| pass | |
| ``` | |
| Install the dependencies: | |
| ```text | |
| pip install psutil pystray pillow | |
| ``` | |
| The significant reliability change is that the script now tracks each target as `(PID, creation_time)` and re-validates it before termination. It also **verifies that the specific process actually disappeared** before moving to the next one, then performs another discovery pass so applications that are relaunched are handled too. | |
| One caveat: a process can refuse termination because of Windows security protections, another security boundary, or because it immediately creates a replacement process. No ordinary Python program can guarantee termination of every protected process merely by changing the API used. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment